File handling is based on the concept of streams. A stream is a sequence of data elements that are made available for processing. Streams allow data to flow in and out of the program.
Input Stream (istream): This stream is used for reading data from a file (or any other input source). For example, you can use an input stream to read data from a text file or the standard input (keyboard).
ifstream infile("input.txt"); // Creates an input stream for reading from the file
string line;
while (getline(infile, line)) {
cout << line << endl; // Output each line read from the file
}
infile.close();
Output Stream (ostream): This stream is used for writing data to a file (or any other output destination). You can use an output stream to write data to text files, log files, or even the console.
ofstream outfile("output.txt"); // Creates an output stream for writing to the file
outfile << "This is a line of text." << endl;
outfile.close();
fstream: This is a more flexible class that can be used for both reading and writing to the same file. It is a combination of ifstream and ofstream and is useful when you need to perform both input and output operations on the same file.
fstream file("example.txt", ios::in | ios::out); // Open file for both reading and writing
string data;
file >> data; // Read data from the file
file << "New data" << endl; // Write data to the file
file.close();
ifstream, ofstream, and fstream.When working with file streams, you can specify the mode in which you want to open the file. These modes control how the file is accessed and modified:
ios::in – Open file for reading.ios::out – Open file for writing.ios::app – Open file in append mode (all writes will be added to the end of the file).ios::binary – Open file as a binary file (no text-specific operations like newlines).ios::trunc – If the file exists, truncate it to zero length.ios::ate – Open file and move the read/write position to the end.ofstream file("example.txt", ios::app | ios::binary); // Open file for appending and binary data