title: Writing my own linux shell I/O redirect '>' function
body: <p>I am writing the redirect function that writes the output of a command to a given filename.</p>
  
  <p>For example:</p>
  
  <p><code>echo Hello World &gt; hello.txt</code> would write 'Hello World' into hello.txt.</p>
  
  <p><code>ls -al &gt; file_list.txt</code> would write the list of all file/directory names in the current directory into file_list.txt.</p>
  
  <p>My function so far is defined as:</p>
  
  <pre><code>int my_redirect(char **args, int count) {
      if (count == 0 || args[count + 1] == NULL) {
          printf("The redirect function must follow a command and be followed by a target filename.\n");
          return 1;
      }
      char *filename = args[count + 1];
  
      //Concatenates each argument into a string separated by spaces to form the command
      char *command = (char *) malloc(256);
      for (int i = 0; i &lt; (count); i++) {
          if (i == 0) {
              strcpy(command, args[i]);
              strcat(command, " ");
          }
          else if (i == count - 1) {
              strcat(command, args[i]);
          }
          else {
              strcat(command, args[i]);
              strcat(command, " ");
          }
      }
  
      //command execution to file goes here
  
      free(command);
      return 1;
  }
  </code></pre>
  
  <p>where <code>args[count]</code> is <code>"&gt;"</code>. </p>
  
  <p>How can I execute the command given by the string from <code>args[0]</code> to <code>args[count - 1]</code> into the file given at <code>args[count + 1]</code>?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>These are the instructions we have been given:</p>
  
  <p>"Improve your shell by adding a redirect for stdout to a file. Only attempt after completing Feature 1. Parse the line for >, take everything before as command, and the first word after as the filename (ignore &lt;, >>, | etc).</p>
  
  <p>Standard out is written out to file descriptor 1 (stdin is 0, stderr is 2). So this task can be achieved by opening the file, and copying it’s file descriptor over to 1 with dup2 system call.</p>
  
  <pre><code>int f = open( filename , O_WRONLY|O_CREAT|O_TRUNC, 0666) ;
  dup2( f , 1 ) ;
  </code></pre>
  
  <p>Note: Using system call open not library wrapper fopen here."</p>