文件描述符fd和文件指针fp之间的相互转换

转自:http://blog.csdn.net/embedded_sky/article/details/45064123

  Linux/Unix下使用open函数(系统调用)打开文件会得到文件描述符fd(int型变量),而使用C库中的fopen函数打开文件则会得到文件描述符fp(FILE*型变量),二者之间是可以相互转换的,下面是两个example。


1.fd转换为fp

[cpp]  view plain  copy
 print ?
  1. int main(int argc, char *argv[])  
  2. {  
  3.     FILE *fp = NULL;  
  4.     fp  = fopen("/home/super_bert/test.dat""r");    /*得到文件指针*/  
  5.     if (fp == NULL)  
  6.     {  
  7.         perror("open file error.");  
  8.         exit(1);  
  9.     }  
  10.     else  
  11.     {  
  12.         printf("open file successfully...\n");  
  13.     }  
  14.       
  15.     int fd;  
  16.     fd = fileno(fp);    /*文件指针转换为文件描述符*/  
  17.     if (-1 == fd)  
  18.     {  
  19.         perror("fp to fd error.");  
  20.     }  
  21.     else  
  22.     {  
  23.         printf("transform successfully...\n")  
  24.         exit(1);  
  25.     }  
  26.       
  27.     return 0;  
  28. }  
    fileno()函数转换成功返回文件描述符fd,失败时返回-1。

2.fp转换为fd

[cpp]  view plain  copy
 print ?
  1. int main(int argc, char *argv[])  
  2. {  
  3.     int  fd;  
  4.     fd = open("/home/super_bert/test.dat", O_CREAT|O_RDWR, 0666);    /*得到文件描述符*/  
  5.     if ( -1 == fd )  
  6.     {  
  7.         perror("open file error.");  
  8.         exit(1);  
  9.     }  
  10.     else  
  11.     {  
  12.         printf("open file successfully...\n");  
  13.     }  
  14.     FILE *fp = NULL;  
  15.     fp = fdopen(fd, "r");       /*文件描述符转换为文件指针*/  
  16.     if (NULL == fp)  
  17.     {  
  18.         perror("fd to fp error.");  
  19.     }  
  20.     else  
  21.     {  
  22.         printf("transform successfully...\n");  
  23.         exit(1);  
  24.     }  
  25.       
  26.     return 0;  
  27. }  
      fdopen()转换成功是返回指向该文件的文件指针,失败返回NULL,错误代码在宏errno中。

如有转载,请注明出处:http://blog.csdn.net/embedded_sky/article/details/45064123

作者:super_bert@csdn


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值