租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

c语言如何从文件中读取数据存入数组,C语言如何从文章中读取单词数量

发布时间:2023-09-14 07:56:20

c语言如何从文件中读取数据存入数组

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