seekg()函数失败 [英] seekg() function fails

查看:485
本文介绍了seekg()函数失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一些简单的代码,它将读取一个文本文件,但读取第一行两次。我认为这将像这样的简单

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
    }

但是,seekg必须失败,因为第一行未处理两次。任何想法为什么?

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

请注意:这不是我遇到的问题,但它的简化版本,以便不必粘贴多个类的代码和多个函数。真正的问题涉及到文件指针被传递到多个类中的多个函数。第一个函数可以调用也可以不调用,并读取文件的第一行。第二个函数读取整个文件,但必须首先调用seekg,以确保我们在文件的开头。

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.

我刚刚使用上面的代码来简化讨论。 / p>

I just used the code above to simplify the discussion.

推荐答案

而不是回到开头读第一行两次,我想我会用类似的东西: / p>

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));

现在,假设 process 不会修改(但如果需要,很容易为第一次调用创建一个额外的副本)。

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).

编辑:给定修改的要求在编辑的答案,听起来像seek真的需要。在这种情况下,在继续之前可能最干净清除流:

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);

这篇关于seekg()函数失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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