如何将标准输入(特定文件名)重定向到标准输出(特定文件名)
How to redirect stdin (specific file name) to stdout (specific file name)
我正在创建 shell 代码。基本上,我想将 stdin 文件重定向到 stdout 文件。例如,当我输入类似 sort < hello.c > t.txt 的命令时,应将 hello.c 文件复制到名为 t.txt.
的新文件中
这是我的代码,当我键入 ls > t.txt 时,我可以重定向其他命令的输出。但是,我不知道如何使用 dup2 将一个文件的输入重定向到另一个文件。
这是我的代码,我只发布循环,因为这是我必须创建逻辑的地方。
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);
输入数组就像
array[0]="sort"
array[1]="<"
array[2]="hello.c"
array[3]=">"
array[4]="t.txt"
事实上,每当你 运行 像 :
command < hello.c > t.txt
假设命令是您的 argv[0],没有参数为 1,并且重定向由 shell 进行。
然而,另一方面,通过你的程序,如果使用了重定向
不是从命令提示符,而是仅通过数组内容,
int dup2(int oldfd, int newfd);
- 创建文件描述符 oldfd 的副本。
在你的情况下,
dup2(in, 0);
dup2(out, 1);
0和1分别代表stdin和stdout文件描述符。所以,如果你想重定向你的输入从 stdin 而不是 hello.c (文件打开为 in),输出从 stdout 而不是 t.txt (文件打开为 out) , 那么不应该反过来,即
dup2(0, in);
dup2(1, out);
我正在创建 shell 代码。基本上,我想将 stdin 文件重定向到 stdout 文件。例如,当我输入类似 sort < hello.c > t.txt 的命令时,应将 hello.c 文件复制到名为 t.txt.
的新文件中这是我的代码,当我键入 ls > t.txt 时,我可以重定向其他命令的输出。但是,我不知道如何使用 dup2 将一个文件的输入重定向到另一个文件。
这是我的代码,我只发布循环,因为这是我必须创建逻辑的地方。
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);
输入数组就像
array[0]="sort"
array[1]="<"
array[2]="hello.c"
array[3]=">"
array[4]="t.txt"
事实上,每当你 运行 像 :
command < hello.c > t.txt
假设命令是您的 argv[0],没有参数为 1,并且重定向由 shell 进行。
然而,另一方面,通过你的程序,如果使用了重定向
不是从命令提示符,而是仅通过数组内容,
int dup2(int oldfd, int newfd);
- 创建文件描述符 oldfd 的副本。
在你的情况下,
dup2(in, 0);
dup2(out, 1);
0和1分别代表stdin和stdout文件描述符。所以,如果你想重定向你的输入从 stdin 而不是 hello.c (文件打开为 in),输出从 stdout 而不是 t.txt (文件打开为 out) , 那么不应该反过来,即
dup2(0, in);
dup2(1, out);