File Handling
Definition
File handling is used to store data permanently in a computer. Using file handling we can store our data in
secondary memory (Hard disk).
Advantages
• Data Preservation: Storing files in documents allows to hold records even though this system terminates.
• Easy Data Access: Accessing records will become easy whilst there may be a large number of records
and it is far saved with inside the record, then these files may be accessed by the use of the C++ commands.
• Portability: It will become less difficult to switch records from one pc to any other with no changes.
1
Predefined standard stream vs file stream
Predefined stream file stream
The predefined streams are available to all programs and can be A file stream needs to be created and
used right away. connected to a file before it can be used
Even though read/write can be performed from any position with One can reposition a file stream to
basic iostreams; this usually does not make any sense with the arbitrary file positions and access data
predefined streams, as they are connected to the sequential devices randomly also.
by default.
2
File operations
• Create/Open a file
• Close a file
• Read from a file
• Write into a file
Open a file
• In C++, if we want to open a file, we must first obtain a stream object.
• A file can be opened in two ways:
▪ Using parameterized constructor
▪ Using open () member function
Using constructor
• Syntax:
• Stream streamobject (“File Name”);
• Example:
• ofstream outfile(“Swati.txt”);
Using open() function
• Syntax:
• stream streamobject;
• streamobject.open (“FileName”);
• Example:
• ofstream outfile;
• outfile.open(“Swati.txt”);
Close a file
• A file is closed by disconnecting it with the stream it is associated with.
• We can close a file using the member function close().
• Syntax:
• streamobject.close();
• Example:
• outfile.close();
End of file (EOF)
• You can detect when the end of the file is reached by using the member function eof().
• Syntax:
• bool eof();
• It returns non-zero when the end of file has been reached, otherwise it returns zero.
3
File modes in C++
• In C++, for every file operation, there exists a specific file mode.
• These file modes allow us to create, read, write, append, and update a file.
• The file modes are defined in the class ios.
• An opening mode is a setting to control how the stream opens the file.
• An opening mode can be provided as a second parameter to the constructor of a file stream or its open()
member function.
Random access in files
• Data from the file can be read sequentially as well as randomly from any position. Sequential data access
may not be appropriate in some cases.
• Random access of data provides faster retrieval of records.
• Random access enables read/write data from any position.
• For random access, it requires first to place a read/write file pointer at the required position in the file and
then perform read/write.
• The file pointer indicates the position in the file at which the next input/output is to occur.
• Moving the file pointer in a file may be required for various operations like modification of data, deletion
of data, searching data etc.
File pointers
• A file pointer is used to handle and keep track of the files being accessed.
• In C++, there are two types of file positions pointers: get and put.
• Get position pointer specifies location for next read and it is available for ifstream or input mode.
• Put position pointer specifies the location for next write operation and is available for ofstream or output
mode.
4
• Both ifstream and ofstream provide member functions for repositioning the file pointer and getting the
current position of file pointer.
Manipulators for file pointers
• tellg():
• It gives current position of get pointer.
• Member of ifstream class.
• Syntax:
• file_pointer.tellg();
• Example:
• int posn = fin.tellg();
• tellp():
• It gives current position of put pointer.
• Member of ofstream class.
• Syntax:
• file_pointer.tellp();
• Example:
• int posn=fout.tellp();
• seekg():
• It is used to move the get pointer to the specific position.
• Member of ifstream class.
• Syntax:
• file_pointer.seekg (number of bytes, Reference point);
• Example:
• fin.seekg(10,ios::beg);
• seekp():
• It is used to move the put pointer to the specific position.
• Member function of ofstream class.
• Syntax:
• file_pointer.seekp(number of bytes, Reference point);
• Example:
• fout.seekp(10,ios::beg);
Reference points
• ios::beg – These are used from the beginning of the file
• ios::end – These are used from the end of the file
• ios::cur – These are used from the current position in the file.
5
Error handling during file operations
• int bad(): If an invalid operation was attempted or any error that cannot be recovered from occurred, this
function will return a value that is not zero. On the other hand, if it is zero, which indicates a false value,
it is possible to recover from any other error that was reported and carry on with operations. Ex: fin.bad();
• int eof(): If the end of the file is reached while reading, this function returns a non-zero value (a true
value); otherwise, it returns zero (false value). Ex: fin.eof();
• int fail(): If an input or output operation was unsuccessful, this function will return a value that is not zero
(true). Ex: fin.fail();
• int good(): If there was no error, this function will return a value that is not zero (true). This indicates that
the functions described above are all valid. For instance, if the function fin.good() returns true, it indicates
that the stream with the name fin is functioning normally and that we can move on to the next step of
performing I/O operations. After it has returned zero, there will be no more operations that can be
performed. Ex: fin.good();
• clear(): Resets the error state, allowing subsequent operations to be attempted. Ex: fin.clear();