简体   繁体   English

ifstream 的问题

[英]Problem with ifstream

Look at this small code, it open a ifstream:看看这个小代码,它打开了一个 ifstream:

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

i have two problems.我有两个问题。

  1. after seekg, tellg return zero and when I read data it reads from beginning of file.在 seekg 之后,tellg 返回零,当我读取数据时,它从文件开头读取。
  2. operator >> seems doesn't work.运算符 >> 似乎不起作用。 always return zero!总是返回零!

////------------------------------------------------ ////------------------------------------------------ --
thanks for your attentions.感谢您的关注。 I found a crazy solution, but I get confused, if I call seekg two times, it works: see this code:我找到了一个疯狂的解决方案,但我很困惑,如果我调用 seekg 两次,它会起作用:请参阅以下代码:

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

really, what's happened?真的,发生了什么事?
////------------------------------------------------ ////------------------------------------------------ --

please help me...请帮我...
thanks in advanced.先谢谢了。

Check the failbit using _fcs.fail() after your seekg call to make sure you haven't specified an invalid file position.在您的seekg调用之后使用_fcs.fail()检查故障位,以确保您没有指定无效文件 position。

To double check the size use仔细检查大小使用

 _fcs.seekg(0,ios::end);
 int length = _fcs.tellg();

You also need to use .read() to get the len value, as your file is binary您还需要使用.read()来获取 len 值,因为您的文件是二进制文件

In binary mode, >> is not supposed to work, you have to use ostream::write.在二进制模式下,>> 不应该工作,你必须使用 ostream::write。

Does your file actually exists and have a size?您的文件是否真的存在并且有大小? if note, you can't "move" to an arbitrary point in an empty file.如果注意,您不能“移动”到空文件中的任意点。

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

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