2014-09-12 60 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

相關問題