要从文件中读取数据并存入数组,可以按照以下步骤进行:
- 打开文件:使用
fopen()
函数打开文件,指定文件名和打开模式(例如,读取模式"r"
)。
FILE *file = fopen("filename.txt", "r"); if (file == NULL) { printf("无法打开文件\n"); return; }
- 读取文件数据:使用
fscanf()
函数循环读取文件中的数据,并将其存入数组中。在读取每个数据之前,需要先使用feof()
函数判断文件是否到达结尾。
int array[100]; // 假设数组大小为100 int i = 0; while (!feof(file) && i < 100) { fscanf(file, "%d", &array[i]); i++; }
- 关闭文件:使用
fclose()
函数关闭文件。
fclose(file);
完整的代码如下所示:
#includeint 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),并且文件中的数据应以空格或换行符分隔。最后,代码会打印出数组中的数据。