gtpc2m2aC/C++ Language Support User's Guide

fdopen-Associate a Stream with an Open File Descriptor

This function associates a stream with an open file descriptor.

Format

#define _POSIX_SOURCE
#include <stdio.h>
FILE *fdopen(int fildes, const char *mode);

fildes
The open file descriptor on which to open a stream.

mode
The access mode for the stream.

This function 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-controlled buffering and formatted input and output.

The specified mode 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 for writing (w), for appending (a), or for update (+).

Mode
Description

r
Open for reading.

w
Open for writing.

a
Open for appending.

r+
Open for update (reading and writing).

w+
Open for update (reading and writing).

a+
Open for update at end-of-file (reading and writing).

All of these modes have the same behavior as the corresponding fopen modes, except that w and w+ 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 indicator for the stream are cleared.

Normal Return

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

Error Return

If unsuccessful, the fdopen function returns NULL and sets errno to one of the following:

EINVAL
The specified mode is incorrect or does not match the mode of the open file descriptor.

EBADF
fildes is not a valid open file descriptor.

Programming Considerations

None.

Examples

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

#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);
    }
    unlink(fn);
  }
}

Related Information

See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.