如何使用C++以反向顺序(即从eof)读取文本文件?
发布于 2014-09-10 19:29:35
是的,但基本上你必须手动完成。
基本算法如下:
is.seekg(0, is.end)查找文件的末尾is.tellg()确定文件大小发布于 2014-09-10 19:41:10
如果文件足够小,所以整个内容都很容易被放入内存中,那么编写代码将文件向前读入字符串,然后在事实发生后反转该字符串,将会更快,也更容易。
如果内容不适合记忆,您将不得不使用nneonneo的解决方案。最好关掉缓冲。
发布于 2014-09-10 19:44:36
只需在istream类中使用seekg和相关函数即可。下面是一个有用的例子。测试过了。
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream in("file.txt");
// Get the length of the file
in.seekg(0, in.end);
int len = in.tellg();
// Start reading the file in reverse
char c;
while (len--)
{
in.seekg(len, in.beg);
in >> c;
cout << c;
}
}https://stackoverflow.com/questions/25773498
复制相似问题