fopen、freopen和fdopen函数用于打开一个开流。
函数原型如下:
#include <stdio.h>
FILE *fopen(const char *restrict pathname, const char *restrict type);
FILE *freopen(const char *restrict pathname, const char *restrict type, FILE *restrict fp);
FILE *fdopen(int filedes, cosnt char *type);
返回值:若成功则返回文件指针,若出错则返回NULL。
参数:
pathame 文件路径
type 文件的打开模式
fp 文件指针
filedes 文件描述符
fopen和fdopen都会自动创建一个FILE对象(即流对象),而freopen是重用一个流对象。对于freopen函数我们很少自己定义一个FILE对象,然后传递给它,而是通过fopen或者fdopen或者用三个预定义流stdin、stdout和stderr递给它。为什么不能自己定义一个FILE对象?因为我们不清楚一个FILE对象内部是怎么样,很难初始化它的数据成员。下面代码会出错:
char pathname[] = "/tmp/myfile";
FILE fp; /*自己创建一个流*/
freopen(patname, "r", &fp); /*用未初始化的流做参数*/
实例 x.5.5.1.c
#include <stdio.h>
int main(void)
{
char pathname[] = "/tmp/myfile";
FILE *fp;
if ((fp=fopen(pathname, "r")) == NULL) {
printf("fopen error for %s\n", pathname);
} else {
printf("fopen seccess for %s\n", pathname);
fclose(fp);
}
return 0;
}
编译与执行
[root@localhost unixc]# echo "123456" > /tmp/myfile
[root@localhost unixc]# cc x.5.5.1.c
[root@localhost unixc]# ./a.out
fopen seccess for /tmp/myfile
[root@localhost unixc]#
实例 x.5.5.2.c
#include <stdio.h>
int main(void)
{
char pathname[] = "/tmp/myfile";
if ((freopen(pathname, "r", stdin)) == NULL) {
printf("freopen error for %s\n", pathname);
} else {
printf("freopen seccess for %s\n", pathname);
}
return 0;
}
编译与执行:
[root@localhost unixc]# cc x.5.5.2.c
[root@localhost unixc]# ./a.out
freopen seccess for /tmp/myfile
[root@localhost unixc]#
实例 x.5.5.3.c
#include <fcntl.h>
#include <stdio.h>
int main(void)
{
char pathname[] = "/tmp/myfile";
int filedes;
FILE *fp;
if ((filedes = open(pathname, O_RDONLY)) == -1) {
printf("open error for %s\n", pathname);
return 1;
}
if ((fp=fdopen(filedes, "r")) == NULL) {
printf("fdopen error for %s\n", pathname);
} else {
printf("fdopen seccess for %s\n", pathname);
fclose(fp);
}
return 0;
}
编译与执行:
[root@localhost unixc]# echo "123456" > /tmp/myfile
[root@localhost unixc]# cc x.5.5.3.c
[root@localhost unixc]# ./a.out
fdopen seccess for /tmp/myfile
[root@localhost unixc]#