我試圖解決遺留系統中的文件讀取問題。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()的源代碼,但由於我很少訪問可以複製問題的唯一系統,所以我還找不到任何東西。
因此,我的問題是,如果任何人都可以指出爲什麼會發生這種情況並引用一些文檔。
@JerryCoffin我只是看了一下,但文件中沒有任何0x1a。我總是使用相同的文件來測試所有系統順便說一句。 – 2014-09-12 12:44:59
http://msdn.microsoft.com/en-us/library/wyssk1bs.aspx - 在文本模式下,CR-LF對被替換爲單個LF。另外可能值得注意的是(至少在Visual Studio中)'read'和'open' POSIX調用已被棄用。 – icabod 2014-09-12 12:46:15
@icabod都是真的,但不應該在所有系統上導致相同的行爲?順便說一句,當然是impl。將被改爲少量的字節順序不可知論者,因爲我們打算擴展到64位,也許系統有不同的endians,但我只是好奇我錯過了什麼read()和朋友 – 2014-09-12 12:49:08