Files in C
Files in C
File handing in C is the process in which we create, open, read, write, and
close operations on a file. C language provides different functions such as
fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and
many different C file operations in our program.
Why do we need File Handling in C?
So far the operations using the C program are done on a prompt/terminal which
is not stored anywhere. The output is deleted when the program is closed. But
in the software industry, most programs are written to store the information
fetched from the program. The use of file handling is exactly what the situation
calls for.
In order to understand why file handling is important, let us look at a few
features of using files:
Reusability: The data stored in the file can be accessed, updated, and
deleted anywhere and anytime providing high reusability.
Portability: Without losing any data, files can be transferred to another in the
computer system. The risk of flawed coding is minimized with this feature.
Efficient: A large amount of input may be required for some programs. File
handling allows you to easily access a part of a file using few instructions
which saves a lot of time and reduces the chance of errors.
Storage Capacity: Files allow you to store a large amount of data without
having to worry about storing everything simultaneously in a program.
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
A text file contains data in the form of ASCII characters and is generally used
to store a stream of characters.
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 to how it is
stored in the main memory.
The binary files can be created only from 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:
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()
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, close, etc. We
use the FILE macro to declare the file pointer variable. The FILE macro is
defined inside <stdio.h> header file.
Syntax of File Pointer
FILE* pointer_name;
File Pointer is used in almost all the file operations in C.
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()
FILE* fopen(const char *file_name, const char *access_mode);
Return Value
If the file is opened successfully, returns a file pointer to it.
If the file is not opened, then returns NULL.
Opening File: fopen()
We must open a file before it can be read, write, or update. The fopen() function is used to open
a file. The syntax of the fopen() is given below.
Opening
Modes Description
Open for reading in binary mode. If the file does not exist, fopen( )
rb
returns NULL.
Open for writing in text mode. If the file exists, its contents are
w 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 are
wb
overwritten. If the file does not exist, it will be created.
Open for append in binary mode. Data is added to the end of the
ab
file. If the file does not exist, it will be created.
Open for both reading and writing in binary mode. If the file does not
rb+
exist, fopen( ) returns NULL.
Opening
Modes Description
Searches file. If the file exists, its contents are overwritten. If the file
w+ doesn’t exist a new file is created. Returns NULL, if unable to open
the file.
Open for both reading and writing in binary mode. If the file exists, its
wb+
contents are overwritten. If the file does not exist, it will be created.
Open for both reading and appending in binary mode. If the file does
ab+
not exist, it will be created.
#include <stdio.h>
#include <stdlib.h>
int main()
// fopen
FILE* fptr;
if (fptr == NULL) {
"now exit.");
exit(0);
return 0;
Output
The file is not opened. The program will now exit.
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");
Example of Opening a File
C
#include <stdio.h>
#include <stdlib.h>
int main()
// file pointer
FILE* fptr;
if (fptr == NULL) {
"exit now");
exit(0);
else {
return 0;
Output
Use formatted string and variable arguments list to take input from a
fscanf()
file.
Function Description
So, it depends on you if you want to read the file line by line or character by
character.
Example:
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.
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.
Function Description
fwrite() This functions write the specified amount of bytes to the binary file.
Example:
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);
where the file_pointer is the pointer to the opened file.
Example:
FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(fptr);