【C语言】如何从文件中读取数据?

2024-07-06 1979阅读

如何从文件中读取数据?

【C语言】如何从文件中读取数据?
(图片来源网络,侵删)

在C语言中,你可以使用标准库中的函数来从文件中读取数据。下面是一些常用的方法:

使用 fscanf() 读取格式化数据

fscanf() 函数类似于 scanf(),但它从文件中读取数据而不是从标准输入。

c复制代码

#include
int main() {
FILE *file;
int number;
float f;
char str[100];
file = fopen("data.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// 从文件中读取数据
while (fscanf(file, "%d %f %s", &number, &f, str) == 3) {
printf("Read: %d, %f, %s\n", number, f, str);
}
if (ferror(file)) {
perror("Error reading file");
} else {
printf("End of file reached.\n");
}
fclose(file);
return 0;
}

在上面的代码中,fscanf() 从文件中读取一个整数、一个浮点数和一个字符串,直到文件结束或出现错误。

使用 fgets() 读取一行

fgets() 函数用于从文件中读取一行文本。

c复制代码

#include
#include
int main() {
FILE *file;
char line[100];
file = fopen("text.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// 从文件中读取每一行
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
if (ferror(file)) {
perror("Error reading file");
} else {
printf("End of file reached.\n");
}
fclose(file);
return 0;
}

fgets() 将读取一行,包括换行符(如果有的话),并将其存储在提供的缓冲区中。

使用 fread() 读取二进制数据

如果你需要读取二进制数据或大量的数据块,可以使用 fread() 函数。

c复制代码

#include
#define BUFFER_SIZE 10
int main() {
FILE *file;
int buffer[BUFFER_SIZE];
size_t itemsRead;
file = fopen("binary_data.bin", "rb");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// 从文件中读取二进制数据
itemsRead = fread(buffer, sizeof(int), BUFFER_SIZE, file);
if (itemsRead > 0) {
printf("Read %zu integers: ", itemsRead);
for (size_t i = 0; i
printf("%d ", buffer[i]);
}
printf("\n");
}
if (ferror(file)) {
perror("Error reading file");
} else {
printf("End of file reached.\n");
}
fclose(file);
return 0;
}

在上面的代码中,fread() 尝试从文件中读取 BUFFER_SIZE 个整数。fread() 返回实际读取的项数,这个数可能会少于请求的项数,尤其是当接近文件末尾时。

在使用 fread() 时,你通常需要检查返回值以确保读取了预期数量的项。

注意事项

  • 在读取文件时,总是检查返回值以确保操作成功。
  • 使用 ferror() 函数来检查是否发生了读取错误。
  • 使用 feof() 函数来检查是否已到达文件末尾。
  • 在完成文件操作后,使用 fclose() 关闭文件。

    这些是从文件中读取数据的几种基本方法。根据你的具体需求和数据格式,你可能需要选择最适合你的方法。

VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]