In C++ programming, we use the iostream standard library, which provides the methods cin and cout for reading from input and writing to output.
To read from and write to files, we use a standard C++ library called fstream. Let’s take a look at the data types defined in the fstream library:
Data Type | Description |
---|---|
fstream | Used to create files, write information to files, and read information from files. |
ifstream | Used to read information from files. |
ofstream | Used to create files and write information to files. |
👇Click to Claim👇
👉C Language Knowledge Resource Collection
C++ File Stream Example: Writing to a File
Let’s look at a simple example of using C++ file streams to write data to the text file testout.txt.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("testout.txt");
if (filestream.is_open())
{
filestream << "Welcome to javaTiku\n";
filestream << "C++ Tutorial.\n";
filestream.close();
}
else cout << "Failed to open file.";
return 0;
}
Output:
The content of the text file testout.txt is set to: Welcome to javaTiku.C++ Tutorial.
C++ File Stream Example: Reading from a File
Let’s look at a simple example of using C++ file streams to read data from the text file testout.txt.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
string srg;
ifstream filestream("testout.txt");
if (filestream.is_open())
{
while (getline (filestream,srg) )
{
cout << srg <<endl;
}
filestream.close();
}
else {
cout << "Failed to open file."<<endl;
}
return 0;
}
Note: Before running the code, you need to create a text file named “testout.txt” with the following content: Welcome to javaTpoint. C++ Tutorial.
Output:
Welcome to javaTiku.C++ Tutorial.
C++ Read and Write Example
Let’s look at a simple example of using C++ file streams to write data to the text file testout.txt and then read data from the file.
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char input[75];
ofstream os;
os.open("testout.txt");
cout << "Writing to text file:" << endl;
cout << "Please enter your name:";
cin.getline(input, 100);
os << input << endl;
cout << "Please enter your age:";
cin >> input;
cin.ignore();
os << input << endl;
os.close();
ifstream is;
string line;
is.open("testout.txt");
cout << "Reading from text file:" << endl;
while (getline (is,line))
{
cout << line << endl;
}
is.close();
return 0;
}
Output:
Writing to text file: Please enter your name: Nakul Jain Please enter your age: 22 Reading from text file: Nakul Jain 22
Popular Recommendations
-
CLion Tutorial – Managing Included Files in CLion
-
C Language Algorithm – “Different Binary Search Trees II” Algorithm Problem
-
C++ Tutorial – Detailed Explanation of Signal Handling in C++