2017-02-12 189 views
0

編寫一個從文本文件讀取數據並將其輸出到二進制文件的程序。我很確定我正在閱讀文件,因爲當我打印信息時,它確實出來了。但是,寫入二進制文件是不正確的。文本文件的每一行寫着:寫入二進制文件

名姓ID GPA

其中,第一和最後一個名字是最多255個字符,該ID是無符號的4字節整數串,和GPA是一個4字節的浮點數。我從文件中讀取並打印出正確的信息,但輸出文件有問題。對於只有61字節的文本文件來說,它差不多是1.5 KB。我的代碼有什麼問題?

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

int textToBinary() 
{ 
    FILE * textfile = fopen("t2.txt", "r"); //Open and read text file 
    FILE * binfile = fopen("t2tobin.bin", "wb"); //Open writable bin file 

    unsigned char firstName[256]; 
    unsigned char lastName[256]; 
    unsigned int id; 
    float gpa; 
    char nLine[]= "\n"; 
    char space[]= " "; 

    if(NULL == textfile) //alerts and exits if binfile is not found 
    { 
     fprintf(stderr, "Failed to open file\n"); 
     fflush(stderr); 
     exit(1); 
    } 


    //implement a loop to continue until the end of the file 
    while(fscanf(textfile, "%s %s %d %f", firstName, lastName, &id, &gpa)!= EOF){ 
     //read one line of the text file 
     printf("%s %s %d %.1f\n", firstName, lastName, id, gpa); //print line information ((test)) 
     //Writing information to binary file 
     fwrite(firstName, sizeof(firstName), 1, binfile);//first name 
     fwrite(space, sizeof(space), 1, binfile);//space 
     fwrite(lastName, sizeof(lastName), 1, binfile);//last name 
     fwrite(space, sizeof(space), 1, binfile);//space 
     fwrite(&id, sizeof(unsigned int), 1, binfile);//ID 
     fwrite(space, sizeof(space), 1, binfile);//space 
     fwrite(&gpa, 4, 1, binfile);//gpa 

     fwrite(nLine, sizeof(nLine), 1, binfile);//new line 
    } 

    fclose(binfile); 
    fclose(textfile); 
    return 0; 
} 
+0

它的預期爲一個字符串的每一個寫使用256個字節。寫6個你得到1,5Kb!撇開:'fwrite(&gpa,4,1,binfile)'=>'fwrite(&gpa,sizeof(float),1,binfile)' –

+0

1.爲什麼不檢查'fopen'的返回值 - 即binabry一。 2.請格式化代碼以使其可讀 –

+1

在使用'fwrite'寫入文件時,使用'strlen'而不是'sizeof'。 – redxef

回答

0

的事情是,每次寫在輸出文件中的字符串時,你正好寫256個字節,因爲sizeof(firstName)等於256(見你的宣言,每個字符* 256 1個字節)。

正確的解決方法是在編寫字符串時使用strlen函數(字符串的長度)而不是sizeof。但C中的字符串必須以\0字符結尾。在讀取字符串時,默認情況下,字符數組(firstName,lastName)會以字符串填充,並在末尾填充\0字符。所以,你只需要輸出字符串,並在最後這一個字節,這就是爲什麼你寫一個字符串的實際字節量sizeof(string)+1

... 
fwrite(firstName, strlen(firstName)+1, 1, binfile);//first name 
fwrite(space, sizeof(space), 1, binfile);//space 
fwrite(lastName, strlen(lastName)+1, 1, binfile);//last name 
fwrite(space, sizeof(space), 1, binfile);//space 
fwrite(&id, sizeof(unsigned int), 1, binfile);//ID 
fwrite(space, sizeof(space), 1, binfile);//space 
fwrite(&gpa, 4, 1, binfile);//gpa 
... 
+0

你還可以提供回讀功能嗎? –