简体   繁体   English

在C ++中使用seekg的问题

[英]Problems using seekg in C++

I'm reading a file through a function like this: 我正在通过这样的函数读取文件:

#include <iostream>
#include <fstream>
#include <string>
...
void readfile(string name){

    string line;
    int p = 0;
    ifstream f(name.c_str());

    while(getline(f,line)){
        p++;
    }
    f.seekg(0);
    cout << p << endl;        

    getline(f,line);
    cout << line << endl;
}

Mi file has 3 lines: Mi文件有3行:

first
second
third

I expected the output: 我期待输出:

3
first

Instead I get: 相反,我得到:

3
(nothing)

why is my seekg not working? 为什么我的不工作?

Because seekg() fails if the stream has reached the end of the file ( eofbit is set), which occurs due to your getline looping. 因为如果流已经到达文件末尾(设置了eofbit ), seekg()失败,这是由于你的getline循环而发生的。 As sftrabbit implies, calling clear() will reset that bit and should allow you to seek properly. 正如sftrabbit所暗示的那样,调用clear()将重置该位并允许您正确搜索。 (Or you could just use C++11, in which seekg will clear eofbit itself.) (或者你可以使用C ++ 11,其中seekg将清除eofbit本身。)

Use iterators for read from the file 使用迭代器从文件中读取

std::fstream file( "myfile.txt", std::ios::out );
std::string data = std::string(
     std::istreambuf_iterator<char>( file ),
     std::istreambuf_iterator<char>() );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM