转自:http://blog.csdn.net/embedded_sky/article/details/45064123
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