Syntax
#include <io.h> int dup(int handle);Description
For example, given:
handle2 = dup(handle1)
handle2 will have the same file access mode (text or binary) as handle1. In addition, if handle1 was originally opened with the O_APPEND flag (described in open), handle2 will also have that attribute.
Warning: Both handles share a single file pointer. 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, the resulting file handle has the same restrictions as the original file handle.
Returns
dup returns the next available file handle for the given file. 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 dup2.
#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