我正在尝试创建一个二进制.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文件只是随机符号。该文件当前不存在,因此程序正在创建它。
答案 0 :(得分:2)
您正在编写员工记录的完整列表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);
}
}
答案 1 :(得分:0)