fopen/freopen/fdopen

本文详细介绍了fopen、freopen及fdopen三个文件操作函数的使用方法。通过实例展示了如何利用freopen进行输入输出重定向,以及fdopen如何将文件描述符转换为标准I/O流。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

fopen是用得比较多的,通常是打开文件读写。另外两个用得不多,但在系统编程时会用到。

freopen

通常与stdin,stdout,stderr一起用,有点重定向的味道

FILE *freopen(const char *restrict pathname, const char *restrict type,FILE *restrict fp);
  • 例1
 94     int a;                                                                                                              
 95           
 96     freopen("in.txt", "r", stdin);
 97     while (scanf("%d", &a) != EOF)
 98         printf("%d\n", a);
 99           
103     return 0;  

从in.txt中读,重定向到stdin,所以下面scanf从stdin接收data内容。

  • 例2
 94     int a;                                                                                                              
 95           
100     freopen("in.txt", "w", stdout);
101     for (a = 0; a<6; a++)
102         printf("%d\n", a);
103     return 0;    

这个例子正好与上面向抬,把stdout重定向到in.txt,所以printf输出的内容就不会在console显示,而被写到in.txt中去了。

fdopen

takes an existing file descriptor,which we could obtain from the open,dup,dup2,fcntl,pipe,socket,socketpair,or accept functions and associates a standard I/O stream with the descriptior.This
function is often used with descriptors that are returned by the functions that
create pipes and network communication channels. Because these special types
of files cannot be opened with the standard I/O fopen function, we have to call
the device-specific function to obtain a file descriptor, and then associate this
descriptor with a standard I/O stream using fdopen.
#include <stdio.h>
FILE * fdopen(int fildes, const char * mode);

将文件描述符转成对应的句柄(指向文件的指针),比如下面是将标准输入stdin转为文件指针,会在console上输出hello!

106     FILE *fp = fdopen(0, "w+");
107     fprintf(fp, "%s\n", "hello!");
108     fclose(fp);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JXES智能生态系统

如文章对你有用,请作者喝个咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值