Redirect stdout to file

I am trying to execute the equivalent of the bash command ls>foo.txtin C.

The following code 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;
}

Comment lines relate to those operations that I believe are necessary for redirection. What should I change to redirect ls output to foo.txt?

+4
source share
2 answers

, , , ( ) stdout, stdout ls, ( ) 4 . .

stdout . , open(), stdout. - ( , ):

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;

, freopen, .

:

  • pipe() open() . .

  • fork() . .

  • dup2() dup(); , stdin , .

  • execlp() . .

  • , wait() (EINTR). , , (errno == EINTR).

+5

freopen().

, stdout output.txt ',

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

"a+" . , . .

stdout freopen() (printf, putchar) 'output.txt'. printf() 'output.txt'.

printf() ( / ), stdout, -

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

-

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

'stdin'.

+4

All Articles