Code: [show] | [select all]
输出结果:
} return 0; fh.close(); cout << lines << endl; for (int i=lines.size()-1; i>=0; i--) lines.push_back(a); while ( getline(fh, a) ) if (!fh) cerr<<"can't open input file"<<endl; ifstream fh( fname.c_str() ); string a; vector<string> lines; string fname="read_line.cpp"; { int main(int argc, char *argv[] ) using namespace std; #include <vector> #include <fstream> #include <string> #include <iostream> (这里会多一个换行)
发现:getline会吃掉换行符,需要自己添加"\n"(可能导致结果不是原汁原味的),然后在倒序输出时,原本的“第一行”就多了个换行。
考虑:如果文件不大,可以尝试全部读进buffer,按 "\r\n"或者 "\n" 切割,然后反向获取并输出。
问题延伸:
如果文件达到10G,如何在控制在低内存占用的情况下逆序输出?
暂时考虑用 seek 操作,未完待续