Retro video games delivered to your door every month!
Click above to get retro games delivered to your door ever month!
X-Hacker.org- Zortech C++ 3.0r4 - <b>dup</b> http://www.X-Hacker.org [<<Previous Entry] [^^Up^^] [Next Entry>>] [Menu] [About The Guide]
dup
dup2

Usage

   #include <io.h>
   int dup(int fd);
   int dup2(int fd1, int fd2);

Description

   The functions dup and dup2 allow more than one file handle to be
   associated with a currently open file. Once associated, any of the file
   handles can be used to carry out operations on the file. All such file
   handles use the same file pointer. The access mode for the file is
   unchanged.

   The function dup creates a new file handle and associates it with the
   file already connected to fd.

   The function dup2 associates fd2 with fd1 so that it refers to the file
   already connected to that handle.

Example 

   #include <stdio.h>
   #include <io.h>
   #include <stdlib.h>

   const int stdout_h = 1;

   int main()
   {
       int oldout, newout;
       oldout = dup(stdout_h);
       if (oldout == -1) {
           perror("dup failed");
           return EXIT_FAILURE;
       }

       newout = open("temp.fil");
       if (dup2(newout,stdout_h) == -1) {
           perror("dup2 failed");
           return EXIT_FAILURE;
       }
       fprintf(stdout,"This goes to the file temp.fil\n");
       fflush(stdout);
       fprintf(oldout,"This goes to stdout\n");
       if (dup2(stdout_h,oldout) == -1) {
           perror("Can't restore stdout");
           return EXIT_FAILURE;
       }
       fprintf(stdout,"This goes to stdout\n");
       return EXIT_SUCCESS;
   }

Return Value

   dup returns the new file handle, otherwise -1 if an error occurred. dup2
   returns 0 if successful, otherwise -1.


   Both functions set errno if an error occurs.

See Also

   close, creat, open



See Also: close creat open

Online resources provided by: http://www.X-Hacker.org --- NG 2 HTML conversion by Dave Pearson