2016-04-27 19 views
-2

我想這也適用於很多其他語言。C中的二進制IO中發生了什麼?

我在這裏有這個代碼,我想知道什麼是真正發生的事情,以及如何我可以解釋是什麼寫入到文件...

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() 
{ 
    //Initialize a variable and load it with input using scanf 
    char write[100] = "Write this."; 

    FILE *fp = fopen("./binFile.txt", "w+"); 
    fwrite(write, sizeof(write[0]), sizeof(write)/sizeof(write[0]), fp); 
    fclose(fp); 
} 

,然後當我打開文本文件,我看到這個...

5772 6974 6520 7468 6973 2e00 0000 0000 
0000 0000 0000 0000 0000 0000 0000 0000 
0000 0000 0000 0000 0000 0000 0000 0000 
0000 0000 0000 0000 0000 0000 0000 0000 
0000 0000 0000 0000 0000 0000 0000 0000 
0000 0000 0000 0000 0000 0000 0000 0000 
0000 0000 

但是我在看到這裏發生了什麼時遇到了一些麻煩。這個文本如何分解爲二進制文件?

+0

您正在使用顯示文件中字符的十六進制代碼的程序打開文本文件。 '57'表示'W','72'表示'r'等。如果您在文本編輯器中打開文件,您應該看到'Write this.',然後該編輯器顯示空字節 –

+2

認真?你從來沒有聽說過ASCII碼? – John3136

+0

你是否期待任何形式的輸出? – BLUEPIXY

回答

2

您正在將整個字符數組寫入文件,並且將char數組初始化爲12個字符,後跟所有零值。這就是爲什麼你看到字符串後的所有零,也許這會讓你的系統認爲它是一個二進制文件。因此,如果要編寫字符串,請使用以下代碼:

fwrite(write, sizeof(write[0]), strlen(write), fp);