Basics of File Handling in C - GeeksforGeeks
Basics of File Handling in C - GeeksforGeeks
Basics of File Handling in C - GeeksforGeeks
Types of Files in C
A file can be classified into two types based on the way the file stores
the data. They are as follows:
Text Files
Binary Files
1. Text Files
Each line in a text file ends with a new line character (‘\n’).
It can be read or written by any text editor.
They are generally stored with .txt file extension.
Text files can also be used to store the source code.
2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of
ASCII characters. They contain data that is stored in a similar manner
tocookies
We use how ittoisensure
stored in the
you have themain memory.
best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
The binary files caninbe
collected thecreated onlymobile
GeeksforGeeks from applications.
within a program and their
contents can only be read by a program.
More secure as they are not easily readable.
They are generally stored with .bin file extension.
C File Operations
C file operations refer to the different possible operations that we can
perform on a file in C such as:
The highlighted text mentions the C function used to perform the file
operations.
File Pointer in C
A file pointer is a reference to a particular position in the opened file. It
is used in file handling to perform all file operations such as read, write,
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
close, etc. We use the FILE macro to declare the file pointer variable.
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
The FILE macrocollected
is defined inside <stdio.h>
in the GeeksforGeeks mobileheader file.
applications.
Syntax of File Pointer
FILE* pointer_name;
Open a File in C
For opening a file in C, the fopen() function is used with the filename or
file path along with the required access modes.
Syntax of fopen()
Parameters
file_name: name of the file when present in the same directory as the
source file. Otherwise, full path.
access_mode: Specifies for what operation the file is being opened.
Return Value
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
Opening Description
Modes
Open for reading in binary mode. If the file does not exist,
rb
fopen( ) returns NULL.
Open for writing in text mode. If the file exists, its contents
w are overwritten. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open the file.
Open for writing in binary mode. If the file exists, its contents
wb
are overwritten. If the file does not exist, it will be created.
Open for both reading and writing in binary mode. If the file
rb+
does not exist, fopen( ) returns NULL.
Open for both reading and writing in binary mode. If the file
wb+ exists, its contents are overwritten. If the file does not exist, it
will be created.
int main()
{
// file pointer variable to store the value returned by
// fopen
FILE* fptr;
// checking
We use cookies to ensure you have theifbestthe file experience
browsing is opened successfully
on our website. By using our site, you
if (fptr == NULL) {
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
printf("The file is not opened. The program will "
collected in the GeeksforGeeks mobile applications.
"now exit.");
exit(0);
}
return 0;
}
Output
The file is not opened because it does not exist in the source directory.
But the fopen() function is also capable of creating a file if it does not
exist. It is shown below
Create a File in C
The fopen() function can not only open a file but also can create a file if
it does not exist already. For that, we have to use the modes that allow
the creation of a file if not found such as w, w+, wb, wb+, a, a+, ab, and
ab+.
FILE *fptr;
fptr = fopen("filename.txt", "w");
int main()
{
// file pointer
FILE* fptr;
return 0;
}
Output
Function Description
So, it depends on you if you want to read the file line by line or character
by character.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
Example:
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);
The getc() and some other file reading functions return EOF (End Of
File) when they reach the end of the file while reading. EOF indicates
the end of the file and its value is implementation-defined.
Note: One thing to note here is that after reading a particular part of
the file, the file pointer will be automatically moved to the end of the
last read character.
Write to a File
The file write operations can be performed by the functions fprintf()
and fputs() with similarities to read operations. C programming also
provides some other functions that can be used to write data to a file
such as:
Function Description
fputs() Prints the whole line in the file and a newline at the end.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge
Example: that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
FILE *fptr ;
fptr = fopen(“fileName.txt”, “w”);
fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);
fputc("a", fptr);
Closing a File
The fclose() function is used to close the file. After successful file
operations, you must always close a file to remove it from the memory.
Syntax of fclose()
fclose(file_pointer);
Example:
FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(fptr);
Example 1: Program to Create a File, Write in it, And Close the File
int main()
{
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you//have
Declare
read andthe file pointer
understood our Cookie Policy & Privacy Policy Cookies are not
FILE* filePointer;
collected in the GeeksforGeeks mobile applications.
// Get the data to be written in file
char dataToBeWritten[50] = "GeeksforGeeks-A Computer "
"Science Portal for Geeks";
return 0;
}
Output
This program will create a file named GfgTest.c in the same directory
as the source file which will contain the following text: “GeeksforGeeks-
A Computer Science Portal for Geeks”.
Example 2: Program to Open a File, Read from it, And Close the File
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
C
collected in the GeeksforGeeks mobile applications.
// C program to Open a File,
// Read from it, And Close the File
#include <stdio.h>
#include <string.h>
int main()
{
printf(
"Data successfully read from file
GfgTest.c\n");
printf("The file is now closed.");
}
return 0;
}
Output
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
The file is now opened.
GeeksforGeeks-A Computer Science Portal for Geeks
Data successfully read from file GfgTest.c
The file is now closed.
This program reads the text from the file named GfgTest.c which we
created in the previous example and prints it in the console.
To open a file in binary mode, we use the rb, rb+, ab, ab+, wb, and wb+
access mode in the fopen() function. We also use the .bin file extension
in the binary filename.
Example
We use fwrite() function to write data to a binary file. The data is written
to the binary file in the from of bits (0’s and 1’s).
Syntax of fwrite()
Parameters:
fclose(fptr);
return 0;
}
Output
We useWrite
cookies to ensure you have
Operation the best browsing experience on our website. By using our site, you
Successful
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.
Reading from Binary File
The fread() function can be used to read data from a binary file in C.
The data is read from the file in the same form as it is stored i.e. binary
form.
Syntax of fread()
Parameters:
Return Value:
Output
fseek() in C
If we have multiple records inside a file and need to access a particular
record that is at a specific position, so we need to loop through all the
records before it to get the record. Doing this will waste a lot of
memory and operational time. To reduce memory consumption and
operational time we can use fseek() which provides an easier way to
get to the required data. fseek() function in C seeks the cursor to the
given record in the file.
Example of fseek()
int main()
{
FILE* fp;
We use cookies to ensure
fp =youfopen("test.txt",
have the best browsing "r");
experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
// collected
Moving inpointer to end mobile applications.
the GeeksforGeeks
fseek(fp, 0, SEEK_END);
// Printing position of pointer
printf("%ld", ftell(fp));
return 0;
}
Output
81
rewind() in C
The rewind() function is used to bring the file pointer to the beginning
of the file. It can be used in place of fseek() when you want the file
pointer at the start.
Syntax of rewind()
rewind (file_pointer);
Example
int main()
{
FILE* fptr;
fptr = fopen("file.txt", "w+");
fprintf(fptr, "Geeks for Geeks\n");
// using rewind()
rewind(fptr);
Functions Description
GeeksforGeeks 210
Next Article
C fopen() function with Examples
Similar Reads
Company Languages
About Us Python
Legal Java
In Media C++
Contact Us PHP
Advertise with us GoLang
GFG Corporate Solution SQL
Placement Training Program R Language
We use cookiesGeeksforGeeks
to ensure you Community
have the best browsing experience on our website. ByTutorial
Android using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy PolicyArchive
Tutorials Cookies are not
collected in the GeeksforGeeks mobile applications.
DSA Data Science & ML
Data Structures Data Science With Python
Algorithms Data Science For Beginner
DSA for Beginners Machine Learning
Basic DSA Problems ML Maths
DSA Roadmap Data Visualisation
Top 100 DSA Interview Problems Pandas
DSA Roadmap by Sandeep Jain NumPy
All Cheat Sheets NLP
Deep Learning
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not
collected in the GeeksforGeeks mobile applications.