C语言文件I/O操作:fopen和freopen函数详解
在C语言中,文件I/O(Input/Output)操作是非常常见的任务,用于读取和写入文件。其中,fopen
和freopen
函数是文件操作中的重要工具,用于打开和重新打开文件。本篇博客将详细介绍这两个函数的用法、特点以及示例。
1. fopen
函数
fopen
函数用于打开一个文件,并返回一个指向该文件的指针。其基本语法如下:
FILE *fopen(const char *filename, const char *mode);
filename
是一个字符串,表示要打开的文件的路径和名称。mode
是一个字符串,表示文件打开的模式,包括读取(“r”)、写入(“w”)、追加(“a”)等模式。
fopen
函数返回一个指向文件的指针,或者在打开失败时返回NULL
。
下面是一个使用fopen
函数读取文件的示例:
#include <stdio.h>
int main() {
FILE *file;
char ch;
file = fopen("example.txt", "r");
if (file == NULL) {
printf("无法打开文件。\n");
return 1;
}
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch);
}
fclose(file);
return 0;
}
2. freopen
函数
freopen
函数用于重新打开一个已经打开的文件,并且可以改变文件的打开模式和文件指针的位置。其基本语法如下:
FILE *freopen(const char *filename, const char *mode, FILE *stream);
filename
和mode
参数与fopen
函数相同。stream
是一个指向已经打开的文件的指针,用于重新打开该文件。
freopen
函数返回一个指向文件的新指针,或者在失败时返回NULL
。
下面是一个使用freopen
函数追加数据到文件的示例:
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "a");
if (file == NULL) {
printf("无法打开文件。\n");
return 1;
}
fprintf(file, "这是追加的内容。\n");
fclose(file);
return 0;
}