_dup _dup2

建立開啟檔案 (_dup) 第二個檔案描述項,或者將檔案描述項 (_dup2)。

int _dup( 
   int fd 
);
int _dup2( 
   int fd1,
   int fd2 
);

參數

  • fd, fd1
    參考開啟檔案的檔案描述項。

  • fd2
    任何檔案描述項。

傳回值

_dup 會傳回新的檔案描述項。_dup2 會傳回 0 以表示成功。如果發生錯誤,每一個函式會傳回– 1 並將 errno 設為 EBADF ,如果檔案描述無效或為 EMFILE ,如果沒有其他的檔案描述項沒有可用的。在無效的檔案描述項的情況下,函式也會叫用無效的參數處理常式,如 參數驗證中所述。

如需更多關於這些和其他回傳碼的資訊,請參閱 _doserrno 、 errno 、 _sys_errlist 、和 _sys_nerr (_doserrno, errno, _sys_errlist, and _sys_nerr)

備註

_dup 和 _dup2 函式使第二個檔案描述項與目前開啟的檔案。這些函式可以與預先定義的檔案描述項,例如的 stdout,與不同的檔案。使用任一檔案描述項,檔案中的作業可以在上執行。檔案所允許的存取類型由新的描述元的建立會受到影響。_dup 會傳回指定之檔案的下一個可用的檔案描述項。_dup2 強制 fd2 參考檔案與 fd1相同。如果 fd2 與開啟檔案在呼叫時,該檔案已關閉。

_dup 和 _dup2 接受檔案描述做為參數。若要透過資料流 (FILE *) 到這些函式之一,請使用 _fileno。fileno 方法會傳回檔案描述目前與指定的資料流。下列範例顯示如何使 stderr (會定義為 Stdio.h 的 FILE* ) 與檔案描述:

int cstderr = _dup( _fileno( stderr ));

需求

程序

必要的標頭檔

_dup

<io.h>

_dup2

<io.h>

主控台 Windows 市集 應用程式不支援。標準資料流控制代碼與主控台, stdin, stdout和 stderr,在這種情況下, C 執行階段函式在 Windows 市集 應用程式之前,可以使用它們必須重新導向。如需更多關於相容性的資訊,請參閱入門介紹中的 相容性 (Compatibility)

範例

// crt_dup.c
// This program uses the variable old to save
// the original stdout. It then opens a new file named
// DataFile and forces stdout to refer to it. Finally, it
// restores stdout to its original state.
//

#include <io.h>
#include <stdlib.h>
#include <stdio.h>

int main( void )
{
   int old;
   FILE *DataFile;

   old = _dup( 1 );   // "old" now refers to "stdout" 
                      // Note:  file descriptor 1 == "stdout" 
   if( old == -1 )
   {
      perror( "_dup( 1 ) failure" );
      exit( 1 );
   }
   _write( old, "This goes to stdout first\n", 26 );
   if( fopen_s( &DataFile, "data", "w" ) != 0 )
   {
      puts( "Can't open file 'data'\n" );
      exit( 1 );
   }

   // stdout now refers to file "data" 
   if( -1 == _dup2( _fileno( DataFile ), 1 ) )
   {
      perror( "Can't _dup2 stdout" );
      exit( 1 );
   }
   puts( "This goes to file 'data'\n" );

   // Flush stdout stream buffer so it goes to correct file 
   fflush( stdout );
   fclose( DataFile );

   // Restore original stdout 
   _dup2( old, 1 );
   puts( "This goes to stdout\n" );
   puts( "The file 'data' contains:" );
   _flushall();
   system( "type data" );
}
  

請參閱

參考

低階 I/O

_close

_creat _wcreat

_open _wopen