dup2

From RAD Studio
Jump to: navigation, search

Go Up to io.h Index


Header File

io.h

Category

Input/output Routines

Prototype

int dup2(int oldhandle, int newhandle);

Description

Duplicates a file handle (oldhandle) onto an existing file handle (newhandle).

  • dup2 creates a new file handle that has the following in common with the original file handle:
  • Same open file or device
  • Same file pointer (that is, changing the file pointer of one changes the other)
  • 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 values:

EBADF Bad file number

EMFILE Too many open files

Example

#include <sys\stat.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>
#define STDOUT 1
int main(void)
{
   int nul, oldstdout;
   char msg[] = "This is a test";
   /* create a file */
   nul = open("DUMMY.FIL", O_CREAT | O_RDWR,
      S_IREAD | S_IWRITE);
   /* 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(nul, STDOUT);
   /* close the handle for DUMMY.FIL */
   close(nul);
   /* will be redirected into DUMMY.FIL */
   write(STDOUT, msg, strlen(msg));
   /* restore original standard output handle */
   dup2(oldstdout, STDOUT);
   /* close duplicate handle for STDOUT */
   close(oldstdout);
   return 0;
}

Portability

POSIX Win32 ANSI C ANSI C++

+

+