Your Browser is not longer supported

Please use Google Chrome, Mozilla Firefox or Microsoft Edge to view the page correctly
Loading...

{{viewport.spaceProperty.prod}}

fdopen - Assign a file pointer to a file descriptor

&pagelevel(4)&pagelevel

Definition

#include <stdio.h>

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

fdopen assigns a file pointer to a file (with file descriptor fd) that has already been opened
with open/open64 or creat/creat64.
Following an fdopen call, the file may also be processed with functions from the standard
I/O library (fread, fputc, fprintf etc.).

Parameters  int fd

File descriptor that was assigned by a creat/creat64 or open/open64 call.

const char *mode

String which specifies the access mode (see description under fopen/fopen64). This
parameter is not evaluated, i.e. the file retains the original access mode that was
specified for open/open64 or creat/creat64. In other words, the access mode cannot
be changed with fdopen. The optional additional specifications in the mode parameter
are not evaluated either.

Return val.

File pointer to the assigned FILE structure

if successful.

Note

If errors occur, e.g. due to an invalid file descriptor, fdopen returns neither a defined result
nor an error message. The program does not abort either!

Example

The following program opens the file fname for elementary as well as standard input/output
operations.

#include <stdio.h>
#include <stdlib.h>
FILE *fp;
int fd;
char buf[10];
int c;
int main(void)
{
   int n;
               /* deal with the file descriptor first */
   if((fd = open("fname",2)) < 0)
     {
        perror("open");
        exit(1);
     }
   if((n = read(fd,buf,10)) > 0)
      write(1,buf,n);
               /* link file pointer with file descriptor */
   fp = fdopen(fd,"w");
   while((c = getchar()) != EOF)
        putc(c,fp);
   fclose(fp);
   return 0;
 }

See also

creat, creat64, fclose, fseek, fseek64, fopen, fopen64, freopen, freopen64, open, open64