如何将system()的输出重定向到文件? [英] How to redirect the output of system() to a file?
问题描述
在此C
程序
#include <stdio.h>
#include <fcntl.h>
int main()
{
int file = open("Result", O_CREAT|O_WRONLY, S_IRWXU);
dup2(stdout, file);
system("ls -l");
return 0;
}
我正在尝试将 system()的输出重定向到文件,为此,我使用了 dup2 ,但是它不起作用.
I'm trying to redirect the output of system() to a file, for that i have used dup2 but it is not working.
此代码有什么问题?
并且,请告诉我是否有更好的方法来做到这一点? (不使用终端上的>
)
What's wrong with this code?
and, please tell me if there is any better way to do this? (without using >
at the terminal )
推荐答案
stdout
是标准输出流的FILE *
指针. dup2
需要文件描述符,您也弄乱了参数顺序.
使用
stdout
is a FILE *
pointer of the standard output stream. dup2
expects file descriptor, also you've messed up the parameters order.
Use
dup2(file, 1);
相反.
关于这部分的更好方法.这种方法很不好,因为您可能要在此system
调用完成之后恢复标准输出.您可以通过多种方式执行此操作.您可以在某处dup
,然后将其dup2
放回原处(并关闭dup
ped一个).我个人不喜欢编写其他答案中建议的自己的cat
实现.如果您唯一想做的就是将带有system
的单个shell命令重定向到文件系统中的文件,那么可能最直接,最简单的方法就是构造shell命令来做到这一点
On the better-way-to-do-this part. This way is bad because you probably want to restore your standard output after this system
call completes. You can do this in a variety of ways. You can dup
it somewhere and then dup2
it back (and close the dup
ped one). I personally don't like writing own cat
implementations as suggested in other answers. If the only thing you want is redirecting a single shell command with system
to a file in the filesystem, then probably the most direct and simple way is to construct the shell command to do this like
system("ls -l > Result");
但是,如果文件名(结果)来自用户输入,则必须小心,因为用户可以提供诸如'Result; rm -rf /*'
之类的文件名.
But you have to be careful if filename (Result) comes from user input as user can supply something like 'Result; rm -rf /*'
as the filename.
此外,在安全性主题上,您应该考虑按照注释中的建议指定ls
的完整路径:
Also, on the topic of security, you should consider specifying the full path to ls
as suggested in the comments:
system("/bin/ls -l > Result");
这篇关于如何将system()的输出重定向到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!