【发布时间】:2021-10-26 17:23:51
【问题描述】:
是否可以直接从文件中读取任何特定数据而无需逐行或逐字符或逐块读取?
我已将少数学生的姓名、成绩、分数和通过年份存储在档案中。 以下是文件内容..
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(临时存储)中使用变量时使用的那样?
为什么我们不能像控制台一样访问文件中的数据(使用变量)?
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
-
@BhargavRao 其中许多 cmets 都是对 OP 的提示,甚至是部分答案。我不会称它们为“扩展讨论”,我希望你没有移动它们。