Writing to a File
Writing to a file in C++ involves storing output data using an output file stream (ofstream). This allows programs to create logs, save user input, export results, or generate reports. By opening a file in write mode, developers can direct formatted output to external storage instead of the console, enhancing data persistence and automation in applications.
Syntax:
ofstream file(“data.txt”);
file << “Hello, file!”;
file.close();
Example:
ofstream outFile(“output.txt”);
outFile << “Name: John Doe\nAge: 30”;
outFile.close();
Reading from a File
Reading from a file in C++ involves accessing stored data using input file streams (ifstream). This process typically includes opening the file, reading its contents using appropriate methods, and then closing the file to release system resources. File reading is essential for tasks such as loading configuration data, processing records, or importing user input from external sources.
Syntax:
ifstream file(“data.txt”);
string line;
while(getline(file, line)) {
cout << line << endl;
}
file.close();
Example:
ifstream inputFile(“output.txt”);
string line;
while(getline(inputFile, line)) {
cout << line << endl;
}
inputFile.close();
Detecting End of File (EOF)
In C++, detecting the End of File (EOF) is essential for safely reading data from files without causing errors or infinite loops. The eof() function, provided by file stream classes like ifstream, returns true when the stream has reached the end of the file. Alternatively, EOF can be detected implicitly by checking the stream condition in loop constructs such as while (getline(file, line)), which automatically stops when no more data is available.
Example:-
while(!file.eof()) {
// read content
}
Reading and Writing Binary Files
Binary files store data in raw byte format, making them efficient for saving structured data like arrays, objects, and multimedia. Unlike text files, binary files preserve the exact memory representation of data, which is crucial for performance and accuracy.
Writing Binary:
ofstream file(“binary.dat”, ios::binary);
int x = 100;
file.write((char*)&x, sizeof(x));
file.close();
Reading Binary:
ifstream file(“binary.dat”, ios::binary);
int y;
file.read((char*)&y, sizeof(y));
cout << “Value: ” << y;
file.close();