【问题标题】:Writing to binary file写入二进制文件
【发布时间】:2017-06-30 19:41:06
【问题描述】:

编写从文本文件中读取数据并将其输出到二进制文件的程序。我很确定我正在正确读取文件,因为当我打印信息时它确实会正确显示。但是,写入二进制文件是不正确的。文本文件的每一行都写着:

名字 姓氏 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;
}

【问题讨论】:

  • 这是预期的,因为每次写入字符串使用 256 个字节。写 6 个你得到 1,5Kb !旁白:fwrite(&amp;gpa, 4, 1, binfile) => fwrite(&amp;gpa, sizeof(float), 1, binfile)
  • 1.你为什么不检查来自fopen 的返回值 - 即二进制文件。 2.请格式化代码使其可读
  • 使用fwrite 写入文件时使用strlen 而不是sizeof
  • 二进制文件中通常不需要换行符;换行符适用于我们人类,二进制文件适用于其他程序。
  • 使用strlen()fwrite() 字符串将难以被fread() 回读。最好的方法是在写入字符串之前记录strlen() 的值。

标签: c input binary output


【解决方案1】:

问题是每次你在输出文件中写入一个字符串时,你正好写入 256 个字节,因为sizeof(firstName) 等于 256(参见你的声明,每个字符 1 个字节 * 256)。

正确的解决方案是在编写字符串时使用strlen 函数(字符串长度)而不是sizeof。但是 C 中的字符串必须以 \0 字符结尾。当您读取字符串时,默认情况下,您的字符数组(名字、姓氏)会在末尾填充字符串和 \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
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-09
    • 2015-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多