File Handling
File Handling
• When working with files, you need to declare a pointer of type file.
This declaration is needed for communication between the file and
the program.
• FILE *fptr;
Opening a file - for creation and edit
Open for append in binary mode. If the file does not exist, it will be
ab
Data is added to the end of the file. created.
Open for both reading and writing in If the file does not exist, fopen() returns
rb+
binary mode. NULL.
Open for both reading and If the file does not exist, it
a+
appending. will be created.
Open for both reading and If the file does not exist, it
ab+
appending in binary mode. will be created.
Closing a File
• The file (both text and binary) should be closed after reading/writing.
• Closing a file is performed using the fclose() function.
• fclose(fptr);
• fptr is a file pointer associated with the file to be closed.
Reading and writing to a text file
• Functions fread() and fwrite() are used for reading from and writing to a
file on the disk respectively in case of binary files.
• Writing to a binary file
• To write into a binary file, you need to use the fwrite() function. The
functions take four arguments:
• address of data to be written in the disk
• size of data to be written in the disk
• number of such type of data
• pointer to the file where you want to write.
• fwrite(addressData, sizeData, numbersData, pointerToFile);
Getting data using fseek()
• If you have many records inside a file and need to access a record at a
specific position, you need to loop through all the records before it to
get the record.
• This will waste a lot of memory and operation time. An easier way to
get to the required data can be achieved using fseek().
• As the name suggests, fseek() seeks the cursor to the given record in
the file.
Syntax of fseek()
• Parameters
stream − This is the pointer to a FILE object that identifies the stream.
offset − This is the number of bytes to offset from whence.
whence − This is the position from where offset is added. It is specified by one of the following constants
−
SEEK_CUR Starts the offset from the current location of the cursor in the file.
No. Function Description
• The rewind() function sets the file pointer at the beginning of the
stream. It is useful if you have to use stream many times.
• Syntax:
• void rewind(FILE *stream)
C ftell() function
• The ftell() function returns the current file position of the specified
stream. We can use ftell() function to get the total size of a file after
moving file pointer at the end of file. We can use SEEK_END constant
to move the file pointer at the end of file.
• Syntax:
• long int ftell(FILE *stream)
1. C program to read name
and marks of n number of
students and store them in a
file.
2. C program to read name and
marks of n number of students
from and store them in a file. If
the file previously exits, add the
information to the file.