将c ++程序的输出管道输出到另一个程序

时间:2015-11-17 04:40:03

标签: 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 打开名为&#34; exampleTest.txt&#34;的文件。并显示该文件的内容

#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;
}

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

我尝试了什么:

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

我期望输出为:

abc 
def

我得到的是什么:

<no output>

我的推理: 主要的&#39;创建文件&#39; exampleTest.txt&#39;用abc def作为文件的输入。 虽然这个文件是给了&#39; pgm&#39; (管道到...),它应该能够读取文件内容和输出

abc
def

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

2 个答案:

答案 0 :(得分:2)

您将输出写入文件然后读取它们,但管道(通常)通过将一个程序的输出带到stdout并将其用作另一个程序的stdin输入来工作。

对您而言,最简单的解决方案可能是让main.cpp在完成后将输出文件名写入stdout。

修改

另一个选择是让main.cpp将行写入stdout以及文件,然后让pgm1.cpp从stdin而不是文件中读取行。根据您的其他要求,这可能是更好的解决方案,也可能不是。

答案 1 :(得分:2)

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

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

对程序的轻微修改可以证明这一点(方法之一):

的main.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