Redirect stdout to a file

38,848

Solution 1

What your code essentially does is that you open a pipe, then fork the process and in the child process (in commented code) close stdout, duplicate the pipe to stdout and execute and ls command, and then (in non-commented code) write 4 bytes to the pipe. In the parent process, you read data from the pipe and wait for the completion of the child process.

Now you want to redirect stdout to a file. You can do that by opening a file using the open() system call and then duplicating that file descriptor to stdout. Something like (I haven't tested this so beware of bugs in the code):

int filefd = open("foo.txt", O_WRONLY|O_CREAT, 0666);
if (!fork()) {
  close(1);//Close stdout
  dup(filefd);
  execlp("ls", "ls", NULL);
} else {
  close(filefd);
  wait(NULL);
}
return 0;

However, you can also use the freopen as suggested by the other answer.

However, I have several concerns of your code and of my modified code:

  • The pipe() and open() system calls can fail. You should always check for system call failure.

  • The fork() system call can fail. Ditto.

  • dup2() can be used instead of dup(); otherwise the code will fail if stdin is not open as it duplicates to the first available file descriptor.

  • The execlp() system call can fail. Ditto.

  • I think wait() can be interrupted by a signal (EINTR). It's recommended to wrap it around a wrapper that retries the system call if it's aborted by a signal (errno == EINTR).

Solution 2

While dealing with redirecting output to a file you may use freopen().

Assuming you are trying to redirect your stdout to a file 'output.txt' then you can write-

freopen("output.txt", "a+", stdout); 

Here "a+" for append mode. If the file exists then the file open in append mode. Otherwise a new file is created.

After reopening the stdout with freopen() all output statement (printf, putchar) are redirected to the 'output.txt'. So after that any printf() statement will redirect it's output to the 'output.txt' file.

If you want to resume printf()'s default behavior again (that is printing in terminal/command prompt) then you have to reassign stdout again using the following code-

freopen("/dev/tty", "w", stdout); /*for gcc, ubuntu*/  

Or -

freopen("CON", "w", stdout); /*Mingw C++; Windows*/ 

However similar technique works for 'stdin'.

Share:
38,848
qwerty
Author by

qwerty

I write code.

Updated on July 09, 2022

Comments

  • qwerty
    qwerty almost 2 years

    I am trying to do the equivalent of the bash command ls>foo.txt in C.

    The code bellow redirects the output to a variable.

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <sys/wait.h>
    
    int main(){
      int pfds[2];
      char buf[30];
    
      pipe(pfds);
    
      if (!fork()) {
        close(pfds[0]);
         //close(1);//Close stdout
        //dup(pfds[1]);
        //execlp("ls", "ls", NULL);
        write(pfds[1], "test", 5); //Writing in the pipe
        exit(0);
      } else {
        close(pfds[1]);  
        read(pfds[0], buf, 5); //Read from pipe
        wait(NULL);
      }
      return 0;
    }
    

    The comments lines refer to those operations that I believe that are required for the redirection. What should I change to redirect the output of ls to foo.txt?