User Tools

Site Tools


Sidebar

Programming Reference/Librarys

Question & Answer

Q&A is closed







c:stdio.h:fdopen
click
to support this page (eg 0,42 € or so) Thanks.

fdopen

#include <stdio.h> /* including standard library */
FILE *fdopen(int fildes, const char *mode);

description of fdopen

fdopen() is the counterpart to fileno(). As a mode, such as the file is opened, the same modes as the can open() can be used.

fdopen() is often applied to file descriptors that are returned from functions that set up the pipes or channels of communication in networks. This is because some functions like open(), dup(), dup2(), fcntl(), pipe(), … in networks can not do anything with streams and require file descriptors. But to again generate descriptors from a stream (FILE pointer), the function fdopen required.

Arguments

Open a file
Arguments for mode are:
“r” Open a file for reading
“w” Create / writing
“a” Append
“b” Open a binary file
“rb” Open binary file for reading
”+” Open file for read/write
“r+” text update (reading and writing)
“w+” text update, discarding previous content (if any)
“a+” text append, reading, and writing at end
example fdopen(“test.txt”, “r+”);, fdopen(“test.txt”, “w+”); fdopen(“test.txt”, “rw”); …

C Sourcecode Example

/* 
 * fdopen example code
 * http://code-reference.com/c/stdio.h/fdopen 
 */
#include <stdio.h>
#ifdef __linux__
   #include <unistd.h>
#else
   // windows 
   #include <io.h>
#endif
 
int main(void) {
   FILE *fileptr, *fileptr2; // pointer
   int fdesc,fdesc2;               // descriptor
   char filename[42]="text.txt";
 
   fileptr=fopen(filename, "w+");
 
   /* error handling*/
   if(!fileptr)
      perror(NULL);
   fdesc = fileno(fileptr);
 
   printf("file descriptor %d for filename %s\n",fdesc ,filename);
   fdesc2=dup(fdesc);
   printf("copied file descriptor %d\n\n",fdesc2);
 
   printf("now we open a stream with fdopen\n");
   /**
   * fdopen
   **/
   fileptr2 = fdopen(fdesc2, "w");
     if(!fileptr2)
        perror(NULL);
 
   fprintf(fileptr,"Content of %s\n",filename);
   fprintf(fileptr2,"also content of %s\n",filename);
   fprintf(stdout,"content is written to %s\n",filename);
   return 0;
}

fdopen output example

  file descriptor 3 for filename text.txt
  copied file descriptor 4
  
  now we open a stream with fdopen
  content is written to text.txt
  
text.txt
also content of text.txt
Content of text.txt
advertising
c/stdio.h/fdopen.txt · Last modified: 2013/02/25 14:50 by 158.181.88.241

Impressum