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

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


1.fd转换为fp

int main(int argc, char *argv[])
{
	FILE *fp = NULL;
	fp  = fopen("/home/super_bert/test.dat", "r");    /*得到文件指针*/
	if (fp == NULL)
	{
		perror("open file error.");
		exit(1);
	}
	else
	{
		printf("open file successfully...\n");
	}
	
	int fd;
	fd = fileno(fp);	/*文件指针转换为文件描述符*/
	if (-1 == fd)
	{
		perror("fp to fd error.");
	}
	else
	{
		printf("transform successfully...\n")
		exit(1);
	}
	
	return 0;
}
    fileno()函数转换成功返回文件描述符fd,失败时返回-1。

2.fp转换为fd

int main(int argc, char *argv[])
{
	int  fd;
	fd = open("/home/super_bert/test.dat", O_CREAT|O_RDWR, 0666);	 /*得到文件描述符*/
	if ( -1 == fd )
	{
		perror("open file error.");
		exit(1);
	}
	else
	{
		printf("open file successfully...\n");
	}
	FILE *fp = NULL;
	fp = fdopen(fd, "r");		/*文件描述符转换为文件指针*/
	if (NULL == fp)
	{
		perror("fd to fp error.");
	}
	else
	{
		printf("transform successfully...\n");
		exit(1);
	}
	
	return 0;
}
      fdopen()转换成功是返回指向该文件的文件指针,失败返回NULL,错误代码在宏errno中。

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

作者:super_bert@csdn

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值