Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In this C program

#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;
}

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 )

like image 647
Eight Avatar asked Jun 25 '12 12:06

Eight


3 Answers

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");
like image 190
unkulunkulu Avatar answered Oct 02 '22 20:10

unkulunkulu


The simple thing is to use > indeed:

#include <stdio.h>
int main()
{
    system("ls -l > /some/file");

    return 0;
}

An alternative is using popen(), something along the lines of

   #include <stdio.h>
   #include <stdlib.h>
   main()
   {
           char *cmd = "ls -l";
           char buf[BUFSIZ];
           FILE *ptr, *file;

           file = fopen("/some/file", "w");
           if (!file) abort();
           if ((ptr = popen(cmd, "r")) != NULL) {
                   while (fgets(buf, BUFSIZ, ptr) != NULL)
                           fprintf(file, "%s", buf);
                   pclose(ptr);
           }
           fclose(file);
           return 0;
   }
like image 20
johannes Avatar answered Oct 02 '22 18:10

johannes


You should use the popen() library function and read chunks of data from the returned FILE * and write them to whatever output file you like.

Reference.

like image 20
trojanfoe Avatar answered Oct 02 '22 18:10

trojanfoe