如何从文件描述符获得一个文件指针?

我正在尝试使用 mkstemp(),它提供了一个文件描述符,但是我想通过 fprintf()生成格式化的输出。有没有一种简单的方法可以将 mkstemp()提供的文件描述符转换为适合与 fprintf()一起使用的 FILE *结构?

52965 次浏览

Use fdopen():

FILE* fp = fdopen(fd, "w");

FILE* f = fdopen(d, "w");

man fdopen output:

SYNOPSIS

#include <stdio.h>


FILE *
fdopen(int fildes, const char *mode);

The fdopen() function associates a stream with the existing file descriptor, fildes. The mode of the stream must be compatible with the mode of the file descriptor. When the stream is closed via fclose(3), fildes is closed also.

There is no standard way of doing this (or the reverse) as the C Standard has nothing to say about file descriptors. Your specific platform may or may not provide such a mechanism.