2011-05-05 56 views
0

看这个小的代码,它打开一个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; 
} 

我有两个问题。

  1. seekg后,所以tellg返回零,当我读数据从文件的开头读取。
  2. 运营商>>似乎不起作用。总是归零!

//// ---------------------------------------- --------
感谢您的关注。我发现了一个疯狂的解决方案,但我感到困惑! 如果我叫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; 
} 

真的,发生了什么?
//// -------------------------------------------- ----

请帮我...
感谢先进。

回答

0

在二进制模式下,>>不应该工作,你必须使用ostream :: write。

您的文件是否真的存在并且有一个大小?如果注意,你不能“移动”到空文件中的任意点。

+0

是的,它的存在。这是一个二进制文件,我也用十六进制编辑器打开它。我想读不写! :( – Mostafa 2011-05-05 03:42:29

+0

对不起,误读。使用istream :: read然后。 – 2011-05-05 03:46:07

+0

我使用它,但为什么seekg没有改变get指针!!!! – Mostafa 2011-05-05 03:52:48

2

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

仔细检查大小使用

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

你还需要使用.read()得到LEN值,因为文件是二进制

+0

我完成了,我编辑了我的问题,再次看到它.. 。 – Mostafa 2011-05-05 05:41:26

+0

@Mostafa我不知道为什么你必须调用它两次。这次你使用了一个不同的幻数(0x402与0x404),所以我不确定你的文件在哪里引导你。检查文件的大小,并确保不超出这个大小。当你说它正在工作时,你的意思是你已经读过你正在寻找的值,或者只是你已经移动了文件指针? – jonsca 2011-05-05 06:11:52