_popen, _wpopen

建立管道並執行命令。

重要

這個 API 不能用於在 Windows 執行階段中執行的應用程式。 如需詳細資訊,請參閱 CRT functions not supported in Universal Windows Platform apps (通用 Windows 平台應用程式中不支援的 CRT 函式)。

語法

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

參數

command
要執行的命令。

mode
所傳回資料流的模式。

傳回值

傳回與所建立管道的一端相關聯的資料流。 管道的另一端會與所繁衍命令的標準輸入或標準輸出相關聯。 函式會在錯誤時傳回 NULL 。 如果錯誤是由不正確參數所造成, errno 則會設定為 EINVAL 。 請參閱<備註>一節查看有效的模式。

如需這些錯誤碼和其他錯誤碼的相關資訊,請參閱 errno_doserrno_sys_errlist_sys_nerr

備註

函式 _popen 會建立管道。 然後,它會以非同步方式執行命令處理器繁衍的複本,並使用 command 作為命令列。 字元字串 mode 會指定要求的存取類型,如下所示。

存取模式 描述
"r" 呼叫處理序可使用傳回的資料流來讀取繁衍命令的標準輸出。
"w" 呼叫處理序可使用傳回的資料流來寫入至繁衍命令的標準輸入。
"b" 在二進位模式中開啟。
"t" 在文字模式中開啟。

注意

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

_wpopen 是寬字元版本的 _popenpath_wpopen 引數是寬字元字串。 否則,_wpopen_popen 的行為即會相同。

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

泛型文字常式對應

Tchar.h 常規 _UNICODE_MBCS 未定義 _MBCS 定義 _UNICODE 定義
_tpopen _popen _popen _wpopen

需求

常式 必要的標頭
_popen <stdio.h>
_wpopen <stdio.h><wchar.h>

如需相容性詳細資訊,請參閱相容性

程式庫

所有版本的 C 執行階段程式庫

範例

// 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))
    {
        puts(psBuffer);
    }

    int endOfFileVal = feof(pPipe);
    int closeReturnVal = _pclose(pPipe);

    if (endOfFileVal)
    {
        printf("\nProcess returned %d\n", closeReturnVal);
    }
    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

另請參閱

進程和環境控制
_pclose
_pipe