通过管道打开文件

时间:2013-04-10 04:49:01

标签: c++ file io

我正在尝试编写一个允许我在命令行输入类似内容的程序:

cat inputfile | myprogram outputfile

在myprogram中,我需要打开输入和输出文件,而输入文件不是参数。我知道如何打开输出文件并将其设置为描述符:

int out=open(argv[1],O_RDONLY);

但我不知道如何使用输入文件执行此操作。我知道cat的输出被发送到我的程序的cin但我不想逐行读取该文件。是否可以通过类似于打开输出文件的方式执行此操作?像这样:

int in=open(?????,O_RDONLY);

1 个答案:

答案 0 :(得分:0)

在C中它可以像

一样解决
#include<stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
        int flags=fcntl(0,F_GETFL);
        fcntl(0,F_SETFL,flags|O_NONBLOCK);
        char ch;
        while(read(0,&ch,1))
        {
                printf("%c",ch);
        }
}
相关问题