C File Handling

We have learned lots of things in c programming, accept user input, execute, and print results on the terminal(output) window. But results are not store permanently, to store data for future reference we are using file handling in c language. Now, instead of accepting input and printing results from the terminal, we will use a file in c to accept input and store results. Accepting input from the file is called reading and printing output in a file is called writing in c language.

What is a File?

The File is a collection of bytes, and it is permanently stored in computer’s secondary memory. There are two types of file in c.

  1. Text File: Text files are normal .txt files, that store information in ASCII format. The user can directly open that file and can read easily.
  2. Binary File: Binary files store information in the binary format (0 or 1). Not user readable.

Basic File Operation in C Language.

When you are working with the file in c, you need to declare a pointer variable of FILE type to store file reference during reading or write operation. Below you can check basic file operation in c.

  • Open or create a File.
  • Read or Write a File.
  • Close the File.

Example 1: C program to write user input in a File.

#include<stdio.h>
int main()
{
FILE *fp;	//declaring a file pointer to store file reference.
char month[20];
	fp=fopen("first.txt","w");	// opening a file in write mode.
	printf("\nEnter Month: ");
	scanf("%s",month);
	fprintf(fp,"%s",month);	//writing text in a file.
	fclose(fp);	//closinfg file.
return 0;
}

FILE *fp – Here we are declaring a pointer variable of FILE type to store file reference in c programming.

fp=fopen(“first.txt”,”w”) – To open a file for read/write fopen(“file”,”mode”) function is used.

fprintf(fp,”%s”,weekday) – To write formated output in file, fprintf(file_pointer,”format”,text) function is used.

fclose(fp) – Every file must be close after read or write operation using fclose() function in c.

So, in the above c code first, we create a file pointer, open a file to write, after that write string into a file, and finally close the file.

Example 2: C program to read text from a File.

#include<stdio.h>
int main()
{
FILE *fp;	//declaring a file pointer to store file reference.
char month[20];
	fp=fopen("first.txt","r");	// opening file in read mode.
	fscanf(fp,"%s",month);	//reading from file.
	printf("\nMonth : %s",month);
	fclose(fp);	//closinfg file.
return 0;
}