fdopen()

Converts a file descriptor to a stream.

  #include <stdio.h>
  
  FILE *fdopen(int fildes, char *mode);
  
  FILE *_fdopen(int fildes, char *mode);    
Parameter

fildes

A file descriptor, obtained from fileno().

mode

The file opening mode.

Remarks

This function creates a stream for the file descriptor fildes. You can use the stream with such standard I/O functions as fprintf() and getchar().

If it is successful, fdopen() returns a stream. If it encounters an error, fdopen()returns NULL.

Listing: Example of fdopen() usage

#include <stdio.h>

#include <unix.h>

int main(void)

{

int fd;

FILE *str;

fd = open("mytest", O_WRONLY | O_CREAT);

/* Write to the file descriptor */

write(fd, "Hello world!\n", 13);

/* Convert the file descriptor to a stream */

str = fdopen(fd,"w");

/* Write to the stream */

fprintf(str, "My name is %s.\n", getlogin());

/* Close the stream. */

fclose(str);

/* Close the file descriptor */

close(fd);

return 0;

}