在C ++中有没有办法转到文本文件中的特定行?

时间:2011-03-05 23:36:08

标签: c++ fstream

如果我使用fstream打开文本文件,是否有一种简单的方法可以跳转到特定的行,例如第8行?

4 个答案:

答案 0 :(得分:35)

绕道而行。

#include <fstream>
#include <limits>

std::fstream& GotoLine(std::fstream& file, unsigned int num){
    file.seekg(std::ios::beg);
    for(int i=0; i < num - 1; ++i){
        file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    }
    return file;
}

file的搜索指针设置为行num的开头。

使用以下内容测试文件:

1
2
3
4
5
6
7
8
9
10

Testprogram:

int main(){
    using namespace std;
    fstream file("bla.txt");

    GotoLine(file, 8);

    string line8;
    file >> line8;

    cout << line8;
    cin.get();
    return 0;
}

输出:8

答案 1 :(得分:6)

如果每一行都有相同的长度,那么你可以使用istream :: seekg()跳转到该位置并从那里读取。

答案 2 :(得分:3)

如果行具有相同的长度,则这是一个有效std::getline()的工作且简洁的示例:

#include <iostream>
#include <fstream>
#include <string>

const int LINE = 4;

int main() {
std::ifstream f("FILE.txt");
std::string s;

for (int i = 1; i <= LINE; i++)
        std::getline(f, s);

std::cout << s;
return 0;
}

答案 3 :(得分:0)

一般情况下,没有,你必须使用与Xeo shows类似的策略走下去。

如果netrom says知道线条的长度是固定的,

即使线路长度未提前知道,但(1)你想要跳得很多,(2)你可以保证在你的同时没有人弄乱你的文件可以进行一次传递以形成索引,然后再使用它。