How to read numeric values from a txt file in C language?
In C language, you can use the fscanf function to read numbers from a txt file.
Here is an example: suppose we have a file named input.txt that contains a series of numbers, with each number on a separate line. We can use the following code to read these numbers:
#include <stdio.h>
int main() {
FILE *file;
file = fopen("input.txt", "r"); // 打开文件
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
int num;
while (fscanf(file, "%d", &num) != EOF) { // 读取文件中的数字,直到文件结尾
printf("%d\n", num);
}
fclose(file); // 关闭文件
return 0;
}
In the above code, the fopen function is used to open a file, with the first parameter being the file name and the second parameter being the open mode. We use “r” mode to indicate read-only mode, which means reading the file.
Next, we use a loop to repeatedly use the fscanf function to read numbers from the file. The fscanf function takes a file pointer as its first argument, a formatting string specifying the data type to read as its second argument. In this case, we use “%d” to indicate reading integers. The third argument is the address of the variable that will receive the read value.
Finally, we use the fclose function to close the file in order to release resources.
After using the fopen function to open a file, we must check if the file was successfully opened by verifying if the file pointer is not NULL. If the file pointer is NULL, it indicates that the file opening was unsuccessful.