首页 > 解决方案 > 是否可以直接从文件中读取任何特定数据?

问题描述

是否可以直接从文件中读取任何特定数据,而无需逐行或逐字符或逐块读取?

我已将少数学生的姓名、成绩、分数和通过年份存储在档案中。以下是文件内容..

suraj
1
411
2020
john
3
400
2005
aman raj
5
389
2015

我只想打印过去一年的学生姓名john。下面是我的代码..

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
    char name[20];
    int roll;
    int total_marks;
    int passing_year;

    FILE *ptr;
    ptr = fopen("/storage/testing.txt", "r");
    if (ptr == NULL)
    {
        perror("File not found");
        exit(-1);
    }

    while (feof(ptr) == 0)
    {
        fgets(name, 20, ptr); // *Edit: The 2nd argument will less or equal to 20. 
        fscanf(ptr, "%d\n", &roll);//line 1
        fscanf(ptr, "%d\n", &total_marks);//line 2
        fscanf(ptr, "%d\n", &passing_year);//line 3

        if (strcmp(name, "john\n") == 0) //\n because fgets() add newline before \0 (only if size specified is more than no. of characters)
            printf("passing year of John was %d\n", passing_year);
    }
    return 0;
}

程序运行成功。以下是控制台的结果..

passing year of John was 2005

[Program finished]

在这里,我只需要,passing year of john但我必须阅读整个文件。当然,我可以改变指向位置,fseek()但我也必须读取最小的第 1 行、第 2 行和第 3 行。我想知道,有什么方法可以直接从文件中读取特定数据,因为我们用于控制台 I/O(临时存储)中的变量?为什么我们不能像控制台一样访问文件中的数据(使用变量)?

标签: cfilepointers

解决方案


如果每个学生在文件中占用相同的空间(并且该文件可能不再是文本文件),您可以fseek()到任何特定索引

suraj    |  1 | 411 | 2020\n           // 27 bytes per student
john     |  3 | 400 | 2005\n           // still a text file
aman raj |  5 | 389 | 2015\n           // uses more space than a
pmg      | 42 |  87 | 2000\n           // more efficient format

fseek(studentfile, 27 * 2, SEEK_SET);
fgets(buffer, 28, studentfile); // read aman raj data

推荐阅读