Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c+的管道输出+;程序到另一个程序_C++_Bash_Unix - Fatal编程技术网

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

C++ c+的管道输出+;程序到另一个程序,c++,bash,unix,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]<<

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;
}
我期望的输出是:

abc 
def
我得到的是:

<no output>
在终端中,我没有得到任何输出。(如果我单独运行每个文件,则有效)

您能告诉我我遗漏了什么吗?

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

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

编辑

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

$./main aaa cccc ;./pgm
aaa
cccc
由于您正在将主程序的输出写入文件,并在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;
}

你真的需要阅读管道的基础知识,而不是在这里提问。使用xargs将删除该问题!是的,我打算更新这个作为答案。我需要顺序执行命令,即一个接一个地执行命令,而不是将一个程序的操作传递到另一个程序。谢谢你的邀请。在C和C++ 25年之后,我才发现,可以使用C++ CUT流操作符(如:CUTH@ G Fetterman)发送文件(Excel)的内容(例如,CypEtEXT.TXT):是否可以重新路由OFFROW(磁盘文件)编写代码,而不是通过管道将其发送到另一个程序(Linux上)。所以不是文件
abc
def
$./main aaa cccc ;./pgm
aaa
cccc
#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;
}
#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