File Handling in C language


A data file is a collection of related records. A record contains data about an entity. Data files can be used to save any type of data. Files are stored on secondary storage. The data is stored in files permanently.

Normally, a program inputs data from the user and stores it in variables. The data stored in the variables is temporary. When the program ends, all data stored in variable is also destroyed.


Use of Data Files:

A data file can be used to provide input to a program. It can also be used to store the output of a program permanently. If a program gets input from a file instead of keyboard, it will get the same data each time it is executed. There will be far less chance of errors.

Text File:

A type of file that stores the data as readable and printable characters is called text file. A source program of C programming is an example of text file. The user can easily view and read the contents of a text file. It can also be printed to get a hard copy.

File pointer:

File pointer is pointer that refers to a file on the secondary storage. It is a variable of type FILE. It is used to access and manipulate a data file. A program has to declare a file pointer to use a file. The file pointer is associated with a file after declaration. One file pointer can be associated with only one data file.

SYNTAX:

The syntax for declaring a file pointer is as follows:

FILE *MyFile;

The identifier MyFile is a file pointer. FILE is the type of MyFile pointer. The symbol ‘*’ indicates that it is a pointer to a file structure. It contains all information that is required to manage files. It must be included in the program to manipulate files.

In C programming language we can perform a number of file operations. Consider the following table in which we have described some of the file operations:

Function Description
fopen () This function is used to create a new file or opens an existing file
fclose () This function is used to close a file.
getc () This function is used to read a character from a file.
putc () This function is used to write a character in a file.
fscanf () This function is used to read a set of data from a file.
fprintf () This function is used to writes a set of data in a file.
getw () This function is used to read an integer from a file.
putw () This function is used to write an integer in a file.
fseek () This function is used to set the position to desire point.
ftell () This function is used to give the current position in the file.
rewind () This function is used to set the position at the beginning of point.

Opening a file:

A file should be opened before it can be processed. A function fopen is used to open a file.

SYNTAX:

The syntax is as follows;

File_Pointer = fopen(File_Name, Mode);

File_Pointer is the name of file pointer declared in the program.

File_Name is name of data file to be opened.

Mode indicates the mode in which the file is to be opened.


Modes of opening Files:

A data file can be opened in the following modes:

Mode Explanation
r The file is opened in read mode. The data can be read only and cannot be written or modified. The file must exist already.
w The file is opened in write mode. The data can be written to the file. The existing data in the file is destroyed.
a The file is opened in the append mode. The new data is written at the end of existing data. The data cannot be read in this mode.
r+ The file is opened in read/write mode. The data can be written and read to a file. The file must already exist.
w+ The file is opened in read/write mode. The data can be written to the file. The existing data in the file is destroyed. The data can also be read.
a+ The file is opened in append mode. The new data is written at the end of existing data. The existing data can also be read.
rb This is used to open the binary filein reading mode.
wb This is used to open the binary file in writing mode.
ab This is used to open the binary file in append mode.
rb + This is used to open the binary file in both reading mode and writing mode.
wb + This is used to open the binary file in both reading mode and writing mode.
ab + This is used to open the binary file in both reading mode and writing mode.


Closing a file:

When a file is opened a connection is established between the file and the program. After the file has been processed, the connection should be terminated. When the file is closed, the file pointer is also destroyed in the memory. The data file becomes inaccessible. Closing of a file is optional. If it is not closed, the operating system automatically closes it when the program finishes.

Each opened file occupies memory. It is important to close a file because an opened file occupied memory. Closing of file releases the memory occupied by file.

A file is closed by using fclose statement. This function disconnects the opened file from the program.

SYNTAX:
fclose(File_pointer);

fclose is the function that closes a file. File_Pointer is a file pointer that refers to the file to be closed.


Input/output operation on File:


Input Functions:

Writing data in text files:

There are three ways to read and write data in text files.

  1. Data can be written to a file one character at a time. fputc function is used for this purpose. Its syntax is as follows:

 SYNTAX: fputc(char, File_Pointer);

  1. Data can be written to a file string. fputs function is used for this purpose. Its syntax is as follows:

SYNTAX: fputs(string, File_Pointer);

  1. Data can be written to a file as formatted input. fprintf function is used for this purpose. Its syntax is as follows:

SYNTAX: fprintf(File_Pointer, Control_String, Write_List);


