简体   繁体   English

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

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

The following code is meant to loop through the last ten lines of a file that I have previously opened. 以下代码旨在遍历我先前打开的文件的最后十行。 I think the seekg function refers to binary files and only go through individual bytes of data, so that may be my issue here. 我认为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;
}

The other method I was thinking of doing is just counting the number of times the file gets looped through initially, taking that and subtracting ten, then counting through the file that number of times, then outputting the next ten, but that seems extensive for what I want to do. 我想做的另一种方法是只计算文件最初循环通过的次数,将其减去十次,然后遍历文件该次数,然后输出下一个十次,但这似乎很广泛我想要做。

Is there something like seekg that will go to a specific line in the text file? 是否有类似seekg内容会转到文本文件中的特定行? Or should I use the method I proposed above? 还是应该使用上面建议的方法?

EDIT: I answered my own question: the looping thing was like 6 more lines of code. 编辑:我回答了我自己的问题:循环的事情就像6多行代码。

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

If you don't care about the order of the last 10 lines, you can do this: 如果您不关心最后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