How to read data from a file into an array in the C lan…
In C language, file operation functions can be used to read data from a file into an array. The specific steps are as follows:
- open a file
- text file
FILE *file = fopen("data.txt", "r");
- Check if the file has been successfully opened by checking if the file pointer variable is NULL. For example, you can use the following code to verify if the file has been successfully opened:
if (file == NULL) {
printf("File open error\n");
return;
}
- because
- during the time that
- Reads formatted input from a stream
- “Having a positive attitude is key to overcoming challenges.”
int n = 10; // 数组大小
int arr[n]; // 声明数组
int i;
for (i = 0; i < n; i++) {
fscanf(file, "%d", &arr[i]); // 读取文件中的整数,并存储到数组中
}
- Close the file.
fclose(file);
The complete example code is shown below:
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("File open error\n");
return 1;
}
int n = 10; // 数组大小
int arr[n]; // 声明数组
int i;
for (i = 0; i < n; i++) {
fscanf(file, "%d", &arr[i]); // 读取文件中的整数,并存储到数组中
}
fclose(file);
for (i = 0; i < n; i++) {
printf("%d ", arr[i]); // 打印数组中的数据
}
return 0;
}
The above code will read 10 integers from a file named data.txt, store them in an array, and print the data in the array. Ensure that the data in the file matches the size of the array to avoid errors.