Share via


_dup, _dup2

建立已開啟檔案的第二個檔案描述項 (_dup),或重新指派檔案描述項 (_dup2)。

語法

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

參數

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

fd2
任何檔案描述項。

傳回值

_dup 會傳回新的檔案描述項。 _dup2 會傳回 0,表示作業成功。 如果發生錯誤,則每個函式都會傳回 -1,如果檔案描述元無效,則設定 errnoEBADF 為 ;如果沒有其他檔案描述元可用,則會設定為 EMFILE 。 傳遞不正確檔案描述元時,函式也會叫用不正確參數處理常式,如參數驗證 中所述

如需傳回碼的詳細資訊,請參閱 errno_doserrno_sys_errlist_sys_nerr

備註

_dup_dup2 函式會建立第二個檔案描述項與目前開啟之檔案的關聯。 這些函式可用來建立預先定義之檔案描述項 (例如針對 stdout) 與其他檔案的關聯。 可使用任一檔案描述項來執行檔案作業。 建立新的描述項不會影響檔案所允許的存取類型。 _dup 會傳回指定檔案的下一個可用的檔案描述項。 _dup2 會強制 fd2fd1 參考相同的檔案。 如果 fd2 在呼叫時與已開啟的檔案相關聯,則會關閉該檔案。

_dup_dup2 會接受檔案描述項作為參數。 若要將資料流程 ( FILE * ) 傳遞至其中一個函式,請使用 _filenofileno 常式會傳回目前與指定資料流相關聯的檔案描述項。 下列範例示範如何將 (定義為 FILE * in stdio.h ) 與檔案描述元產生關聯 stderr

int cstderr = _dup( _fileno( stderr ));

根據預設,此函式的全域狀態會限定于應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。

需求

常式 必要的標頭
_dup <io.h>
_dup2 <io.h>

通用 Windows 平臺 (UWP) 應用程式中不支援主控台。 與主控台、 stdinstdoutstderr 相關聯的標準資料流程控制碼必須先重新導向,C 執行時間函式才能在 UWP 應用程式中使用這些控制碼。 如需相容性詳細資訊,請參閱相容性

範例

// 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" );
}
This goes to stdout first
This goes to stdout

The file 'data' contains:
This goes to file 'data'

另請參閱

低階 I/O
_close
_creat, _wcreat
_open, _wopen