将命令输出重定向到C中的文件

时间:2015-08-10 19:41:05

标签: c

我正在尝试将ls命令的输出重定向到文件fout.txt 但文件fout.txt仅包含 这是输出

以下是我的计划:

int fout, ferr;
char *tok[3];
tok[0] = "ls", tok[1] = ">", tok[2] = "fout.txt";
fout = open("fout.txt", O_RDWR|O_CREAT|O_APPEND, 0600);
ferr = open("ferr.txt", O_RDWR|O_CREAT|O_APPEND, 0600);
puts("Here is the output\n");
execvp(tok[0], tok);
close(fout);
close(ferr);

请在这里帮忙。

2 个答案:

答案 0 :(得分:4)

您尝试的重定向不是通过execvp()调用直接完成的。它已在bash like this完成:

/* Execute a simple command that is hopefully defined in a disk file
   somewhere.

   1) fork ()
   2) connect pipes
   3) look up the command
   4) do redirections
   5) execve ()
   6) If the execve failed, see if the file has executable mode set.
   If so, and it isn't a directory, then execute its contents as
   a shell script.

   Note that the filename hashing stuff has to take place up here,
   in the parent.  This is probably why the Bourne style shells
   don't handle it, since that would require them to go through
   this gnarly hair, for no good reason.

注意"连接管道"。

(这并不是一个完整的答案 - 提问者应该被要求研究某事 ......)

答案 1 :(得分:4)

不同的重定向字符(< > >> |)由shell解释。当您要求执行直接execvp时,您只需执行带有参数ls>的{​​{1}}命令。

当我这样做时,我上了stderr:

fout.txt

要使用exec系列函数重定向,必须明确打开文件并使用ls: >: No such file or directory ls: fout.txt: No such file or directory 将它们连接到stdin(0),stdout(1)和/或stderr(2),如{{3}所示}}