将数据写入二进制文件

Writing data to binary file

我正在尝试创建一个二进制 .dat 文件,所以我尝试了

#include<stdio.h>
struct employee {
    char firstname[40];
    char lastname[40];
    int id;
    float GPA;
 };
 typedef struct employee Employee;

void InputEmpRecord(Employee *);
void PrintEmpList(const Employee *);
void SaveEmpList(const Employee *, const char *);
int main()
{
    Employee EmpList[4];
    InputEmpRecord(EmpList);
    PrintEmpList(EmpList);
    SaveEmpList(EmpList, "employee.dat");
    return 0;
}

void InputEmpRecord(Employee *EmpList)
{
    int knt;
    for(knt = 0; knt < 4; knt++) {
        printf("Please enter the data for person %d: ", knt + 1);
        scanf("%d %s %s %f", &EmpList[knt].id, EmpList[knt].firstname,EmpList[knt].lastname, &EmpList[knt].GPA);
    }
}

void PrintEmpList(const Employee *EmpList)
{
    int knt;
    for(knt = 0; knt < 4; knt++) {
        printf("%d %s %s %.1f\n", EmpList[knt].id, EmpList[knt].firstname,EmpList[knt].lastname, EmpList[knt].GPA);
    }
}

void SaveEmpList(const Employee *EmpList, const char *FileName)
{
    FILE *p;
    int knt;
    p = fopen(FileName, "wb"); //Open the file
    fwrite(EmpList, sizeof(Employee), 4, p); //Write data to binary file
    fclose(p);
}

我给它输入:

10 John Doe 64.5
20 Mary Jane 92.3
40 Alice Bower 54.0
30 Jim Smith 78.2

因此 printf 语句起作用并将正确的信息打印到屏幕,但创建的 employee.dat 文件只是随机符号。该文件当前不存在,因此程序正在创建它。

扩展@adamdc78 和我的评论:

正在以 1 和 0 的形式将数据写入文件。正是您阅读它的方式导致您看到 "bunch of random symbols"。文本编辑器希望数据以 ASCII 或 Unicode 格式(以及其他格式)编码

对于ASCII,原始二进制文件的每个字节代表一个字符。这种编码对于普通的英语及其标点符号来说已经足够了,但对于全球使用的所有符号来说还不够。

所以他们想出了 Unicode,它使用可变字节长度编码来捕获全球使用的所有语言符号(lot,不仅仅是 A-Z, a-z.)

希望这对您有所帮助。

稍后我会添加一些阅读 material 的链接。另请注意:有人可能会迂腐地评论我刚刚写的东西不太准确。这就是我引用链接的原因。

您正在写入整个员工记录列表 4 次。而不是

for(knt = 0; knt < 4; knt++) {
    if(EmpList[knt].firstname != NULL && EmpList[knt].lastname != NULL) {
         fwrite(EmpList, sizeof(Employee), 4, p);
    }
}

你可以只使用:

fwrite(EmpList, sizeof(Employee), 4, p);

如果你必须有支票,你可以使用:

for(knt = 0; knt < 4; knt++) {
    if(EmpList[knt].firstname != NULL && EmpList[knt].lastname != NULL) {
         fwrite(EmpList+knt, sizeof(Employee), 1, p);
    }
}