【发布时间】:2014-03-23 20:48:38
【问题描述】:
你好程序员注意我看到了这段代码,但这让我很困惑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");
}
【问题讨论】:
-
您能否将您的问题编辑为 1) 缩进代码和 2) 澄清您的要求?
-
是更好还是你还需要我给你看我正在处理的代码@Thanatos
-
我认为代码会很有用,如果你把它缩进的话。
-
@Thanatos 哦,好吧,我明白了,但是那个人发布了答案,会重新编辑问题以适应答案,因为我真的很想知道如何浏览文件中的许多记录。
-
@user2861799,请勿编辑您的问题以适应答案。这违背了网站的目的。