title: Redirect stdout to a file
body: <p>I am trying to do the equivalent of the bash command <code>ls&gt;foo.txt</code> in C.</p>
  
  <p>The code bellow redirects the output to a variable.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/wait.h&gt;
  
  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;
  }
  </code></pre>
  
  <p>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?</p>