2014-09-12 58 views
0

我试图解决遗留系统中的文件读取问题。read()返回在某些系统上读取的错误字节数

这是一个32位Windows应用程序,仅在安装了相同SP,SDK和IDE的Windows7/SP1/64bit系统上进行测试和运行。 IDE是VS2010/SP1。

下面的代码有问题:

#define ANZSEL 20 

int ii, bfil, ipos; 

if ((bfil = open("Z:\\whatever.bla", O_RDONLY, 0)) == -1) { goto end; } // please don't complain about this; it's just here because I didn't want to rephrase the if == -1 above and because it's a legacy codebase; i also tried with UNC paths by the way with the same result 

    ii = read(bfil, &some_struct_instance, sizeof(some_struct)); 
    ipos = _lseek(bfil,0,SEEK_CUR); // ipos shows the correct position here, ie. sizeof(some_struct) 
    if (ii == sizeof(some_struct)) { 

     ii = read(bfil, &another_struct_instance, sizeof(another_struct)*ANZSEL); // ii here sometimes shows 15 instead of sizeof(another_struct)*ANZSEL 
     ipos = _lseek(bfil,0,SEEK_CUR); // ipos always shows the correct value of sizeof(some_struct) + sizeof(another_struct)*ANZSEL 
     if (ii == sizeof(another_struct)*ANZSEL) { 

     // should always come here as long as the files' long enough 

因此,大家可以看到,它应该是一个普通的老的二进制直接读入一些结构。我可以观察到的是,当我创建文件,并首先用memset/Zeromem清除结构以“init”所有填充字节为0x00而不是0xCC(这是微软在调试模式下将mem标记为未初始化的方式堆栈mem)问题在系统上消失,它以前不正确。

虽然它似乎很清楚,我怎么样,我可以“妥善”解决这一问题 - 指定O_BINARY开放()之类

if ((bfil = open("Z:\\whatever.bla", O_RDONLY|O_BINARY, 0)) == -1) 

我没有,为什么这会表现得如此不同的任何线索。 我试图通过这两个系统上的open()和read()的源代码,但由于我很少访问可以复制问题的唯一系统,所以我还找不到任何东西。

因此,我的问题是,如果任何人都可以指出为什么会发生这种情况并引用一些文档。

+0

@JerryCoffin我只是看了一下,但文件中没有任何0x1a。我总是使用相同的文件来测试所有系统顺便说一句。 – 2014-09-12 12:44:59

+0

http://msdn.microsoft.com/en-us/library/wyssk1bs.aspx - 在文本模式下,CR-LF对被替换为单个LF。另外可能值得注意的是(至少在Visual Studio中)'read'和'open' POSIX调用已被弃用。 – icabod 2014-09-12 12:46:15

+0

@icabod都是真的,但不应该在所有系统上导致相同的行为?顺便说一句,当然是impl。将被改为少量的字节顺序不可知论者,因为我们打算扩展到64位,也许系统有不同的endians,但我只是好奇我错过了什么read()和朋友 – 2014-09-12 12:49:08

回答

3

当文件包含值0x1a(又名control-Z)时,通常会发生这种情况。与之前的MS-DOS一样,Windows将control-Z解释为指示文本文件的结尾,因此当您以文本模式打开文件并且达到0x1a时,它将停止读取。

正如你已经发现的那样,以二进制模式打开文件修复了这个问题 - 0x1a不再被解释为表示文件结束。

+0

@eryksun:它实际上是操作系统本身(大多数情况下,无论如何)。 http://msdn.microsoft.com/en-us/library/windows/desktop/ms683462.aspx – 2014-09-12 14:28:23

相关问题