fdopen()

Associate a stream with a file descriptor

Synopsis:

#include <stdio.h>

FILE* fdopen( int filedes, 
              const char* mode );

Arguments:

filedes
The file descriptor that you want to associate with a stream.
mode
The mode specified when filedes was originally opened. For information, see fopen(), except modes begining with w don't cause truncation of the file.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The fdopen() function associates a stream with the file descriptor filedes, which represents an opened file or device.

The filedes argument is a file descriptor that was returned by one of accept(), creat(), dup(), dup2(), fcntl(), open(), pipe(), or sopen().

The fdopen() function preserves the offset maximum previously set for the open file description corresponding to filedes.

Returns:

A file stream for success, or NULL if an error occurs (errno is set).

Errors:

EBADF
The filedes argument isn't a valid file descriptor.
EINVAL
The mode argument isn't a valid mode.
EMFILE
Too many file descriptors are currently in use by this process.
ENOMEM
There isn't enough memory for the FILE structure.

Examples:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main( void )
{
    int filedes ;
    FILE *fp;

    filedes = open( "file", O_RDONLY );
    if( filedes != -1 ) {
        fp = fdopen( filedes , "r" );
        if( fp != NULL ) {
            /* Also closes the underlying FD, filedes. */
            fclose( fp );
        }
    }
    return EXIT_SUCCESS;
}

Classification:

POSIX 1003.1

Safety:
Cancellation point Yes
Interrupt handler No
Signal handler No
Thread Yes

See also:

creat(), dup(), dup2(), errno, fcntl(), fopen(), freopen(), open(), pipe(), sopen()