dup2
Duplicates a file handle (oldhandle) onto an existing file handle (nezvhandle).
Defined in header <io.h>
Syntax
#include <io.h>
int dup2(int oldhandle, int newhandle);
Portability
| DOS | UNIX | Windows | ANSI C | C++ only |
|---|---|---|---|---|
| ■ | ■ | ■ |
Remarks
dup2 is not available on UNIX System III.
dup2 creates a new file handle that has the following in common with the original file handle:
■ same open file or device 13 same file pointer (that is, changing the file pointer of one changes the other) a same access mode (read, write, read/write)
dup2 creates a new handle with the value of newhandle. If the file associated with newhandle is open when dup2 is called, the file is closed.
newhandle and oldhandle are file handles obtained from a creat, open, dup, or dup2 call.
Return value
dup2 returns 0 on successful completion, -1 otherwise.
In the event of error, the global variable errno is set to one of the following:
EMFILE Too many open files EBADF Bad file number
See also
Example
#include <SYs\stat.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
ttdefine STDOUT 1
int main(void)
{
int fptr, oldstdout;
char msg[] = "This is a test";
/* create a file */
fptr - open("DUMMY.FIL", 0_CREAT I 0_RDWR, S_IREAD I S_IWRITE);
if (fptr) {
/* create a duplicate handle for standard output */
oldstdout = dup (STDOUT);
/* redirect standard output to DUMMY. FIL by duplicating the */
/* file handle onto the file handle for standard output */
dup2(fptr, STDOUT);
/* close the handle for DUMMY.FIL */
close(fptr);
/* this will be redirected into DUMMY.FIL */
write(STDOUT, msg, strlen(msg) );
/* restore original standard output handle */
dup2(oldstdout, STDOUT);
/* close the duplicate handle for STDOUT */
close(oldstdout);
else
printf("Error opening file!\n");
return 0;
Differences from modern implementations
Nothing recorded yet.
Modern references
These are search links, not yet checked by hand.
Stable link: /3.1/io.h/dup2/
· short form /3.1/dup2/