Writing data character by character using fputc() function:

Data can be written to file one character at a time by using fputc function. Its syntax is as follows:

fputc(char, File_Pointer);

EXAMPLE:

# include <conio.h>

# include <stdio. h>

void main()

{

FILE *out;

charch;

out = fopen(“c:\\test.txt”,”w”);

printf (“enter a character (. to end):”);

ch= getche();

while(ch != ‘.’)

{

fputc(ch, out);

ch = getche();

}

fclose(out);

}

The above program will input characters from the keyboard until the user types a dot. The input will be stored in test.txt file on C: drive.

Writing data as string in text file using fputs() function:

Data is written to file as string by using fputs function. Its syntax is as follows:

fputs(string, File_Pointer);

string is the string to be stored in the file.

File_Pointer is a file pointer associated with a data file in which the string will be written.

CODE:

# include <conio.h>

# include <stdio.h>
void main()

{

FILE *out;

charch[25];

inti;

if((out = fopen (“c:\\stest.txt”, “w”)) ==NULL)

cout<<(“File opening error”);

for (i=0;i<3;i++)

{

pritnf (“enter string”);

gets(ch);

fputs(ch, out);

fputs(“\n”, out);

}

fclose(out);

getch();

}


Output Functions:

Reading data character by character in text file using fgetc () function:

Data can be read from text file one character at a time by using fgetc function. Its syntax is as follows:

ch = fgetc(File_Pointer);

File_Pointer is the file pointer that refers to a file.

fgetc is the function to read the file character by character.

ch is a variable that store the character that is read from the file.

CODE:

# include <conio.h>

# include <stdio.h>
void main()

{

FILE *in;

charch;

if((in = fopen (“c:\\test.txt”, “r”))==NULL)

printf (“File opening error”);

while ((ch = fgetc(in)) != EOF)

printf (“%c”, ch);

fclose(in);

}

The above program reads a file test.txt character by character. The fgetc function continues to read and display the file character by character until it finds EOF character. The EOF stands for end of file is a special character. It is used to indicate the end of a text file. It is placed after the last character in one file. It is added automatically at the end of files. A constant EOF represents end of file character. EOF is frequently used to find the end of file.

Reading data as string from text file using fgets() function:

Data can be read from file as string by using fgets function. Its syntax is as follows:

fgets(string, File_Pointer);

string is the string to be stored in the file.

File_Pointer is a file pointer associated with a data file in which the string will be written.


Formatted File input and output using fscanf() and fprintf() functions:

The data in formatted output is written in a particular manner with the help of format specifiers. In this method, a series of different types of data is written in files. The data in formatted input is read in particular manner with the help of format specifiers. In this method, data is read in the same sequence in which it was written.

C programming language provides different functions for formatted input and output. These functions are used to read and write data in a specific format. Two most important functions are as follows:

  1. fprintf is used to write formatted output in a file.

SYNTAX:

fprintf(File_Pointer, Control_String, Write_list);

Control string contains format specifiers and escape sequences. It indicates the format according to which data is written to data file.

Write_List is a list of variables, constants or expressions whose values are written in the file. Each item in the list is separated by comma.

  1. fscanf is used to read formatted data from a file.

SYNTAX:

fscanf(FILE_Pointer, Control_string, Read_list);

Control string contains format specifiers and escape sequences. It indicates the format according to which data is read from data file.

Write_List is a list of variables in which values are stored from the file. Each item in the list is separated by comma.


Difference between append and write mode:

In C programming language both write and append mode are almost the same while opening a file. Both of these are used to write in a file and both create new file if the file is not existing.

The main and the only difference between these mode is that when we open a file in the write mode then the data that is written already in the file gets deleted and when we open the file in append mode the data is not deleted rather we can make changes in the file. When the file is opened in the append mode the cursor is at the end of current data in the file.


Reading and writing in a Binary file:

In C programming language we can write and read data from a binary file. A binary file is the one that contains a large numeric data but is similar to an ordinary file. The functions fread () and fwrite () are used to read and write in a binary file respectively.


Fseek(), ftell and rewind() functions:

Fseek () function is used to move the reading control to different positions by suing the fseek function.

Ftell () function is used to tell the byte location of the current position of cursor in the pointer.

Rewind () function is used to move the control at the beginning of the file.