Programs often need to store data persistently so it is not lost when the program closes. In C++, this is accomplished by interacting with the file system using the <fstream> library.
Just as <iostream> provides cin and cout to read from and write to the console, <fstream> provides classes to read from and write to files.
There are three main classes included in the <fstream> library:
ofstream (Output File Stream): Creates and writes to files.ifstream (Input File Stream): Reads from files.fstream: Can both read from and write to files.To write data to a file, you create an object of the ofstream class. If the file does not exist, C++ will create it for you.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// 1. Create and open a text file
ofstream MyFile("student_data.txt");
// 2. Write to the file using the insertion operator (<<)
MyFile << "Name: John Doe" << endl;
MyFile << "ID: 2024CSE001" << endl;
MyFile << "Grade: A" << endl;
// 3. Always close the file when finished
MyFile.close();
cout << "File written successfully." << endl;
return 0;
}To read from an existing file, use the ifstream class. You often read files line-by-line using a while loop and the getline() function.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string textLine;
// 1. Open an existing file
ifstream ReadFile("student_data.txt");
// Check if the file opened successfully
if (!ReadFile) {
cout << "Error: File could not be opened!" << endl;
return 1;
}
// 2. Read the file line by line
while (getline(ReadFile, textLine)) {
// Output the text from the file to the console
cout << textLine << endl;
}
// 3. Close the file
ReadFile.close();
By default, ofstream opens a file and overwrites its contents. You can change this behavior by specifying an open mode flag.
For example, to append to a file instead of overwriting it, use ios::app:
// Opens the file in append mode
ofstream AppendFile("student_data.txt", ios::app);
AppendFile << "Status: Active" << endl;
AppendFile.close();#include <fstream> for file operations.ofstream to create and write to files.ifstream to read from files..close() the file when you are finished to release operating system resources.C++ uses stream classes for file operations, found in the <fstream> library.
Output file stream. Used to create files and write data to them.
Input file stream. Used to read data from existing files.
File stream. Used for both reading and writing.
Test your understanding with 2 questions
Which class is used specifically for reading data from a file?
What must you do after you are finished working with a file?
2 Modules
2 Modules