用c语言读取随机存取文件

用c语言读取随机存取文件,c,file,struct,C,File,Struct,您好程序员注意到我看到了这段代码,但这让我很困惑fseekfp,sizeofe*id-1,SEEK\u SET我不知道sizeofe*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

您好程序员注意到我看到了这段代码,但这让我很困惑fseekfp,sizeofe*id-1,SEEK\u SET我不知道sizeofe*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");
}
将文件位置移动到新位置。然后,当您从该流读取时,它将检索该位置的内容

在您的例子中,从SEEK_集合开始,位置是sizeofe*id-1。这意味着定位到文件中的第id个记录sizeofe

第一条记录的大小为sizeofe*1-1,即0 第二条记录的大小为sizeofe*2-1,位于第一条记录的大小之后 ... 因此,当您使用id=2进行fseek时,它将定位在第二条记录上,然后将该记录读入名为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
// ...

你能把你的问题编辑成1缩进代码,2澄清你的问题吗?这样更好吗,还是你还需要我向你展示我正在使用的代码@Thanatos我认为如果你缩进代码,代码会很有用。@Thanatos哦,好的,我明白了,但是那家伙发布了答案,他将重新编辑问题以符合答案,因为我真的想知道如何浏览文件中的许多记录。@user2861799,不要编辑你的问题以适应答案。这违背了网站的目的。