gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:18:43 24 4
gpt4 key购买 nike

我正在尝试将 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);

请在这里帮忙。

最佳答案

您尝试的重定向不是直接通过 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.

注意“连接管道”。

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

关于c - 将命令输出重定向到 C 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31927789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com