user1944224
user1944224

Reputation: 143

fileno cast FILE to descriptor C

Is there a way to cast a variable of type int (file descriptor) into type FILE in C ? I have an open pipe fd and I want to use the functions which expect FILE.

Upvotes: 2

Views: 371

Answers (2)

Samuel Edwin Ward
Samuel Edwin Ward

Reputation: 6675

On POSIX systems, you can use fdopen to construct a FILE * that refers to a file descriptor.

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225052

You can't cast it, but you can call fdopen(3), which does exactly what you want:

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: 5

Related Questions