将 execvp 与输入文件一起使用到程序并将输出重定向到新文件
Use execvp with Input file to a program and redirection output to a new file
我确实尝试过使用 this and this 但无法正确使用(请在将其作为可能的副本引用之前注意链接)。
在我的程序中,我正在尝试 运行 一个使用文本文件作为输入的程序,并将程序的输出重定向到一个新文件。
这是我的代码:
if (fork() == 0) {
char *args[]={"program",">","output.txt",NULL};
int fd = open("/input.txt", O_RDONLY);
dup2(fd, 0);
execvp("program",args);
return 0;
}
program.c
是我正在尝试的程序 运行(不是我的主程序)
/input.txt
是我想用作 program.c
输入的文件
output.txt
是我想将程序输出重定向到的文件
我知道为了重定向我的程序输出我应该使用 programname>outputfile
.
但我无法让它工作,我想也许我在 args array
上做错了什么。发送 input.txt
作为 program.c
的输入并将其输出重定向到 output.txt
的正确方法是什么? (注意我的主程序不是program.c
)
如有任何帮助,我们将不胜感激
使用 programname>outputfile
是 shell 的一个功能。 shell 为您打开输出文件并将文件描述符复制到 1
(stdout
).
如果您不想 运行 一个 shell,您可以在调用 exec*
之前使用 open
和 dup2
进行输入重定向.尝试这样的事情:
int fdOut = open("output.txt", O_WRONLY | O_CREAT);
/* don't forget to check fdOut for error indication */
int rc = dup2(fdOut, 1);
/* also check the return code for errors here */
我确实尝试过使用 this and this 但无法正确使用(请在将其作为可能的副本引用之前注意链接)。
在我的程序中,我正在尝试 运行 一个使用文本文件作为输入的程序,并将程序的输出重定向到一个新文件。
这是我的代码:
if (fork() == 0) {
char *args[]={"program",">","output.txt",NULL};
int fd = open("/input.txt", O_RDONLY);
dup2(fd, 0);
execvp("program",args);
return 0;
}
program.c
是我正在尝试的程序 运行(不是我的主程序)
/input.txt
是我想用作 program.c
输入的文件
output.txt
是我想将程序输出重定向到的文件
我知道为了重定向我的程序输出我应该使用 programname>outputfile
.
但我无法让它工作,我想也许我在 args array
上做错了什么。发送 input.txt
作为 program.c
的输入并将其输出重定向到 output.txt
的正确方法是什么? (注意我的主程序不是program.c
)
如有任何帮助,我们将不胜感激
使用 programname>outputfile
是 shell 的一个功能。 shell 为您打开输出文件并将文件描述符复制到 1
(stdout
).
如果您不想 运行 一个 shell,您可以在调用 exec*
之前使用 open
和 dup2
进行输入重定向.尝试这样的事情:
int fdOut = open("output.txt", O_WRONLY | O_CREAT);
/* don't forget to check fdOut for error indication */
int rc = dup2(fdOut, 1);
/* also check the return code for errors here */