在C ++中有没有办法去去一个特定的行在一个文本文件? [英] In C++ is there a way to go to a specific line in a text file?

查看:140
本文介绍了在C ++中有没有办法去去一个特定的行在一个文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I open a text file using fstream is there a simple way to jump to a specific line, such as line 8?

推荐答案

#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;
}

设置文件的搜索指针 num 开头。

测试包含以下内容的文件:

Testing a file with the following content:

1
2
3
4
5
6
7
8
9
10

Testprogram:

Testprogram:

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

    GotoLine(file, 8);

    string line8;
    file >> line8;

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

输出: 8

这篇关于在C ++中有没有办法去去一个特定的行在一个文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