推荐答案
// www.javascriptcn.com code example
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Failed to open file\n");
return 1;
}
// 文件操作代码
fclose(file);
return 0;
}本题详细解读
函数原型
FILE *fopen(const char *filename, const char *mode);
参数说明
filename: 要打开的文件名,可以是相对路径或绝对路径。
mode: 文件打开模式,常见的模式有:
"r": 只读模式,文件必须存在。
"w": 写入模式,如果文件存在则清空内容,如果文件不存在则创建。
"a": 追加模式,如果文件存在则在文件末尾追加内容,如果文件不存在则创建。
"r+": 读写模式,文件必须存在。
"w+": 读写模式,如果文件存在则清空内容,如果文件不存在则创建。
"a+": 读写模式,如果文件存在则在文件末尾追加内容,如果文件不存在则创建。
返回值
- 成功时返回指向
FILE 对象的指针。
- 失败时返回
NULL,并设置 errno 来指示错误。
使用示例
FILE *file;
file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// 文件操作代码
fclose(file);注意事项
- 使用
fopen 打开文件后,必须使用 fclose 关闭文件,以避免资源泄漏。
- 在打开文件时,应检查返回值是否为
NULL,以确保文件成功打开。
- 使用
perror 可以输出错误信息,帮助调试。