我只想读取文本文件的最后一行(我在 UNIX 上,可以使用 Boost)。我知道的所有方法都需要扫描整个文件以获取根本没有效率的最后一行。有没有一种有效的方法来只获取最后一行?
此外,我需要它足够健壮,即使有问题的文本文件不断被另一个进程附加到它也能正常工作。
最佳答案
使用 seekg 跳转到文件末尾,然后回读直到找到第一个换行符。 下面是一些使用 MSVC 的示例代码。
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string filename = "test.txt";
ifstream fin;
fin.open(filename);
if(fin.is_open()) {
fin.seekg(-1,ios_base::end); // go to one spot before the EOF
bool keepLooping = true;
while(keepLooping) {
char ch;
fin.get(ch); // Get current byte's data
if((int)fin.tellg() <= 1) { // If the data was at or before the 0th byte
fin.seekg(0); // The first line is the last line
keepLooping = false; // So stop there
}
else if(ch == '\n') { // If the data was a newline
keepLooping = false; // Stop at the current position.
}
else { // If the data was neither a newline nor at the 0 byte
fin.seekg(-2,ios_base::cur); // Move to the front of that data, then to the front of the data before it
}
}
string lastLine;
getline(fin,lastLine); // Read the current line
cout << "Result: " << lastLine << '\n'; // Display it
fin.close();
}
return 0;
}
下面是一个测试文件。文本文件中的空数据、单行数据和多行数据均成功。
This is the first line.
Some stuff.
Some stuff.
Some stuff.
This is the last line.
关于c++ 只读取最后一行文本文件的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11876290/