Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
874 views
in Technique[技术] by (71.8m points)

c++ - seekg() function fails

I am trying to write some simple code which will read a text file but reads the first line twice. I thought this would be as simple as something like this

    std::ifstream file;
    file.open("filename", std::ios_base::in);
    std::string line;
    std::getline(file, line);
    // process line
    file.seekg(0, ios::beg);

    while (std::getline(file, line))
    {
        // process line
    }

However the seekg must fail as the first line is not processed twice. Any idea why?

PLEASE NOTE: This is not the problem I am faced with but a simplified version of it so as not to have to paste multiple classes code and multiple functions. The real problem involves a file pointer being passed to multiple functions in multiple classes. The first function may or may not be called and reads the first line of the file. The second function reads the whole file but must first call seekg to ensure we are at the beginning of the file.

I just used the code above to simplify the discussion.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Rather than seeking back to the beginning and reading the first line twice, I think I'd approach things with something like:

std::ifstream file("filename");

std::string line;

std::getline(file, line);
process(line);

do { 
    process(line);
} while (getline(file, line));

At the moment, this assumes that process doesn't modify line (but if needed, it's easy enough to make an extra copy of it for the first call).

Edit: given the modified requirements in the edited answer, it sounds like the seek is really needed. That being the case, it's probably cleanest to clear the stream before proceeding:

std::getline(file, line);
process1(line);

file.seekg(0);
file.clear();

process2(file);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...