2012-02-07 185 views
14

嗨,在我的項目中,我必須讀取一個.bin文件,其中包含short(16 bit values)形式的傳感器數據。我正在使用fread函數將其寫入緩衝區,但我覺得讀入不正確。我的意思是在我寫的和我讀到的內容之間沒有一致性。你們可以建議這裏出了什麼問題嗎?這不是我的項目中的代碼...我只是試圖在這裏驗證freadfwrite函數。如何使用fread和fwrite函數讀取和寫入二進制文件?

#include<stdio.h> 
void main() 
{ 
    FILE *fp = NULL; 

    short x[10] = {1,2,3,4,5,6,5000,6,-10,11}; 
    short result[10]; 

    fp=fopen("c:\\temp.bin", "wb"); 

    if(fp != NULL) 
    { 
     fwrite(x, 2 /*sizeof(short)*/, 10 /*20/2*/, fp); 
     rewind(fp); 
     fread(result, 2 /*sizeof(short)*/, 10 /*20/2*/, fp); 
    } 
    else 
     exit(0); 

    printf("\nResult"); 
    printf("\n%d",result[0]); 
    printf("\n%d",result[1]); 
    printf("\n%d",result[2]); 
    printf("\n%d",result[3]); 
    printf("\n%d",result[4]); 
    printf("\n%d",result[5]); 
    printf("\n%d",result[6]); 
    printf("\n%d",result[7]); 
    printf("\n%d",result[8]); 
    printf("\n%d",result[9]); 

    fclose(fp) 
} 

後,我做了FREAD()(十六進制值):

temp.bin: 
01 02 03 04 05 06 e1 8e 88 06 ef bf b6 0b... 

後,我做

stdout: 
Result 
0 
914 
-28 
-28714 
-32557 
1 
512 
-32557 
908 
914 
+0

你嘗試過關閉然後重新打開該文件?如果您寫入文件並立即讀取,我不確定文件的內容。您可能必須先關閉它才能確保數據被刷新?另外,請確保打開它以便第二次讀取... – aardvarkk 2012-02-07 16:35:17

回答

12

用模式w+(讀寫)打開文件。下面的代碼工作:

#include<stdio.h> 
int main() 
{ 
    FILE *fp = NULL; 

    short x[10] = {1,2,3,4,5,6,5000,6,-10,11}; 
    short result[10]; 
    int i; 

    fp=fopen("temp.bin", "w+"); 

    if(fp != NULL) 
    { 
     fwrite(x, sizeof(short), 10 /*20/2*/, fp); 
     rewind(fp); 
     fread(result, sizeof(short), 10 /*20/2*/, fp); 
    } 
    else 
     return 1; 

    printf("Result\n"); 
    for (i = 0; i < 10; i++) 
     printf("%d = %d\n", i, (int)result[i]); 

    fclose(fp); 
    return 0; 
} 

隨着輸出:

Result 
0 = 1 
1 = 2 
2 = 3 
3 = 4 
4 = 5 
5 = 6 
6 = 5000 
7 = 6 
8 = -10 
9 = 11 
+0

@ RichardJ.RossIII在我的答案中有幾處更正。 – trojanfoe 2012-02-07 17:27:05

3

當你打開文件,你忘了允許和fwrite()閱讀:

fp=fopen("c:\\temp.bin", "wb"); 

應該是:

fp=fopen("c:\\temp.bin", "w+b"); 
+2

模式'rwb'不被識別。我認爲你的意思是'w + b'或'wb +'。 – pmg 2012-02-07 16:42:13

+0

@pmg'rwb'適用於我,Mac OSX Lion上的gcc。 – 2012-02-07 16:43:00

+2

@理查德:這不是標準。 [見這裏](http://port70.net/~nsz/c/c99/n1256.html#7.19.5.3)或[在本PDF中](http://www.open-std.org/JTC1/sc22 /wg14/www/docs/n1256.pdf)。 – pmg 2012-02-07 16:44:20

相關問題