文件open、流fopen、fdopen

Open打开文件、fopen打开流、fdopen在一个已经打开的文件描述符上打开一个流

   fclose函数关闭文件时,该函数会将保存在内存中尚未来得及写回磁盘的文件内容写到磁盘上。如果没有调用fclose函数,就必须等待内存中缓冲区被填满,由系统将其内容写回到磁盘上去。 

   由于fclose函数在关闭文件时会将缓冲区中的内容写到磁盘上,因此flcose函数实际是进行了一个写文件操作。在网络环境中,文件的内容是要通过网络传输到目的主机上并且写入磁盘的。在这个传输过程中,如果网络连接出现问题或者传输数据出错,就会导致文件内容写入失败。这时fclose函数就会出错。

  1 /* FILE: p662_open.c
  2  * DATE: 20180124
  3  * ==============
  4  * DESCRIPTION: open fopen fdopen
  5  */
  6 
  7 #include <stdio.h>
  8 // #include <unistd.h>  // 宏 STDOUT_FILENO
  9 #include <fcntl.h>
 10 
 11 #define BUFFSIZE 128
 12 
 13 int main(void)
 14 {
 15         FILE *fp;
 16         int fd;
 17         char buf[BUFFSIZE];
 18         int len;
 19         // fopen 打开文件流     
 20         if((fp=fopen("temp.txt", "w")) == NULL)
 21                 perror("fail to fopen");
 22         fprintf(fp, "hello world\n");
 23         fclose(fp);
 24 
 25         // open 打开文件
 26         if((fd=open("temp.txt", O_RDWR)) < 0)
 27                 perror("fail to open");
 28         // fdopen 在已经打开的文件描述符上打开流
 29         if((fp=fdopen(fd, "a")) == NULL)
 30                 perror("fail to fdopen");
 31         fprintf(fp, "hello world again\n");
 32         fclose(fp);
 33 
 34         write(fileno(stdout), "===\n", 5);      // STDOUT_FILENO
 35         fp = fopen("temp.txt", "r");
 36         // 读取文件 并输出
 37         while((len=fread(buf, sizeof(char), BUFFSIZE-1, fp)) > 0)
 38                 fprintf(stdout, "%s", buf);
 39 
 40         return 0;
 41 }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值