How to get a FILE pointer from a file descriptor?

CPosixMkstemp

C Problem Overview


I'm playing around with mkstemp(), which provides a file descriptor, but I want to generate formatted output via fprintf(). Is there an easy way to transform the file descriptor provided by mkstemp() into a FILE * structure that is suitable for use with fprintf()?

C Solutions


Solution 1 - C

Use fdopen():

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

Solution 2 - C

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.

Solution 3 - C

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBD at RivenhillView Question on Stackoverflow
Solution 1 - CRichard PenningtonView Answer on Stackoverflow
Solution 2 - CGregory PakoszView Answer on Stackoverflow
Solution 3 - CanonView Answer on Stackoverflow