编写一个程序,使用 fopen 函数以只读模式打开一个文本文件
在 C 语言中,fopen 函数用于打开或创建文件。当以只读模式("r" 模式)调用 fopen 时,如果文件存在,则会返回指向该文件的文件指针;如果文件不存在,则会返回 NULL,并且设置全局变量 errno 来表示错误原因。
下面是一个示例程序,展示了如何使用 fopen 函数以只读模式打开一个文本文件:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp = fopen("example.txt", "r");
if (fp == NULL) {
perror("Failed to open file");
return EXIT_FAILURE;
}
fclose(fp);
return EXIT_SUCCESS;
}

