【问题标题】:Reading from Random access file in c从c中的随机访问文件中读取
【发布时间】: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,请勿编辑您的问题以适应答案。这违背了网站的目的。

标签: c file struct


【解决方案1】:

fseek 将文件位置移动到新位置。然后,当您从该流中读取时,它将检索该位置的内容。

在您的情况下,位置从一开始就是sizeof(e) * (id - 1) (SEEK_SET)。这意味着您文件中idth 记录 (sizeof(e)) 的位置

  • 第一条记录在sizeof(e) * (1 - 1),即0
  • 第二条记录在sizeof(e) * (2 - 1),在第一条记录sizeof(e)之后的字节
  • ...

所以,当您使用fseekid=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
// ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 2015-01-10
    • 1970-01-01
    相关资源
    最近更新 更多