fopen函数用于打开一个文件,并返回一个指向该文件的指针。其基本语法为:
FILE *fopen(const char *filename, const char *mode); 其中,filename为要打开的文件名(包括路径),mode为打开文件的模式。
常用的文件打开模式有:
以下是一个示例代码,展示如何使用fopen函数打开一个文件并进行读写操作:
#include <stdio.h> int main() { FILE *file; // 以只读方式打开文件 file = fopen("example.txt", "r"); if (file == NULL) { printf("无法打开文件\n"); return 1; } // 读取文件内容 char ch; while ((ch = fgetc(file)) != EOF) { printf("%c", ch); } // 关闭文件 fclose(file); // 以追加方式打开文件 file = fopen("example.txt", "a"); if (file == NULL) { printf("无法打开文件\n"); return 1; } // 写入文件内容 fprintf(file, "Hello, World!"); // 关闭文件 fclose(file); return 0; } 注意:在使用完文件后,应该使用fclose函数来关闭文件,以释放系统资源。