File Handling in C
File Handling in C
File Handling in C
File handling in C enables us to create, update, read, and delete the files stored on the
local file system through our C program. The following operations can be performed
on a file.
Mode Description
r opens a text file in read mode
0w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
o file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
For performing the operations on the file, a special pointer called File pointer
is used which is declared as
FILE *filePointer;
So, the file can be opened as
filePointer = fopen(“fileName.txt”, “w”)
The second parameter can be changed to contain all the attributes listed in
the above table.
Reading from a file –
The file read operations can be performed using functions fscanf or fgets.
Both the functions performed the same operations as that of scanf and gets
but with an additional parameter, the file pointer. So, it depends on you if
you want to read the file line by line or character by character.
And the code snippet for reading a file is as:
FILE * filePointer;
Writing a file –:
The file write operations can be performed by the functions fprintf and fputs
with similarities to read operations. The snippet for writing to a file is as :
FILE *filePointer ;
filePointer = fopen(“fileName.txt”, “w”);
fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2012);
Closing a file –:
After every successful file operations, you must always close a file. For
closing a file, you have to use fclose function. The snippet for closing a file is
given as :
FILE *filePointer ;
filePointer= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(filePointer)
Program to Open a File, Read from it, And Close the File
# include <stdio.h>
# include <string.h>
int main( )
{
// Declare the file pointer
FILE *filePointer ;
#include<conio.h>
int main( )
{
// Declare the file pointer
FILE *filePointer ;
// Get the data to be written in file
char dataToBeWritten[50]
= "GeeksforGeeks-A Computer Science Portal for Geeks";
OUTPUT:
The file is now opened.