Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

File Handling in C

In programming, we may require some specific input data to be generated several


numbers of times. Sometimes, it is not enough to only display the data on the console.
The data to be displayed may be very large, and only a limited amount of data can be
displayed on the console, and since the memory is volatile, it is impossible to recover
the programmatically generated data again and again. However, if we need to do so, we
may store it onto the local file system which is volatile and can be accessed every time.
Here, comes the need of file handling 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()

Functions for file handling


There are many functions in the C library to open, read, write, search and close the file. A
list of file functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file


4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

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.

1. FILE *fopen( const char * filename, const char * mode );

Opening
Modes Description

Searches file. If the file is opened successfully fopen( ) loads it into


r memory and sets up a pointer that points to the first character in it. If
the file cannot be opened fopen( ) returns NULL.

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.

Searches file. If the file is opened successfully fopen( ) loads it into


memory and sets up a pointer that points to the last character in it. It
a
opens only in the append mode. If the file doesn’t exist, a new file is
created. Returns NULL, if unable to open the file.

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.

Searches file. It is opened successfully fopen( ) loads it into memory


r+ and sets up a pointer that points to the first character in it. Returns
NULL, if unable to open the file.

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.

Searches file. If the file is opened successfully fopen( ) loads it into


memory and sets up a pointer that points to the last character in it. It
a+
opens the file in both reading and append mode. If the file doesn’t
exist, a new file is created. Returns NULL, if unable to open the file.

Open for both reading and appending in binary mode. If the file does
ab+
not exist, it will be created.

The fopen function works in the following way.

o Firstly, It searches the file to be opened.


o Then, it loads the file from the disk and place it into the buffer. The buffer is used
to provide efficiency for the read operations.
o It sets up a character pointer which points to the first character of the file.

Example of Opening a File


 C

// C Program to illustrate file opening

#include <stdio.h>

#include <stdlib.h>
int main()

// file pointer variable to store the value returned by

// fopen

FILE* fptr;

// opening the file in read mode

fptr = fopen("filename.txt", "r");

// checking if the file is opened successfully

if (fptr == NULL) {

printf("The file is not opened. The program will "

"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

// C Program to create a file

#include <stdio.h>

#include <stdlib.h>

int main()

// file pointer

FILE* fptr;

// creating file using fopen() access mode "w"

fptr = fopen("file.txt", "w");


// checking if the file is created

if (fptr == NULL) {

printf("The file is not opened. The program will "

"exit now");

exit(0);

else {

printf("The file is created Successfully.");

return 0;

Output

The file is created Successfully.


Reading From a File
The file read operation in C 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. There are also other functions we
can use to read from a file. Such functions are listed below:
Function Description

Use formatted string and variable arguments list to take input from a
fscanf()
file.
Function Description

fgets() Input the whole line from the file.

fgetc() Reads a single character from the file.

fgetw() Reads a number from a file.

fread() Reads the specified bytes of data from a binary file.

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

Similar to printf(), this function use formatted string and varible


fprintf()
arguments list to print output to the file.

fputs() Prints the whole line in the file and a newline at the end.
Function Description

fputc() Prints a single character into the file.

fputw() Prints a number to the file.

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);

Closing File: fclose()


The fclose() function is used to close a file. The file must be closed after performing all
the operations on it. The syntax of fclose() function is given below:

1. int fclose( FILE *fp );

You might also like