#include <fstream>
#include <string>
using namespace std;
int main()
{
// 读文件, 保存至fileContent中
string openFile = "C:\\1.txt";
ifstream inf;
inf.open(openFile.c_str(), ios::in);
string lineContent;
string fileContent;
while (getline(inf, lineContent))
{
fileContent += lineContent +'\n';
}
inf.close();
//写文件
string outFile = "C:\\2.txt";
ofstream of(outFile.c_str());
of << fileContent <<endl;
of.close();
return 0;
}
来自C++ Primer 的读文件方法:
#include <iostream>
#include <vector>
#include <sstream>
#include <fstream>
using namespace std;
int FileToVector(string & fileName, vector<string> &val)
{
ifstream input(fileName.c_str());
if (!input)
{
return -1;
}
string line;
while(getline(input, line))
{
val.push_back(line);
}
input.close();
return 0;
}
int main(int argc, const char * argv[])
{
string path = "C:\\test.txt";
vector<string> g_val;
FileToVector(path, g_val);
string word;
stringstream ss;
for (vector<string>::iterator iter = g_val.begin(); iter != g_val.end();iter++)
{
ss.str(*iter);
while(ss >> word)
{
cout<<word<<" ";
}
cout<<endl;
ss.clear();
}
return 0;
}