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.
**************************************************************************/
}