c++ 只读取最后一行文本文件的最快方法?

标签 c++ iostream seek

我只想读取文本文件的最后一行(我在 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/

相关文章:

c - 写入标准输入,然后将流移回 1 个位置

C++:传递给非好友的友元函数

c++ - 如何在 C++ 中执行另一个 while 循环期间获取流输入

c++ - 在多线程应用程序中,如果函数不修改/读取数据或修改/读取临时数据,2个以上线程可以访问同一个函数吗?

c++ - 使用相同的 fstream 读取和写入相同的文件

C++ 持久性生物操作

file - 如何计算平均搜索时间?

c++ - 用编译器强制第一个实例

C++:检查 istream 是否有非空格、非制表符、非换行符而未提取字符

algorithm - 就像有cache oblivious 和cache optimal 算法一样,有seek optimal 算法吗?