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
---------------------
作者:super_bert
来源:CSDN
原文:https://blog.csdn.net/embedded_sky/article/details/45064123?utm_source=copy
版权声明:本文为博主原创文章,转载请附上博文链接!