In this tutorial, you will learn how to use streams in C++ to read and write files. Specifically, we will cover the use of ifstream (input file stream) and ofstream (output file stream) classes provided by the C++ Standard Library.
By the end of this tutorial, you will be able to:
Prerequisites: Basic knowledge of C++ programming is required to fully understand the concepts explained in this tutorial.
In C++, a stream is a sequence of bytes where we can write or read data. A file stream is just a stream associated with a file.
Use the ifstream class to read data from a file. Here's how to do it:
Use the ofstream class to write data to a file. Here's how to do it:
Let's see some practical examples.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream myfile; // Create an object of ifstream
myfile.open ("example.txt"); // Open a file
if (myfile.is_open()) { // If the file is open, read from it
string line;
while (getline (myfile, line)) {
cout << line << '\n'; // Output the text from the file
}
myfile.close(); // Close the file
}
else cout << "Unable to open file";
return 0;
}
In the above example, we're reading line by line from the file "example.txt" and printing each line.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile; // Create an object of ofstream
myfile.open ("example.txt"); // Open a file
if (myfile.is_open()) { // If the file is open, write to it
myfile << "Hello World!\n"; // Write to the file
myfile.close(); // Close the file
}
else cout << "Unable to open file";
return 0;
}
In this example, we're writing the string "Hello World!" to the file "example.txt".
In this tutorial, you've learned how to use ifstream and ofstream in C++ to read from and write to files. You can now perform basic file operations using streams in C++.
Next, you might want to learn more about handling errors during file operations, or explore more advanced file handling techniques.
Solutions and explanations will be provided in the next tutorial. To practice further, you may want to try modifying these programs or creating your own.