首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ifstream问题

ifstream问题
EN

Stack Overflow用户
提问于 2011-05-05 03:32:31
回答 1查看 1.5K关注 0票数 0

看看这个小代码,它打开了一个ifstream:

代码语言:javascript
复制
std::ifstream _fcs; 

bool openFile(char* path)
{
    istream::pos_type pos; 
    int tmp = 0;

    _fcs.open(path, fstream::binary | fstream::in);

    if(!_fcs.is_open())
        return false;

    tmp = 0;
    pos = 0x404;

    _fcs.seekg(0x404);
    pos = _fcs.tellg(); /// return zero

    _fcs >> tmp; /// 
    _fcs.read((char*)&tmp, 4);

    return true;
}

我有两个问题。

  1. 在seekg之后,tellg返回零,当我读取数据时它从文件开始读取。
  2. 运算符>>似乎不起作用。始终返回零!

////

谢谢你的关心。我找到了一个疯狂的解决方案,但我很困惑!如果我调用seekg两次,它会工作,请参见下面的代码:

代码语言:javascript
复制
 bool openFile(char* path)
 {
    istream::pos_type pos; 
    int tmp;
    bool fail;

    _fcs.open(path, fstream::binary | fstream::in);

    if(!_fcs.is_open())
        return false;

    _fcs.seekg(0x402);
    _fcs.seekg(0x402); /// When it comments, the tellg returns 0. am i crazy!?

    fail = _fcs.fail();
    assert(!fail);

    pos = _fcs.tellg(); /// return 0x402!!!

     /// _fcs >> tmp;
    _fcs.read((char*)&tmp, 4);

    return true;
}

真的,发生什么事了?

////

请帮帮我..。

谢谢你的进阶。

EN

回答 1

Stack Overflow用户

发布于 2011-05-05 04:36:37

_fcs.fail()调用后使用seekg检查故障位,以确保没有指定无效的文件位置。

要重复检查大小使用

代码语言:javascript
复制
 _fcs.seekg(0,ios::end);
 int length = _fcs.tellg();

您还需要使用.read()来获取len值,因为您的文件是二进制的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5892348

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档