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

Jim*_*Jim 21 c++ fstream

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

Xeo*_*Xeo 36

循环你的方式.

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

使用以下内容测试文件:

1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)

Testprogram:

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

    GotoLine(file, 8);

    string line8;
    file >> line8;

    cout << line8;
    cin.get();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出: 8


Mor*_*sen 6

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


Teo*_*aru 5

这是一个有效且简洁的示例,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;
}
Run Code Online (Sandbox Code Playgroud)