Read / Write a Text File
How to read a text file using C++? Here is an example:
Let's create a text file "myTest.txt", and type the following
lines:
This is a test file This is the second line of the test file Then let's write a C++ program to read this file:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
//using ifstream to input file stream from a text file
ifstream myfile ("myTest.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Can't open file";
return 0;
}
To write strings to a text file, we can write a program like this:
#include <iostream>
#include <fstream>
using namespace std; int main () {
//using ofstream to output strings to a text file
ofstream myfile ("myTest.txt");
if (myfile.is_open())
{
myfile << "This is a test.\n";
myfile << "I am learning C++.\n";
myfile.close();
}
else cout << "Can't open file";
return 0;
}
In the above two examples, we include Stream class "fstream"
as a header file to both read and write from/to files. Then for reading
(input) from a text file, we use "ifstream" , for writing (output)
to a text file, we use "ofstream".
|