Hello程序员注意到我看到了这段代码,但这让我感到困惑fseek(fp, sizeof(e) * (id - 1), SEEK_SET)
我不确定sizeof(e)*(id-1)
正在做什么?
//program to read a specified employee's record from a random access
//file. The file was previously created and initialized to hold a maximum of 5000 records
//and some data was later stored in the file.
#include <stdio.h>
//Declare Employee structure
struct Employee
{
int IdNo;
char FName[20];
char LName[20];
float Pay;
};
typedef struct Employee EMP;
void main ()
{
int id;
FILE *fp;
EMP e = {0, "", "", 0.0};
fp = fopen("Employee.dat", "r+b");
if (fp != NULL)
{
printf("\nEnter employee's id number (1-5000)");
scanf("%d", &id);
//locate the record, read it in, then close the file
fseek(fp, sizeof(e) * (id - 1), SEEK_SET);
fread(&e, sizeof(e), 1, fp);
fclose(fp);
if (e.IdNo != 0)
{
printf("Employee's record successfully retrieved from the file\n");
printf ("Id: %d\n", e.IdNo);
printf ("First Name: %s\n", e.FName);
printf ("Last Name: %s\n", e.LName);
printf ("Pay: %f\n", e.Pay);
}
else
printf("Employee record retrieved from file is empty\n");
}
else
printf("Error - could not open random access file\n");
}
答案 0 :(得分:0)
fseek
将文件位置移动到新位置。然后,当您从该流中读取时,它将检索该位置的内容。
在您的情况下,位置从头开始为sizeof(e) * (id - 1)
(SEEK_SET
)。这意味着您的文件中的id
记录(sizeof(e)
)的位置
sizeof(e) * (1 - 1)
,即0
sizeof(e) * (2 - 1)
,即第一条记录sizeof(e)
字节之后因此,当您fseek
使用id=2
时,它将位于第二条记录,然后将该记录读入名为e
的变量。
更新
解决您问题的评论。如果您想要浏览多个记录,可以按记录进行记录
fseek(fp, sizeof(e) * (id - 1), SEEK_SET);
fread(&e, sizeof(e), 1, fp);
// do something with record e
// seek and read further records ...
或一次读取多个记录到结构数组
EMP emps[10];
// ...
fseek(fp, sizeof(emps[0]) * (id - 1), SEEK_SET);
fread(emps, sizeof(emps[0]), 10, fp);
// do something with records in emps
或者你可以在没有干预的情况下阅读一个接一个的记录
fread(&e, sizeof(e), 1, fp);
// do something with first record
fread(&e, sizeof(e), 1, fp);
// do something with second record
// ...