File Handling
File Handling
Basics of Files
• File: A file is a collection of data stored on a disk with a specific name and format.
• C++ provides file handling capabilities through the <fstream> header, which
includes three classes:
o ifstream: Input file stream for reading from files.
o ofstream: Output file stream for writing to files.
o fstream: File stream for both reading and writing.
Standard Input/Output
• Standard Input: Refers to the default input device, usually the keyboard. In C++, it
is represented by std::cin.
• Standard Output: Refers to the default output device, usually the console. In C++,
it is represented by std::cout.
File Operators
End-Of-File (EOF)
• EOF: A special condition that indicates the end of a file has been reached.
• Function: eof() method can be used with file streams to check for EOF.
while (!file.eof()) {
// Read data
}
• Opening a File:
o Use the open() function or constructor of the stream class.
ofstream outFile;
outFile.open("example.txt");
• Closing a File:
o Use the close() function to release file resources.
outFile.close();
Writing to a File
ofstream outFile("example.txt");
outFile << "Hello, File!";
outFile.close();
• Use the >> operator or file methods such as getline() to read data.
ifstream inFile("example.txt");
string data;
while (getline(inFile, data)) {
cout << data << endl;
}
inFile.close();
Error Conditions
• Check for errors during file operations using the following methods:
o fail(): Checks if a file operation failed.
o bad(): Checks for serious errors such as hardware failure.
o good(): Checks if the file stream is in a good state.
if (file.fail()) {
cout << "Error opening file!";
}
Record Input/Output
• Record Writing:
o Use binary mode to write structured data (e.g., objects or records).
struct Record {
int id;
char name[50];
};
• Record Reading:
o Use binary mode to read structured data.
Conclusion
File handling in C++ provides a robust mechanism for interacting with files. Understanding
the concepts of text and binary modes, standard I/O, and error handling ensures efficient
file operations for a variety of applications.