Create a second handle for an open file (_dup), or reassign a file handle (_dup2).
#include <io.h> | Required only for function declarations |
int _dup( int handle );
int _dup2( int handle1, int handle2 );
handle, handle1 | Handle referring to open file | |
handle2 | Any handle value |
The _dup and _dup2 functions cause a second file handle to be associated with a currently open file. Operations on the file can be carried out using either file handle. The type of access allowed for the file is unaffected by the creation of a new handle.
The _dup function returns the next available file handle for the given file. The _dup2 function forces handle2 to refer to the same file as handle1. If handle2 is associated with an open file at the time of the call, that file is closed.
Note that in a QuickWin application you cannot use the _dup and _dup2 functions on stdin, stdout, or stderr (defined in STDIO.H). You can, however, use the _dup and _dup2 functions on other handles.
The _dup function returns a new file handle. The _dup2 function returns 0 to indicate success. Both functions return –1 if an error occurs and set errno to one of the following values:
Value | Meaning |
EBADF | Invalid file handle |
EMFILE | No more file handles available (too many open files) |
Standards:UNIX
16-Bit:DOS, QWIN, WIN, WIN DLL
32-Bit:DOS32X
Use _dup and _dup2 for compatibility with ANSI naming conventions of non-ANSI functions. Use dup and dup2 and link with OLDNAMES.LIB for UNIX compatibility.
/* DUP.C: This program uses the variable old to save the original stdout.
* It then opens a new file named new and forces stdout to refer
* to it. Finally, it restores stdout to its original state.
*/
#include <io.h>
#include <stdlib.h>
#include <stdio.h>
void main( void )
{
int old;
FILE *new;
old = _dup( 1 ); /* “old” now refers to “stdout” */
/* Note: file handle 1 == “stdout” */
if( old == -1 )
{
perror( “_dup( 1 ) failure” );
exit( 1 );
}
write( old, “This goes to stdout first\r\n”, 27 );
if( ( new = fopen( “data”, “w” ) ) == NULL )
{
puts( “Can't open file 'data'\n” );
exit( 1 );
}
/* stdout now refers to file “data” */
if( -1 == _dup2( _fileno( new ), 1 ) )
{
perror( “Can't _dup2 stdout” );
exit( 1 );
}
puts( “This goes to file 'data'\r\n” );
/* Flush stdout stream buffer so it goes to correct file */
fflush( stdout );
fclose( new );
/* Restore original stdout */
_dup2( old, 1 );
puts( “This goes to stdout\n” );
puts( “The file 'data' contains:” );
system( “type data” );
}
This goes to stdout first
This goes to stdout
The file 'data' contains:
This goes to file 'data'