C PROJECT BATCH
CHAPTER 2
FILE HANDLING BASICS
Topics Covered
• What Is File Handling?
• Why To Use File Handling?
• How C Handles Files ?
• Steps Required In File Handling
• File Opening Modes
What is a File?
• A file is a collection on information, usually
stored on a computer’s disk. Information can
be saved to files and then later reused.
3
Why We Need File Handling ?
• Files are places where data can be stored
permanently.
• Some programs expect the same set of data to be fed
as input every time it is run.
– Cumbersome.
– Better if the data are kept in a file, and the program
reads from the file.
• Programs generating large volumes of output.
– Difficult to view on the screen.
– Better to store them in a file for later viewing/
processing
How C Handles Files ?
• C uses a structure called FILE (defined in stdio.h) to store the
attributes of a file.
• C provides a number of functions that helps to perform basic file
operations.
• Following are these functions:
– fopen() create a new file or open a existing file
– fclose() closes a file
– fgetc() reads a character from a file
– fputc() writes a character to a file
– rewind() set the position to the beginning point
– fscanf() reads a set of data from a file
– fprintf() writes a set of data to a file
– fseek() set the position to desire point
– ftell() gives current position in the file
5
Steps in Processing a File
1. Create the stream via a pointer variable using the
FILE structure:
FILE* fp;
2. Open the file, associating the stream name with
the file name.
3. Read or write the data.
4. Close the file.
File Open
• The file open function (fopen) serves two
purposes:
– It makes the connection between the physical file
and the stream.
– It creates “a program file structure to store the
information” C needs to process the file.
• Syntax:
fopen(“filename”, “mode”);
More On fopen
• The file mode tells C how the program will use the
file.
• The filename indicates the system name and location
for the file.
• We assign the return value of fopen to our pointer
variable:
fp = fopen(“data.txt”, “w”);
fp = fopen(“D:\\data.txt”, “w”);
More On fopen
File Open Modes
More on File Open Modes
Some More Modes
• r+ - open for reading and writing, start at beginning
• w+ - open for reading and writing (overwrite file)
• a+ - open for reading and writing (append if file
exists)
Closing a File
• When we finish with a mode, we need to close the
file before ending the program or beginning another
mode with that same file.
• To close a file, we use fclose and the pointer
variable:
fclose(fp);