Syntax
#include <io.h> int dup2(int handle1, int handle2);Description
handle2 will point to the same file as handle1, but will retain the file access mode (text or binary) that it had before duplication. In addition, if handle2 was originally opened with the O_APPEND flag, it will also retain that attribute. If handle2 is associated with an open file at the time of the call, that file is closed.
Warning: Both handles share a single file position. If you reposition a file using handle1, the position in the file returned by handle2 will also change.
If you duplicate a file handle for an open stream (using fileno), the resulting file handle has the same restrictions as the original file handle.
dup2 returns 0 to indicate success. It returns -1 if an error occurs and sets errno to one of the following values:
Value
This example makes a second file handle, fh3, refer to the same file as the file handle fh1 using dup. The file handle fh2 is then associated with the file edopen.da2, and finally fh2 is forced to associate with edopen.da1 by the dup2 function.
#include <io.h>#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys\stat.h> int main(void) { int fh1,fh2,fh3; if (-1 == (fh1 = open("edopen.da1", O_CREAT|O_TRUNC|O_RDWR, S_IREAD|S_IWRITE) )) { perror("Unable to open edopen.da1"); return EXIT_FAILURE; } if (-1 == (fh3 = dup(fh1))) { /* fh3 refers to the sample file as fh1 */ perror("Unable to dup"); close(fh1); return EXIT_FAILURE; } else printf("Successfully performed dup handle.\n"); if (-1 == (fh2 = open("edopen.da2", O_CREAT|O_TRUNC|O_RDWR, S_IREAD|S_IWRITE) )) { perror("Unable to open edopen.da2"); close(fh1); close(fh3); return EXIT_FAILURE; } if (-1 == dup2(fh1, fh2)) { /* Force fh2 to the refer to the same file */ /* as fh1. */ perror("Unable to dup2"); } else printf("Successfully performed dup2 handle.\n"); close(fh1); close(fh2); close(fh3); return 0; /**************************************************************************** The output should be: Successfully performed dup handle. Successfully performed dup2 handle. ****************************************************************************/ }Related Information