所以我首先创建了一个创建二进制文件的程序,该程序如下所示:
#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");
fwrite(EmpList, sizeof(Employee), 4, p);
fclose(p);
}
创建一个文件并在其中存储4个员工数据结构。所以我需要在一个单独的程序中打开文件并读取数据并将其打印到ascii格式的stdout,所以我尝试了这个:
#include<stdio.h>
struct employee {
char firstname[40];
char lastname[40];
int id;
float GPA;
};
void read(FILE*);
int main()
{
FILE *p;
p = fopen("employee.dat", "rb+");
read(p);
fclose(p);
return 0;
}
void read(FILE *p)
{
struct employee data;
int knt = 0, a;
while(!feof(p)) {
fread(&data.id, sizeof(int), 1, p);
fread(data.firstname, sizeof(char), 40, p);
fgets(data.lastname, 40, p);
fscanf(p, "%f", &data.GPA);
printf("%s %s %d %f", data.firstname, data.lastname, data.id, data.GPA);
knt++;
}
}
我在while循环中使用fread,fgets和fscanf的原因是因为我想知道哪一个可行。我也知道while(!feof(p))
很糟糕,但我的教授说他希望我们暂时使用它,他会告诉我们如何尽快解决这个问题。我得到了一些输出,但它只是看似随机的符号和数字。