c语言

c语言怎么从文件中读取数据存入数组

小亿
765
2023-09-13 16:44:36
栏目: 编程语言

要从文件中读取数据并存入数组,可以按照以下步骤进行:

  1. 打开文件:使用fopen()函数打开文件,指定文件名和打开模式(例如,读取模式"r")。
FILE *file = fopen("filename.txt", "r");
if (file == NULL) {
printf("无法打开文件\n");
return;
}
  1. 读取文件数据:使用fscanf()函数循环读取文件中的数据,并将其存入数组中。在读取每个数据之前,需要先使用feof()函数判断文件是否到达结尾。
int array[100];  // 假设数组大小为100
int i = 0;
while (!feof(file) && i < 100) {
fscanf(file, "%d", &array[i]);
i++;
}
  1. 关闭文件:使用fclose()函数关闭文件。
fclose(file);

完整的代码如下所示:

#include <stdio.h>
int main() {
FILE *file = fopen("filename.txt", "r");
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
int array[100];  // 假设数组大小为100
int i = 0;
while (!feof(file) && i < 100) {
fscanf(file, "%d", &array[i]);
i++;
}
fclose(file);
// 打印数组中的数据
int j;
for (j = 0; j < i; j++) {
printf("%d ", array[j]);
}
printf("\n");
return 0;
}

上述代码将从名为filename.txt的文件中读取整数数据,并将其存入数组array中。读取的数据数量不能超过数组的大小(100),并且文件中的数据应以空格或换行符分隔。最后,代码会打印出数组中的数据。

0
看了该问题的人还看了