How can C language use EOF to determine the end of a file?
In C language, we can use a combination of a while loop and the scanf function along with EOF (End of File) to determine if a file has ended. Below is an example code:
#include <stdio.h>
int main() {
FILE *file;
int num;
// 打开文件
file = fopen("filename.txt", "r");
// 检查文件是否打开成功
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
// 读取文件中的整数,并判断文件是否结束
while (fscanf(file, "%d", &num) != EOF) {
printf("%d\n", num);
}
// 关闭文件
fclose(file);
return 0;
}
In the code above, the fscanf function attempts to read one integer from the file each time and stores it in the num variable. When the fscanf function returns EOF, it means the file has ended and the loop stops. Otherwise, the integer read is printed on the screen. Finally, the opened file is closed. Please note that “filename.txt” in the code above is just an example file name, you need to change it to the correct file name according to your actual situation.