_popen _wpopen

建立管道並執行命令。

重要

這個 API 不能用於 Windows 執行階段執行的應用程式。如需詳細資訊,請參閱 CRT 函式不支援使用 /ZW

FILE *_popen( const char *command, const char *mode ); FILE *_wpopen( const wchar_t *command, const wchar_t *mode );

參數

  • 命令
    要執行的命令。

  • mode
    傳回資料流的方式。

傳回值

傳回資料流與建立的管道另一端。 管道另一端與產生的命令的標準輸入或標準輸出。 函式在錯誤的傳回 NULL 。 如果錯誤是不正確的參數,例如,如果 命令方式 為 null 指標或 模式 不是有效的方式, errno 設定為 EINVAL。 如需有效模式。請參閱 <備註> 一節。

如需這些屬性和其他錯誤碼的詳細資訊,請參閱 _doserrno、errno、_sys_errlist 和 _sys_nerr

備註

_popen 函式會建立管道和非同步執行命令處理器的產生的複本與指定 命令的字串。 字串 模式 指定要求的型別,如下所示。

  • "r"
    使用傳回的資料流,呼叫程序可能會產生的命令的標準輸出。

  • "w"
    使用傳回的資料流,呼叫程序可能會產生的命令的標準項目寫入。

  • "b"
    開啟二進位模式。

  • "t"
    開啟文字模式。

    注意事項注意事項

    如果使用在 Windows 程式, _popen 函式會傳回造成程式停止無限期回覆的無效檔案指標。_popen 在主控台應用程式正確運作。若要建立重新輸入和輸出導向的 Windows 應用程式,請參閱 Windows SDK的 建立重新導向的輸入和輸出的子處理序

_wpopen_popen的寬字元版本;對 _wpopen路徑 引數是寬字元字串。 _wpopen_popen 其餘行為相同。

泛用文字常式對應

Tchar.h 常式

未定義的 _UNICODE 和 _MBCS

已定義 _MBCS

已定義 _UNICODE

_tpopen

_popen

_popen

_wpopen

需求

程序

必要的標頭檔

_popen

<stdio.h>

_wpopen

<stdio.h> 或 <wchar.h>

如需更多關於相容性的資訊,請參閱入門介紹中的 相容性 (Compatibility)

程式庫

所有的 C 執行階段程式庫 (C run-time libraries) 版本。

範例

// crt_popen.c
/* This program uses _popen and _pclose to receive a 
 * stream of text from a system process.
 */

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

int main( void )
{

   char   psBuffer[128];
   FILE   *pPipe;

        /* Run DIR so that it writes its output to a pipe. Open this
         * pipe with read text attribute so that we can read it 
         * like a text file. 
         */

   if( (pPipe = _popen( "dir *.c /on /p", "rt" )) == NULL )
      exit( 1 );

   /* Read pipe until end of file, or an error occurs. */

   while(fgets(psBuffer, 128, pPipe))
   {
      printf(psBuffer);
   }


   /* Close pipe and print return value of pPipe. */
   if (feof( pPipe))
   {
     printf( "\nProcess returned %d\n", _pclose( pPipe ) );
   }
   else
   {
     printf( "Error: Failed to read the pipe to the end.\n");
   }
}

範例輸出

這個輸出假設,只有在目前目錄中的檔案與 C++ 擴充功能。

 Volume in drive C is CDRIVE
 Volume Serial Number is 0E17-1702

 Directory of D:\proj\console\test1

07/17/98  07:26p                   780 popen.c
               1 File(s)            780 bytes
                             86,597,632 bytes free

Process returned 0

.NET Framework 對等用法

不適用。若要呼叫標準 C 函式,請使用 PInvoke。如需更多的資訊,請參閱 Platform Invoke Examples

請參閱

參考

處理程序和環境控制

_pclose

_pipe