fdopen() — Associate a stream with an open file descriptor

Standards

Standards / Extensions C or C++ Dependencies

POSIX.1
XPG4
XPG4.2
Single UNIX Specification, Version 3

both  

Format

#define _POSIX_SOURCE
#include <stdio.h>

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

General description

Associates a stream with an open file descriptor. A stream is a pointer to a FILE structure that contains information about a file. A stream permits user-controllable buffering and formatted input and output. For a discussion of the z/OS® UNIX services implementation of buffering, see z/OS XL C/C++ Programming Guide.

The specified options must be permitted by the current mode of the file descriptor. For example, if the file descriptor is open-read-only (O_RDONLY), the corresponding stream cannot be opened write-only (w).

These options are the same as for an fopen() operation.

Special behavior for XPG4.2: The values for options are changed to include binary streams.
Mode
Description
r or rb
Open for reading.
w or wb
Open for writing.
a or ab
Open for appending.
r+ or rb+ or r+b
Open for update (reading and writing).
w+ or wb+ or w+b
Open for update (reading and writing).
a+ or ab+ or a+b
Open for update at End Of File (EOF) (reading and writing).

All these options have the same behavior as the corresponding fopen() options, except that w, wb, w+, wb+ and w+b do not truncate the file.

The file position indicator of the new stream is the file offset associated with the file descriptor. The error indicator and end of file (EOF) indicator for the stream are cleared.

Returned value

If successful, fdopen() returns a FILE pointer to the control block for the new stream.

If unsuccessful, fdopen() returns NULL and sets errno to one of the following values:
Error Code
Description
EBADF
fildes is not a valid open file descriptor.
EINVAL
The specified mode is incorrect or does not match the mode of the open file descriptor.

Example

CELEBF08
⁄* CELEBF08

   This example associates stream with the file descriptor fd which is
   open for the file fdopen.file.
   The association is made in write mode.

 *⁄
#define _POSIX_SOURCE
#include <stdio.h>
#include <sys⁄types.h>
#include <sys⁄stat.h>
#include <fcntl.h>
#include <unistd.h>

main() {
  char fn[]="fdopen.file";
  FILE *stream;
  int  fd;

  if ((fd = creat(fn, S_IWUSR)) < 0)
    perror("creat() error");
  else {
    if ((stream = fdopen(fd, "w")) == NULL) {
      perror("fdopen() error");
      close(fd);
    }
    else {
      fputs("This is a test", stream);
      fclose(stream);
    }}}

Related information