为什么它只在第二次正确读取文件

时间:2011-04-28 12:37:30

标签: c++ file-io

我有一个前64个字节的文件:

0x00:  01 00 00 10 00 00 00 20 00 00 FF 03 00 00 00 10  
0x10:  00 00 00 10 00 00 FF 03 00 00 00 10 00 00 FF 03  
0x20:  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  
0x30:  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 

当我在第26位读取4个字节的文件(模式读取和写入)时,我得到0,下一次(在第30位),我得到正确的4096。

代码是:

// read LastDirectoryBlockStartByte...
seekg(26);
char * pCUIBuffer = new char[4];
read(pCUIBuffer, 4);
const unsigned int x1 = gcount ();
const unsigned int LastDirectoryBlockStartByte = *(unsigned int *)pCUIBuffer;

// read LastDirectoryBlockNumberItems...
seekg(30);
read(pCUIBuffer, 4);
const unsigned int x2 = gcount ();
const unsigned int LastDirectoryBlockNumberItems = *(unsigned int *)pCUIBuffer;

使用gcount()我检查了字节被读取 - 这两次都是正确的4。 我不知道调试它。

----------编辑----------

当我使用以下代码(之前有一些虚拟代码)时,它正确读取:

char * pCUIBuffer = new char[4];
seekg(26);
read(pCUIBuffer, 4);
const unsigned int x1 = gcount ();
seekg(26);
read(pCUIBuffer, 4);
const unsigned int x2 = gcount ();
const unsigned int LastDirectoryBlockStartByte = *(unsigned int *)pCUIBuffer;

// read LastDirectoryBlockNumberItems...
seekg(30);
read(pCUIBuffer, 4);
const unsigned int x3 = gcount ();
const unsigned int LastDirectoryBlockNumberItems = *(unsigned int *)pCUIBuffer;

难点在于代码处于一种方法的开头。而“虚假的价值”显然与列出的代码无关。也许这是一个有冲洗或同步的技巧(但我试过......)或其他一些......

2 个答案:

答案 0 :(得分:1)

你说pCUIBuffer包含一个指针:

*(unsigned int *)pCUIBuffer;

然后你会在RAM中得到它指向的任何东西。这可能是任何事情。

答案 1 :(得分:0)

现在我正在写一个答案,因为我试图联系TonyK失败(我要求写一个答案)。

我的问题的完美答案是通过调用exceptions (eofbit | failbit | badbit)来启用例外。

入魔