Basics of File Handling in C Programming

File Handling is the storing of data in a file using a program. In C programming language, the programs store results, and other data of the program to a file using file handling in C. Also, we can extract/fetch data from a file to work with it in the program.
The operations that you can perform on a File in C are −
Creating a new file
Creating a new file
Opening an existing file
Opening an existing file
Reading data from an existing file
Reading data from an existing file
Writing data to a file
Writing data to a file
Moving data to a specific location on the file
Moving data to a specific location on the file
Closing the file
Closing the file
The fopen() function is used to create a new file or open an existing file in C. The fopen function is defined in the stdio.h header file.
Now, lets see the syntax for creation of a new file or opening a file
file = fopen(“file_name”, “mode”)
This is a common syntax for both opening and creating a file in C.
file_name − It is a string that specifies the name of the file that is to be opened or created using the fopen method. mode: It is a string (usually a single character ) that specifies the mode in which the file is to be opened. There are various modes available to open a file in C, we will learn about all of them later in this article.
The fopen function will create a new file when it will not find any file of the specified name in the specified location. Else, if the file is found it will be opened with the mode specified.
Let’s see can example which will make the concept clear,
Suppose we are opening a file named hello.txt using the fopen function. The following will be the statement,
file = fopen(“hello.txt”, “w”)
This will search for a file named hello.txt in the current directory. If the file exists, it will open the file otherwise it will create a new file named “hello.txt” and open it with write mode (specified using “w”).
Now, let’s see all types of modes that are available for us to read or write a file in C, and see code snippets that will show sample runs of the code.
Mode = “r” − open for reading, this mode will open the file for reading purpose only, i.e. the contents can only be viewed, nothing else like edits can be done to it.
This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "r")){
      printf("File opened successfully in read mode");
   }
   else
   printf("The file is not present! cannot create a new file using r mode");
   fclose(file);
   return 0;
}
File opened successfully in read mode
We have created a file named hello.txt in our current directory but if we try to access other file then we will get “The file is not present! cannot create a new file using r mode” as output.
Mode = “rb” − open for reading in binary mode, this mode will open the file for reading in binary mode only, i.e. the contents can only be viewed and nothing else like edits can be done to it.
This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("program.txt", "rb")){
      printf("File opened successfully in read mode");
   }
   else
   printf("The file is not present! cannot create a new file using rb mode");
   fclose(file);
   return 0;
}
The file is not present! cannot create a new file using rb mode
Mode = “w” − open for writing only, this mode will open the file if present in the current directory for writing only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing.
If we open a file that contains some text in it, the contents will be overwritten.
 Live Demo
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("helo.txt", "w")){
      printf("File opened successfully in write mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}
File opened successfully in write mode or a new file is created
You can see here, we have tried to open file “helo.txt” which is not present in the directory, still the function returned the success message because it has create a file named “helo.txt”.
Mode = “wb” − open for writing in binary mode, this mode will open the file if present in the current directory for writing in binary mode i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing in binary mode.
If we open a file that contains some text in it, the contents will be overwritten.
 Live Demo
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "wb")){
      printf("File opened successfully in write in binary mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}
File opened successfully in write in binary mode or a new file is created
Mode = “a” − open for append only, this mode will open the file if present in the current directory for writing only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing. If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
 Live Demo
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "a")){
      printf("File opened successfully in append mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}
File opened successfully in append mode or a new file is created
Mode = “ab” − open for append in binary, this mode will open the file if present in the current directory for writing in binary only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing in binary.
If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
 Live Demo
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "ab")){
      printf("File opened successfully in append in binary mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}
File opened successfully in append in binary mode or a new file is created
Mode = “r+” − open for reading and writing both, this mode will open the file for both reading and writing purposes i.e. both read and write operations can be performed to the file.
This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.
If we open a file that contains some text in it and write something, the contents will be overwritten.
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "r+")){
      printf("File opened successfully in read and write both");
   }
   else
   printf("The file is not present! cannot create a new file using r+ mode");
   fclose(file);
   return 0;
}
File opened successfully in read and write both
We have created a file named hello.txt in our current directory but if we try to access another file then we will get “The file is not present! cannot create a new file using r+ mode” as output.
Mode = “rb+” − open for reading in binary mode, this mode will open the file for reading in binary mode only, i.e. the contents can only be viewed and nothing else like edits can be done to it.
This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.
If we open a file that contains some text in it and write something, the contents will be overwritten.
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("program.txt", "rb+")){
      printf("File opened successfully in read mode");
   }
   else
   printf("The file is not present! cannot create a new file using rb+ mode");
   fclose(file);
   return 0;
}
The file is not present! cannot create a new file using rb+ mode
Mode = “w” − open for writing and reading, this mode will open the file if present in the current directory for writing and reading operation both. If the file is not present in the current directory, the program will create a new file and open it for reading and writing.
If we open a file that contains some text in it, the contents will be overwritten.
 Live Demo
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("helo.txt", "w+")){
      printf("File opened successfully in read-write mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}
File opened successfully in read-write mode or a new file is created
You can see here, we have tried to open file “helo.txt” which is not present in the directory, still the function returned the success message because it has create a file named “helo.txt”.
Mode = “wb+” : open for writing and reading in binary mode, this mode will open the file if present in the current directory for writing and reading in
binary mode. If the file is not present in the current directory, the program will create a new file and open it for reading and writing in binary mode.
If we open a file that contains some text in it, the contents will be overwritten.
 Live Demo
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "wb+")){
      printf("File opened successfully in read-write in binary mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}
File opened successfully in read-write in binary mode or a new file is created
Mode = “a+” − open for read and append, this mode will open the file if present in the current directory for both reading and writing. If the file is not present in the current directory, the program will create a new file and open it for reading and writing.
If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
 Live Demo
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "a+")){
      printf("File opened successfully in read-append mode or a new file is created");
   }
   else
   printf("Error!");
   fclose(file);
   return 0;
}
File opened successfully in read-append mode or a new file is created
Mode = “ab+” − open for read and append in binary, this mode will open the file if present in the current directory for both reading and writing in binary. If the file is not present in the current directory, the program will create a new file and open it for reading and writing in binary. If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "ab+")){
      printf("File opened successfully in read-append in binary mode or a new file is created");
   }
   else
   printf("Error!”);
   fclose(file);
   return 0;
}
File opened successfully in read-append mode or a new file is created
We can read content of a file in c using the fscanf() and fgets() and fgetc() functions. All are used to read contents of a file.
Let’s see the working of each of the function −
The fscanf() function is used to read character set i.e strings from the file. It returns the EOF, when all the content of the file are read by it.
int fscanf(FILE *stream, const char *charPointer[])
FILE *stream: the pointer to the opened file.
const char *charPointer[]: string of character.
#include <stdio.h>
int main(){
   FILE * file;
   char str[500];
   if (file = fopen("hello.txt", "r")){
         while(fscanf(file,"%s", str)!=EOF){
         printf("%s", str);
      }
   }
   else
   printf("Error!”);
   fclose(file);
   return 0;
}
LearnprogrammingattutorialsPoint
The fget() function in C is used to read string from the stream.
char* fgets(char *string, int length, FILE *stream)
char *string: It is a string which will store the data from the string.
int length: It is an int which gives the length of string to be considered.
FILE *stream: It is the pointer to the opened file.
#include <stdio.h>
int main(){
   FILE * file;
   char str[500];
   if (file = fopen("hello.txt", "r")){
      printf("%s", fgets(str, 50, file));
   }
   fclose(file);
   return 0;
}
Learn programming at tutorials Point
The fgetc() function in C is used to return a single character from the file. It gets a character from the file and returns EOF at the end of file.
char* fgetc(FILE *stream)
FILE *stream: It is the pointer to the opened file.
#include <stdio.h>
int main(){
   FILE * file;
   char str;
   if (file = fopen("hello.txt", "r")){
      while((str=fgetc(file))!=EOF)
      printf("%c",str);
   }
   fclose(file);
   return 0;
}
Learn programming at tutorials Point
We can write data to a file in C using the fprintf(), fputs(), fputc() functions. All are used to write contents to a file.
Let’s see the working of each of the function −
The fprintf() function is used to write data to a file. It writes a set of characters in a file.
int fprintf(FILE *stream, char *string[])
FILE for *stream: It is the pointer to the opened file.
char *string[]: It is the character array that we want to write in the file.
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "w")){
      if(fprintf(file, "tutorials Point”) >= 0)
      printf("Write operation successful");
   }
   fclose(file);
   return 0;
}
Write operation successful
The fputf() function in C can be used to write to a file. It is used to write a line (character line) to the file.
int fputs(const char *string, FILE *stream)
Constant char *string[]: It is the character array that we want to write in the file.
FILE for *stream: It is the pointer to the opened file.
 Live Demo
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "w")){
      if(fputs("tutorials Point", file) >= 0)
      printf("String written to the file successfully...");
   }
   fclose(file);
   return 0;
}
String written to the file successfully...
The fputc() function is used to write a single character to the file.
int fputc(char character , FILE *stream)
char character : It is the character that we want to write in the file.
FILE for *stream: It is the pointer to the opened file.
 Live Demo
#include <stdio.h>
int main(){
   FILE * file;
   if (file = fopen("hello.txt", "w")){
      fputc('T', file);
   }
   fclose(file);
   return 0;
}
‘T’ is written to the file.
The fclose() function is used to close the open file. We should close the file after performing operations on it to save the operations that we have applied to it.
fclose(FILE *stream)
FILE for *stream: It is the pointer to the opened file.
 Live Demo
#include <stdio.h>
int main(){
   FILE * file;
   char string[300];
   if (file = fopen("hello.txt", "a+")){
      while(fscanf(file,"%s", string)!=EOF){
         printf("%s", string);
      }
      fputs("Hello", file);
   }
   fclose(file);
   return 0;
}
LearnprogrammingatTutorialsPoint
Learn programming at Tutorials PointHello