c - 是否可以直接从文件中读取任何特定数据?
问题描述
是否可以直接从文件中读取任何特定数据,而无需逐行或逐字符或逐块读取?
我已将少数学生的姓名、成绩、分数和通过年份存储在档案中。以下是文件内容..
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(临时存储)中的变量?为什么我们不能像控制台一样访问文件中的数据(使用变量)?
解决方案
如果每个学生在文件中占用相同的空间(并且该文件可能不再是文本文件),您可以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
推荐阅读
- reactjs - 唯一地折叠每个按钮,而不是一次全部折叠
- sql - oracle 触发器和 json_value
- php - 如何在 PHP 类函数中设置变量
- unix - 如何为特定文件的字数添加前缀零以使总数为 8 位并将输出打印到文件
- xml - 如何使用谷歌应用脚本在谷歌表格中导入带有 xml 响应的 txt 文件?
- java - 升级到 groovy 2.5 时数据驱动的 Spock 测试失败
- angular - 角 loadChildren 没有做任何事情
- python - 在 PyCharm 中安装包的问题
- css - 使用 flex-basis 时 Flex 项目溢出
- html5-video - chrome 中的 html5-video 大中心播放按钮,如 firefox