【问题标题】:Use fseek to print any arbitrary record使用 fseek 打印任意记录
【发布时间】:2021-03-08 21:52:57
【问题描述】:

如何使用 fseek 查找任意记录并打印该记录?特别是第三条记录。
文件格式:

first name
last name
gpa

我的代码(假设文件已经存在):

typedef struct
{
    char first [20], last[20];
    double gpa;
} Student;

int main ()
{
    Student student;
    FILE* file = fopen ("gpa.dat", "r+");

    fseek(file, sizeof(Student), SEEK_END);
    fread(&student, sizeof(student), 1, file);

    printf("Name: %s %s\nGPA: %lf\n", student.first, student.last, student.gpa);

    fclose(file);
    return 0;
}

所以如果第三条记录是

xxx
yyy
3.56

这就是我要打印的内容

【问题讨论】:

  • 为什么必须使用fseek 来完成这项任务?
  • 是文本文件还是固定大小记录的二进制文件?
  • gpa.dat 是如何创建的?
  • fseek 以字节为单位移动文件指针,可以从文件的开头SEEK_SET 或任何当前位置SEEK_CUR 或从结尾向后移动SEEK_END
  • gpa.dat 是通过从 stdin 获取输入然后使用 fwrite 创建的,如果这就是你的意思? @约翰尼莫普。它是一个文本文件,具有可增长的大小记录@Barmar。

标签: c file fseek


【解决方案1】:

如果您正在读取二进制文件,则应在打开模式下使用b 修饰符。

要获取任意记录,请将sizeof(Student) 乘以零基记录号。并使用SEEK_SET 从文件开头开始计数。

int main ()
{
    Student student;
    FILE* file = fopen ("gpa.dat", "rb+");
    int record_num = 3;

    fseek(file, record_num * sizeof(Student), SEEK_SET);
    fread(&student, sizeof(student), 1, file);

    printf("Name: %s %s\nGPA: %lf\n", student.first, student.last, student.gpa);

    fclose(file);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2020-08-16
    • 2019-04-30
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 2013-03-26
    相关资源
    最近更新 更多