BD at Rivenhill
BD at Rivenhill

Reputation: 12983

How to get a FILE pointer from a file descriptor?

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()?

Upvotes: 98

Views: 62857

Answers (3)

Richard Pennington
Richard Pennington

Reputation: 19985

Use fdopen():

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

Upvotes: 122

Gregory Pakosz
Gregory Pakosz

Reputation: 70254

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.

Upvotes: 32

anon
anon

Reputation:

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.

Upvotes: -7

Related Questions