繁体   English   中英

从C ++文件中读取特定行

[英]Reading specific lines from a file in C++

以下代码旨在遍历我先前打开的文件的最后十行。 我认为seekg函数引用二进制文件,并且仅处理单个字节的数据,因此这可能是我的问题。

    //Set cursor to 10 places before end
    //Read lines of input
    input.seekg(10L, ios::end);

    getline(input, a);

    while (input) {
        cout << a << endl;
        getline(input, a);
    }

    input.close();
    int b;
    cin >> b;
    return 0;
}

我想做的另一种方法是只计算文件最初循环通过的次数,将其减去十次,然后遍历文件该次数,然后输出下一个十次,但这似乎很广泛我想要做。

是否有类似seekg内容会转到文本文件中的特定行? 还是应该使用上面建议的方法?

编辑:我回答了我自己的问题:循环的事情就像6多行代码。

向后搜索换行符10次,或直到文件光标小于或等于零为止。

如果您不关心最后10行的顺序,则可以执行以下操作:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>

int main() {

    std::ifstream file("test.txt");
    std::vector<std::string> lines(10);

    for ( int i = 0; getline(file, lines[i % 10]); ++i );

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM