c++ - 将 C++ 程序的输出通过管道传递给另一个程序

标签 c++ bash unix

main.cpp 采用 2 个命令行参数并打开名为“exampleTest.txt”的文件并写入该文件。

#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
    ofstream op;
    op.open("exampleTest.txt",ios::out);
    op<<argv[1]<<"\n"<<argv[2]<<endl;
    op.close();
    return 0;
}

pgm1.cpp 打开名为“exampleTest.txt”的文件并显示该文件的内容

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
    string line;
    ifstream fs;
    fs.open("exampleTest.txt",ios::in);

    if (fs.is_open())
    {
        while(getline(fs,line))
        {
            cout<<line<<endl;

        }
    }
    fs.close();

    return 0;
}

通过编译这两个程序并单独运行它们就可以了。 但是,我想将 main.cpp 的输出通过管道传递给程序 pgm1.cpp

我尝试了什么:

g++ main.cpp -o main
g++ pgm1.cpp -o pgm
./pgm |./main abc def

我期望的输出是:

abc 
def

我得到的是:

<no output>

我的推理: 'main' 创建文件 'exampleTest.txt' 并将 abc def 作为文件的输入。 虽然此文件已提供给“pgm”(通过管道传输到...),但它应该能够读取文件内容并输出

abc
def

在终端中,我没有得到任何输出。 (如果我分别运行每个文件,则有效)
你能告诉我我错过了什么吗?

最佳答案

$./main aaa cccc ;./pgm
aaa
cccc

由于您正在将主程序的输出写入文件并使用文件名(硬编码)作为 pgm1.cpp 文件,因此使用管道重定向不会有帮助,因为管道通常将标准输入作为输入。

对您的程序稍加修改就可以证明这一点(方法之一):

主要.cpp

#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
    ofstream op;
    op.open("exampleTest.txt",ios::out);
    op<<argv[1]<<"\n"<<argv[2]<<endl;
    op.close();
    cout << "exampleTest.txt";
    return 0;
}

pgm1.cpp

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
    string line;
    ifstream fs;
    fs.open(argv[1],ios::in);

    if (fs.is_open())
    {
        while(getline(fs,line))
        {
            cout<<line<<endl;

        }
    }
    fs.close();

    return 0;
}

输出:

  $ ./main ddd eee | xargs ./pgm
    ddd
    eee

关于c++ - 将 C++ 程序的输出通过管道传递给另一个程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33749301/

相关文章:

bash - 使用带分隔符的 AWK 打印特定列

bash - 在 bash/unix 中获取以前的日期

c++ - 如何检查ACL是否被保护

linux - 重定向本身就是参数的程序的输出

bash - 将大量文件压缩为 n 个 zip 文件

linux - bash 脚本打开 chrome 然后在 chrome 关闭时关闭计算机

linux - 在 unix 中使用 bash 恢复已删除的文件

c++ - 如何使用返回而不是 '\n' 将换行符添加到 stringstream 或字符串?

c++ - 如何根据变量包含的值创建一定数量的线程?

C++ 可变参数模板来替换类型列表