2017-02-12 185 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

你还可以提供回读功能吗? –