How to redirect the output of system() to a file?

后端 未结 4 1290
忘了有多久
忘了有多久 2021-01-02 21:34

In this C program

#include 
#include 
int main()
{
    int file = open(\"Result\", O_CREAT|O_WRONLY, S_IRWXU);

         


        
4条回答
  •  北海茫月
    2021-01-02 22:38

    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);
    

    instead.

    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 dupped 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");
    

    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.

    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");
    

提交回复
热议问题