Introduction
File handling in C++ allows programs to read from and write to files, enabling data storage beyond program runtime. It provides mechanisms to create, open, read, write, and close files using standard C++ libraries. File I/O is managed using streams and various classes such as ifstream, ofstream, and fstream from the <fstream> header. These operations are vital for applications involving logging, data persistence, configurations, or transferring information. C++ treats file operations similarly to keyboard and screen I/O, abstracting complexities for the programmer. Understanding file modes, stream types, and error handling is essential for robust file manipulation. This section covers all aspects of file handling including text and binary file processing.
Header File Required
To perform file input and output operations in C++, the <fstream> header must be included. It provides essential classes such as ifstream for reading files, ofstream for writing files, and fstream for combined read/write access. This header enables robust and structured file handling capabilities within C++ programs.
Syntax:-
#include <fstream>
Types of File Streams
- ifstream (Input File Stream): Used to read data from files.
- ofstream (Output File Stream): Used to write data to files.
- fstream (File Stream): Used to read from and write to files.
Opening a File
To read or write data in C++, you must first open a file using a stream object like ifstream, ofstream, or fstream. Files can be opened directly when the stream is created or later using the open() function. You can also specify the file mode (read, write, append, etc.) to control how the file is accessed.
Syntax:
fstream file;
file.open(“filename.txt”, mode);
Or use constructor-based opening:
ifstream in(“file.txt”);
ofstream out(“file.txt”);
Modes:
- ios::in – Open for reading.
- ios::out – Open for writing.
- ios::app – Append to the end of file.
- ios::ate – Move to the end of the file upon opening.
- ios::trunc – Truncate contents if file exists.
- ios::binary – Binary mode.
Example:
ofstream outFile;
outFile.open(“example.txt”, ios::out);
outFile << “Writing to a file.”;
outFile.close();
Closing a File
In C++, closing a file is a crucial step after completing read or write operations. It ensures that any data remaining in the buffer is properly flushed to the file and that system resources are released. This is done using the close() function provided by file stream classes such as ifstream, ofstream, and fstream. While files may be closed automatically when the program ends, explicitly closing them improves reliability and prevents potential data loss.
Syntax:-
file.close();