How to redirect system () output to a file?

In this program 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;
}

I am trying to redirect the output of system () to a file for which I used dup2 , but it does not work.

What is wrong with this code ? and please tell me is there a better way to do this ? (without use >on the terminal)

+6
source share
4 answers

stdoutis a pointer to the FILE *standard output stream. dup2expects a file descriptor, also you have mixed up the order of the parameters. Use

dup2(file, 1);

instead.

, . , , , system. . dup -, dup2 ( dup ped one). cat, . system , , , ,

system("ls -l > Result");

, () , - 'Result; rm -rf /*' .

, ls, :

system("/bin/ls -l > Result");
+6

>:

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

    return 0;
}

popen(), -

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

popen() FILE * , .

+4

dup dup2. dup , .

new_fd = dup(file); - file 3 ( stdin 0, stdout is 1 stderr is 2). new_fd 4

If you want to redirect stdoutto a file. Then do as shown below.

close(stdout);
new_fd = dup(file);

Now dup will return 1 as an alias for the descriptor filebecause we have closed stdout, therefore the open file descriptors 0,2,3and 1are the smallest file descriptor available.

If you use dup2means, dup2(file,1);follow these steps

0
source

All Articles