c++ - 运行 .exe 并重定向标准输入和输出

标签 c++ c++11 redirect

在我生命的大部分时间里,我一直在使用 cstdio。现在我正尝试转移到 iostream

假设我有一个名为“foo.cpp”的单独程序,如下所示:

int main(){ // foo.cpp
    int x;
    std::cin >> x;
    std::cout << x + 5 << "\n";
}

在另一个名为“bar.cpp”的程序中,我调用了 foo 可执行文件。过去,如果我想将 stdin 和 stdout 重定向到一个文件,我会像这样使用 freopen:

int main(){ // bar.cpp, redirecting stdin and stdout
    freopen("foo.in", "r", stdin); // Suppose "foo.in" contains a single integer "42"
    freopen("foo.out", "w", stdout);

    system("foo.exe"); // "foo.out" will contain "47"
}

现在我正在尝试将 std::cinstd::cout 重定向到字符串流。像这样:

int main(){ // bar.cpp, redirecting cin and cout
    std::istringstream instr("62");
    std::ostringstream outstr;

    std::cin.rdbuf(instr.rdbuf());
    std::cout.rdbuf(outstr.rdbuf());

    system("foo.exe"); // outstr should contain "67"
}

但我了解到,std::cinstd::cout 在执行“foo.exe”时没有被重定向。该程序现在需要用户输入并将打印到 std::cout。 “foo.exe”执行完成后,“bar.cpp”中的 std::cinstd::cout 仍然重定向到 instroutstr 分别。

我的问题是,是否有办法像我预期的那样使用 iostream 来完成,或者我是否坚持使用 freopen

最佳答案

有一段时间没看到 freopen 调用了。这带回了一些旧的记忆。

无论如何,我认为您应该坚持使用 freopendocumentation该函数的页面从字面上说明这是主要用例之一:

This function is especially useful for redirecting predefined streams like stdin, stdout and stderr to specific files.

我认为您不能仅使用 iostream 进行重定向,因为 iostream 库没有与 freopen 等效的库> 功能。

有趣的是为什么您尝试的这个解决方案不起作用:

std::cin.rdbuf(instr.rdbuf());
std::cout.rdbuf(outstr.rdbuf());

也许使用这两行你只会影响当前进程的 std::cinstd::coutrdbuf 和subprocess 有另一个 std::cinstd::cout 实例。

当调用system时,文件的信息似乎从父进程复制到子进程。这就是为什么您在主进程中使用 freopenstdinstdout 上所做的更改在子进程中也是可见的。

无论如何,you should not use system从主 C++ 程序运行子程序。因为你可能在 Windows 上(从 foo.exe 猜测),我会分析这个 example来自微软。它解释了如何创建子进程并使用管道重定向子程序的输入和输出。

关于c++ - 运行 .exe 并重定向标准输入和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43500658/

相关文章:

c++ - Windows C++ GUI 应用程序

c++ - 禁止跨编译单元包含不兼容的 header

c++ - 有关模板和虚拟功能的问题

c++ - 保存累加器的每次迭代?

具有显式构造函数的不可复制类型的 C++11 数组初始化

javascript - 将 React-Hook 与重定向和 setTimeout 结合使用

c++ - 使用 vector 和 QVector 进行奇怪的内存管理

c++ - 无法将 insert() 结构插入 unordered_set

asp.net - 当我们想重定向到 asp.net : using a link button and then Response. 重定向或使用 html <a> 链接中的新页面时,哪个更好?

.htaccess - HTACCESS 中带有字符 % 的 URL 重定向