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

时间:2018-05-12 20:04:34

标签: c++ function file

以下代码用于循环我之前打开的文件的最后十行。我认为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;
}

我想要做的另一种方法就是计算文件最初循环的次数,取出并减去10次,然后计算文件次数,然后输出接下来的10次,但似乎广泛的我想做什么。

是否有类似seekg的内容会转到文本文件中的特定行?或者我应该使用上面提出的方法吗?

编辑:我回答了我自己的问题:循环的东西就像是另外6行代码。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

如果你不关心最后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;
}
相关问题