按行写文件:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ofstream outfile("output.txt", ios::out);
if(outfile.is_open() == true)
{
outfile << "first line!" << endl;
outfile << "second line!" << endl;
outfile << "last line!" << endl;
}
outfile.close();
return 0;
}
按行读文件:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream infile("output.txt", ios::in);
if(infile.is_open() == true)
{
string line;
while(infile.eof() == false)
{
getline(infile, line);
cout << line << endl;
}
}
infile.close();
return 0;
}