fdopen Function

Associate a stream with a file descriptor.

Include

<stdio.h>

Prototype

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

Arguments

fildes file descriptor
mode type of access permitted

Return Value

Returns a pointer to the open stream. If the function fails, a null pointer is returned.

Remarks

The following are types of file access:

r Opens an existing text file for reading.
w Opens an empty text file for writing.
a Opens a text file for appending.
rb Opens an existing binary file for reading.
wb Opens an empty binary file for writing.
ab Opens a binary file for appending.
r+ Opens an existing text file for reading and writing.
w+ Opens an empty text file for reading and writing.
a+ Opens a text file for reading and appending.
r+b or rb+ Opens an existing binary file for reading and writing.
w+b or wb+ Opens an empty binary file for reading and writing.
a+b or ab+ Opens a binary file for reading and appending.

This function requires a heap.

Example

#include <stdio.h> /* for fdopen, fclose, printf, FILE,  NULL, EOF */
int main(void)
{
  FILE *myfile1, *myfile2;
  int y;
  if ((myfile1 = fdopen("afile1", "r")) == NULL)
    printf("Cannot open afile1\n");
  else
  {
    printf("afile1 was opened\n");
    y = fclose(myfile1);
    if (y == EOF)
      printf("afile1 was not closed\n");
    else
      printf("afile1 was closed\n");
  }
  if ((myfile1 = fdopen("afile1", "w+")) == NULL)
    printf("Second try, cannot open afile1\n");
  else
  {
    printf("Second try, afile1 was opened\n");
    y = fclose(myfile1);
    if (y == EOF)
      printf("afile1 was not closed\n");
    else
      printf("afile1 was closed\n");
  }
  if ((myfile2 = fdopen("afile2", "a+")) == NULL)
    printf("Cannot open afile2\n");
  else
  {
    printf("afile2 was opened\n");
    y = fclose(myfile2);
    if (y == EOF)
      printf("afile2 was not closed\n");
    else
      printf("afile2 was closed\n");
  }
}

Example Output

Cannot open afile1
Second try, afile1 was opened
afile1 was closed
Cannot open afile2

Example Explanation

afile1 must exist before it can be opened for reading (r) or the fdopen function will fail.

If the fdopen function opens a file for writing (w+) that doesn’t exist, it will be created and then opened. If the file does exist, it cannot be overwritten and will be appended.

If the fdopen function attempts to append a file (a+) that doesn’t exist, it will NOT be created and fdopen will fail. If the file does exist, it will be opened for appending.