简体   繁体   English

如何将标准输入(特定文件名)重定向到标准输出(特定文件名)

[英]How to redirect stdin (specific file name) to stdout (specific file name)

I am creating a shell code. 我正在创建一个外壳代码。 Basically, I want to redirect stdin file to stdout file. 基本上,我想将stdin文件重定向到stdout文件。 For instance when I enter a command like sort < hello.c > t.txt, then the hello.c file should be copied in new mentioned file called t.txt. 例如,当我输入诸如sort <hello.c> t.txt之类的命令时,应将hello.c文件复制到新提到的名为t.txt的文件中。

Here is my code, I am able to redirect output of other commands, when I type ls > t.txt. 这是我的代码,当我键入ls> t.txt时,我能够重定向其他命令的输出。 However, I don't have any idea about redirecting one file's input to other file using dup2. 但是,我不知道要使用dup2将一个文件的输入重定向到另一文件。

Here is my code, I am only posting the loop, as this is where I have to create the logic. 这是我的代码,我仅发布循环,因为这是我创建逻辑的地方。

int in, out;

for (i = 0; i < arridx; i++) {
    if(strcmp( array[i],"<")==0)
    {    
             in = open(array[i+1], O_RDONLY);        
             array[i]=0;
            // array[i+1]=0;
    }
    if(strcmp( array[i],">")==0)
    {
              out = open(array[i+1], O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
              array[i]=0;
             // array[i+1]=0;
    }
}
dup2(in, 0);
dup2(out, 1);

// close unused file descriptors
close(in);
close(out);

Input array would be like 输入数组就像

array[0]="sort"
array[1]="<"
array[2]="hello.c"
array[3]=">"
array[4]="t.txt"

In fact, whenever you run something like : 实际上,无论何时运行类似:

command < hello.c > t.txt

The redirection will take place presuming command is your argv[0] with no of arguments as 1, and redirection taking place by the shell. 重定向将发生,假设命令是您的argv [0],且参数个数均不为1,并且重定向由Shell进行。

However, on another point, going through your program, if redirection is used not from command prompt but by array contents only, int dup2(int oldfd, int newfd); 但是,在另一点上,遍历您的程序,如果不是从命令提示符使用重定向,而是仅通过数组内容使用重定向,则可以使用int dup2(int oldfd, int newfd); - creates a copy of the file descriptor oldfd. -创建文件描述符oldfd的副本。 In your case, 就你而言

dup2(in, 0);
dup2(out, 1);

0 and 1 stands for stdin and stdout file descriptors respectively. 0和1分别代表stdin和stdout文件描述符。 So, if you would like to redirect your input to be taken from the stdin instead of hello.c (file opened as in) and output to be taken from the stdout instead of t.txt (file opened as out), then shouldn't be other way round ie 因此,如果您想重定向输入,使其从标准输入而不是hello.c(文件以in打开)取回,而输出则从标准输出而不是t.txt(文件以out打开)取回,则不应该'反正就是

dup2(0, in);
dup2(1, out);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM