File handling in C refers to the task of storing data in the form of input or output produced by running C programs in data files for future reference and analysis.
When a collection of related data is
stored on any secondary storage medium, it is called data file. Data files are
permanent in nature and they allow large quantities of data to be stored
on-line and used in pieces as needed.
Once we compile and run the program, the
output is obtained, but this output is not stored in the form of information
anywhere in the system. If we want to store the output produced for future references,
we have to implement file handling.
A file is nothing but a
source of storing information permanently in the form of a sequence of bytes on
a disk where a group of related data is stored. File is created for permanent
storage of data.
Need for File Handling in C:
There is a time when the output
generated by compiling and running the program does not serve the purpose. If
we want to check the output of the program several times, it becomes a tedious
task to compile and run the same program multiple times. This is where file
handling comes into play. Here are some of the following reasons behind the
popularity of file handling:
· Reusability: It helps in preserving the data or information
generated after running the program.
· Large storage
capacity: Using files, you need not worry about the problem of storing
data in bulk.
· Saves time:
There are certain programs that require a lot of input from the user. You can
easily access any part of the code with the help of certain commands.
· Portability:
You can easily transfer the contents of a file from one computer system to
another without having to worry about the loss of data.
Types of Files in C:
In C,
data files are of two types: Text Files and Binary Files
Text Files:
A text file contains textual information.
These are the simplest files a user can create when dealing with file handling
in C. A carriage return and a line-feed
character tab is the data delimiter (marks end of input string). Such files are
referred to as sequential files. E.g. program source code, a file created
through word processor.
It is created with a .txt extension using any simple text
editor. Generally, we use notepads to create text files. Text file stores
information in the form of ASCII characters internally, but when we open the
text file, we would find the content of the text readable to humans.
Hence,
it is safe to say that text files are simple to use and access. But, along with
advantages comes disadvantages as well. Since it is easily readable, it does
not provide any security of information. Moreover, it consumes large storage
space. Hence, there is a different type of file available called binary files
which helps us solve this problem.
Binary Files:
A
binary file stores information in the form of the binary number system (0’s and
1’s) and hence occupies less storage space. In simple words, it stores
information in the same way as the information is held in computer memory.
Therefore, it proves to be much easier to access.
In
a binary file, the data is not delimited. The entire file is one piece of data.
Hence, it is the programmer’s responsibility to dissect the bytes and impart
logic to them. Since each byte is data, the file pointer position can be
maintained easily. This allows the programmer to retrieve data from and write
data to anywhere in the file. It is created with a .bin extension. It overcomes the drawback
offered by text files. Since it is not readable to humans, the information is
more secure. Hence, it is safe to say that binary files prove to be the best
way to store information in a data file.
File Handling Operations:
There are various operations associated with file handling in C. They are:
- Creation of a new file
- Opening an existing file
- Reading data from a file
- Writing data to a file
- Moving to a specific location
- Closing a file
File Declaration:
Each
file used in a program must have a pointer of FILE Type associated with it.
Syntax: FILE *file_ptr;
Example: FILE *fp; // variable fp is pointer to type FILE
There are a number of functions that helps to perform basic file operations. Following are the functions:
Function |
Description |
fopen() |
create a new file or open an existing file |
fclose() |
closes an opened file |
getc() |
reads a character from a file |
putc() |
writes a character to a file |
fscanf() |
reads a set of data from a file |
fprintf() |
writes a set of data to a file |
getw() |
reads a integer from a file |
putw() |
writes a integer to a file |
fseek() |
Move the file position to a desired point |
ftell() |
gives current position in the file |
rewind() |
set the position to the starting point |
fread() |
Read from a file |
fwrite() |
Write to a file |
Opening a File or Creating a File:
The first step in using a file is to
open it. A file can be used in different ways, for reading from or writing to,
or perhaps both. Before performing any type of operation, a file must be
opened. We open the file by using the function fopen(). This has two
parameters, the name of the file to be opened and the mode to use. fopen()
returns a file pointer on success or NULL on failure.
Syntax:
file-pointer=fopen(“FILE NAME ”, “Mode”);
Example: FILE *fp=fopen( “tstdata.txt”, “r”);
Here, *fp
is the FILE pointer, which will hold the reference to
the opened file.
If the files do not exist, or there is a
problem opening them, fopen() returns a special value called NULL. When you
open a file for reading, you are assuming that the file exists. If it does not,
fopen() will give you an error. When you open a file for writing the file may or
may not exist, and fopen() will create one for you if it needs to
The modes and their implications are given below:
Mode |
Description |
r |
open
existing file for reading |
w |
open
or create a file for writing. If the file specified exists, it is
overwritten. If the file does not exist
it is created |
a |
open a
text file for appending(adding) data |
r+ |
open
file for reading and writing(updating) |
w+ |
open a
text file in both reading and writing mode |
a+ |
open a
text file in both reading and writing mode |
rb |
open a
binary file in reading mode |
wb |
open
or create a binary file in writing mode |
ab |
open a
binary file in append mode |
rb+ |
open a
binary file in both reading and writing mode |
wb+ |
open a
binary file in both reading and writing mode |
ab+ |
open a binary file in both reading and writing mode |
Closing a File:
Every file must be closed after all I/O operations
related to that file are completed. This is to ensure flushing the buffer of
that file. Flushing a buffer is essential as it prevents loss of data when
writing to disk. When a file is closed, various system resources are freed. The fclose()
function is used to close
an opened file. It has one
parameter, the file pointer whose file needs to be closed.
fclose() returns zero on success and EOF on failure.
This would be done using a statement like:
fclose(file_ptr);
Example:
FILE *p1, *p2;
p1 = fopen(“INPUT.txt”, “r”);
p2 =fopen(“OUTPUT.txt”, “w”);
……..
……..
fclose(p1);
fclose(p2);
Example:
Program to open and close a file
#include<stdio.h>
#include<conio.h>
int
main()
{
FILE
*fp;
fp=fopen(“tstdata.txt”,
“w”);
if(fp==0)
printf(“Error in file opening”);
else
fclose(fp);
return
0;
}
Reading and Writing a Text File in C:
The
input/output operations in a file help us read and write in a file. The
simplest functions used while performing operations on reading and writing
characters in a file are getc() and putc() respectively.
In
order to read and write a set of data in a file, we use the fscanf() and
fprintf() functions.
Text File: Reading
Reading a file means copying the contents of the file from
secondary storage. The file must be opened in the “r” mode. The function
getc(), fgetc(), or fscanf() can be used to achieve this.
getc() and fgetc() functions : Both these functions are to get a character from the stream.
Syntax: getc(stream);
Syntax: fgetc(stream);
Text File: Writing
Write a file means putting information into a file. The
stream must be opened in the “w” or the “a” mode. The function putc(), fputc()
or fprintf() are available in stdio.h to achieve this.
putc() and fputc() function(): The putc() and fputc()
function output a character to a stream. They are similar to the putchar()
function, only the putchar() function outputs the character to stdout, while
putc() and fputc() output the character to a stream.
Random Access Files:
In ‘C’ language, the data stored in the file can be accessed in two ways:
- Sequential access
- Random access
If we want to read, access record in the middle of the file and if the file size is too large sequential access is not preferable. In this case, random access to file can be used, which allows to access any record directly at any position in the file. We can randomly position file pointer at any position in the data file. Random access means you can move to any part of a file and read or write data from it without having to read through the entire file.
In general, with small files, we access the files sequentially. In sequential access, we access the file record by record or character by character. This approach is appropriate if the file size is small, but what if the file has tens of thousands of records? In random file access, if a file has 10,000 records and if we want to go to the 9,999th record, we can directly point the file pointer to this record using the random file access technique. Random accessing of files in C language can be done with the help of the following functions:
- fseek()
- ftell()
- rewind()
fseek() function: fseek() function is used to take file pointer
to a particular position of the data file.
Syntax:
fseek(Fpointer, Position, Initial);
Fpointer is name of file pointer
variable.
Position number of characters to
be jumped
Initial specifies the position
from where file pointer should be jumped. It can three values :
0: From the beginning of file.
1: Current position.
2: End of file
ftell() function: This function returns the
current position of file pointer.
Syntax: ftell(Fpointer)
Fpointer is the name of file pointer variable.
rewind(): This function is used to move the file pointer to the beginning of the file. This function is useful when we open file for update.
Syntax: rewind(file pointer);
0 Comments
if you have any doubts plz let me know...