fopen
是 Linux 系统中的一个标准 C 库函数,用于打开文件并返回一个文件指针。这个函数在 <stdio.h>
头文件中声明。fopen
函数的基本语法如下:
FILE *fopen(const char *filename, const char *mode);
"r"
: 只读模式,文件必须存在。"w"
: 写入模式,如果文件存在则清空内容,不存在则创建新文件。"a"
: 追加模式,在文件末尾添加内容,不存在则创建新文件。"r+"
: 读写模式,文件必须存在。"w+"
: 读写模式,如果文件存在则清空内容,不存在则创建新文件。"a+"
: 追加读模式,在文件末尾添加内容,同时允许读取,不存在则创建新文件。"b"
:"rb"
, "wb"
, "ab"
, "r+b"
, "w+b"
, "a+b"
。fopen
返回一个指向 FILE
结构的指针,该结构用于后续的文件操作。NULL
,并且错误代码会被存储在 errno
中。以下是一个简单的示例,展示如何使用 fopen
打开一个文件并进行读写操作:
#include <stdio.h>
int main() {
// 打开文件进行读取
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// 读取文件内容
char line[100];
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
// 关闭文件
fclose(file);
// 再次打开文件进行写入
file = fopen("example.txt", "w");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// 写入新内容
fprintf(file, "New content written by the program.\n");
// 关闭文件
fclose(file);
return 0;
}
perror
函数打印具体的错误信息。ferror
函数检查是否发生了错误。fclose
。try-finally
或 RAII
技术确保文件总是被关闭。通过理解和正确使用 fopen
函数,可以有效地进行文件操作,确保数据的持久化和程序的稳定性。
领取专属 10元无门槛券
手把手带您无忧上云