返回流的模式。

返回一个与创建的管道一端相关联的流。 管道的另一端与生成的命令的标准输入或标准输出相关联。 函数针对错误返回 NULL 。 如果错误是由无效参数引起的,则将 errno 设置为 EINVAL 。 有关有效模式的信息,请参阅“备注”部分。

有关这些和其他错误代码的信息,请参阅 errno _doserrno _sys_errlist _sys_nerr

函数 _popen 创建一个管道。 然后,它会异步执行命令处理器的生成副本,并将 command 用作命令行。 字符串 mode 指定请求的访问类型,如下所示。

如果在 Windows 程序中使用, _popen 函数将返回可导致程序无限期停止响应的无效文件指针。 _popen 在控制台应用程序中正常工作。 若要创建重定向输入和输出的 Windows 应用程序,请参阅在 Windows SDK 中使用 重定向输入和输出创建子进程

_wpopen _popen 的宽字符版本; path _wpopen 参数是宽字符字符串。 除此以外, _wpopen _popen 的行为完全相同。

默认情况下,此函数的全局状态范围限定为应用程序。 若要更改此行为,请参阅 CRT 中的全局状态

一般文本例程映射

Tchar.h 例程 _UNICODE _MBCS 未定义 _MBCS 已定义 _UNICODE 已定义
// 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);
        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