12 File Handling
12 File Handling
fstream, ifstream,ofstream
Introduction to File Handling
• Important concept for interacting with files on the computer's file
system.
• It allows programs to store, retrieve, and manipulate data.
• File handling is widely used for tasks such as data storage,
configuration management, logging, and data processing.
• Understanding file handling in C++ is essential for efficient data
management and seamless integration with external files.
File Handling Classes in C++
• There are three main file handling classes:
1. ifstream
2. ofstream
3. fstream.
• These classes are part of the <fstream> header file.
ifstream - Input File Stream:
• Used for reading input from files.
• Example:
• Reading data from a text file or configuration file.
File Handling Classes in C++
ofstream - Output File Stream:
• Used for writing output to files.
• Example:
• Writing data to a log file or creating a new file and writing data to it.
fstream - Input and Output File Stream:
• Provides both input and output capabilities.
• Can be used for reading and writing operations on files.
• Example:
• Opening a file, reading data from it, and then writing modified data back to the same
file.
Functions of File Handling
• Opening Files:
• Opening files is done using the open() function or constructor with the file name and
mode as parameters.
• Modes include
1. ios::in for input
2. ios::out for output
3. ios::app for append mode
4. ios::binary for binary mode
5. ios::ate to set the initial position at the end of the file.
Modes can be combined using the bitwise OR operator (|).
• Closing Files:
• Files should be properly closed using the close() function to release the file
resources.
Functions of File Handling
Reading from Files:
• Reading data from files can be done using the >> operator to extract data or
the getline() function to read lines.
• Reading can be character by character, line by line, or in chunks.
Writing to Files:
• Writing data to files can be done using the << operator to insert data or the
write() function to write data.
• Writing can be character by character, line by line, or in blocks.