代码之家  ›  专栏  ›  技术社区  ›  Akusete

在不写入C/C++文件的情况下捕获系统调用stdout++

  •  1
  • Akusete  · 技术社区  · 17 年前

    Perl

    //without file io
    $output = `echo hello`;
    

    C

    //with file io
    system ("echo hello > tmp");
    std::fstream file ("tmp");
    std::string s;
    file >> s;
    
    2 回复  |  直到 17 年前
        1
  •  2
  •   ephemient    17 年前

    使用C popen iostream ):

    FILE *p = popen("echo hello", "r");
    std::string s;
    for (size_t count; (count = fread(buf, 1, sizeof(buf), p));)
        s += string(buf, buf + count);
    pclose(p);
    

    假设你 输入输出流 有非标准 fstream:: X fstream(int fd)

    FILE *p = popen("echo hello", "r");
    std::ifstream p2(fileno(p));
    std::string s;
    p2 >> s;
    p2.close();
    pclose(p);
    

    使用 Boost.Iostreams 输入输出流

    boost::iostreams::file_descriptor_source p2(fileno(p));
    

    不幸的是,Windows很可怕 _popen 仅适用于控制台应用程序;对于图形应用程序:

    SECURITY_ATTRIBUTES sec;
    sec.nLength = sizeof(sec);
    sec.bInheritHandle = TRUE;
    sec.lpSecurityDescriptor = NULL;
    HANDLE *h[2];
    CreatePipe(&h[0], &h[1], &sec, 0);
    SetHandleInformation(h[0], HANDLE_FLAG_INHERIT, 0)
    STARTUPINFO si;
    memset((void *)&si, 0, sizeof(si));
    si.hStdInput = INVALID_HANDLE_VALUE;
    si.hStdOutput = h[1];
    si.hStdError = INVALUD_HANDLE_VALUE;
    si.dwFlags |= STARTF_USESTDHANDLES;
    CreateProcess(NULL, "cmd /c \"echo hello\"", NULL, NULL, TRUE, 0, NULL, NULL, &si, NULL);
    boost::iostreams::file_descriptor_source p(h[0]);
    

    (完全未经测试)

        2
  •  0
  •   Community Mohan Dere    9 年前