Unit 5 Basics of File Handling
Unit 5 Basics of File Handling
• To preserve data
• Easy access
• Transportable on any computer
C programming language supports two types of files and they are as follows...
Text file : The file that contains ASCII codes of data like digits, alphabets and symbols is called text
file (or) ASCII file.
Normal text file that can be accessed using Notepad
Displays normal text content that can be edited or deleted.
Takes minimum effort to maintain, easily readable, less security and takes bigger storage
space.
Binary File : The file that contains data in the form of bytes (0's and 1's) is called as binary file.
Generally, the binary files are compiled version of text files.
.bin files in computer
Stores data in binary form, holds large amount of data, provides better security.
File Operations in C
The following are the operations performed on files in c programming langauge...
All the above operations are performed using file handling functions available in C. We discuss file
handling functions in the next topic.
Different operations that can be performed on a file are:
1. Creation of 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)
The text in the brackets denotes the functions used for performing those operations.
Functions in File Operations:
Opening or creating file
For opening a file, fopen function is used with the required access modes. Some of the commonly
used file access modes are mentioned below.
File opening modes in C:
• “r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the first character in it. If the file cannot be opened fopen( ) returns
NULL.
• “rb” – Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
• “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new
file is created. Returns NULL, if unable to open file.
• “wb” – Open for writing in binary mode. If the file exists, its contents are overwritten. If the
file does not exist, it will be created.
• “a” – 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. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open file.
• “ab” – Open for append in binary mode. Data is added to the end of the file. If the file does not
exist, it will be created.
• “r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the first character in it. Returns NULL, if unable to open the file.
• “rb+” – Open for both reading and writing in binary mode. If the file does not exist, fopen( )
returns NULL.
• “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a
new file is created. Returns NULL, if unable to open file.
• “wb+” – Open for both reading and writing in binary mode. If the file exists, its contents are
overwritten. If the file does not exist, it will be created.
• “a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
a pointer which points to the last character in it. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open file.
• “ab+” – Open for both reading and appending in binary mode. If the file does not exist, it will
be created.
As given above, if you want to perform operations on a binary file, then you have to append ‘b’ at
the last. For example, instead of “w”, you have to use “wb”, instead of “a+” you have to use “a+b”.
For performing the operations on the file, a special pointer called File pointer is used which is
declared as
FILE *filePointer;
So, the file can be opened as
filePointer = fopen(“fileName.txt”, “w”)
The second parameter can be changed to contain all the attributes listed in the above table.
FILE * filePointer;
filePointer = fopen(“fileName.txt”, “r”);
fscanf(filePointer, "%s %s %s %d", str1, str2, str3, &year);
• Writing a file –:
The file write operations can be performed by the functions fprintf and fputs with similarities to
read operations. The snippet for writing to a file is as :
FILE *filePointer ;
filePointer = fopen(“fileName.txt”, “w”);
fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2012);
• Closing a file –:
After every successful file operations, you must always close a file. For closing a file, you have
to use fclose function. The snippet for closing a file is given as :
FILE *filePointer ;
filePointer= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(filePointer)
FILE STREAMS:
Abstraction between the programmer and the device.
Sequence of bytes of data.
File I/O takes place through two streams : Input stream & Output stream.
So far, we have been using the iostream standard library, which provides cin and cout methods for
reading from standard input and writing to standard output respectively.
To perform file processing in C++, header files <iostream> and <fstream> must be included in
your C++ source file.
1
ofstream
This data type represents the output file stream and is used to create files and to write information to files.
2
ifstream
This data type represents the input file stream and is used to read information from files.
3
Fstream
This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means
it can create files, write information to files, and read information from files.
File Pointer :
Points to the memory location that contains information about the file.
● Name of the file
● Current position of the file
● Mode of the file
● Track errors in the file
Syntax:
FILE * filePointer;
Example 1: Program to Open a File, Write in it, And Close the File
# include <stdio.h>
# include <string.h>
int main( )
FILE *filePointer ;
char dataToBeWritten[50]
// Open the existing file GfgTest.c using fopen()in write mode using "w" attribute
// Check if this filePointer is null which maybe if the file does not exist
if ( filePointer == NULL )
else
{
fputs(dataToBeWritten, filePointer) ;
fputs("\n", filePointer) ;
fclose(filePointer) ;
return 0;
Example 2: Program to Open a File, Read from it, And Close the File
// C program to Open a File, Read from it, And Close the File
# include <stdio.h>
# include <string.h>
int main( )
FILE *filePointer ;
char dataToBeRead[50];
// Check if this filePointer is null which maybe if the file does not exist
if ( filePointer == NULL )
else
{
// Print the dataToBeRead
fclose(filePointer) ;
return 0;
#include <stdlib.h>
struct threeNum
};
int main()
int n;
FILE *fptr;
exit(1);
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
fclose(fptr);
return 0;
#include <stdlib.h>
struct threeNum
};
int main()
int n;
FILE *fptr;
exit(1);
}
fclose(fptr);
return 0;