title: Getting segmentation fault in Linux when running my C program
body: <p>I am trying to simulate the <a href="http://en.wikipedia.org/wiki/Cat_%28Unix%29" rel="nofollow">cat</a> command in <a href="http://en.wikipedia.org/wiki/Red_Hat_Linux" rel="nofollow">Red Hat Linux</a>. I am getting a <a href="http://en.wikipedia.org/wiki/Segmentation_fault" rel="nofollow">segmentation fault</a> when I run my program.</p>
  
  <p>For example:</p>
  
  <pre><code>./a.out a &gt; b
  </code></pre>
  
  <p><code>a</code> contains hello. I expect hello to be copied in <code>b</code>.</p>
  
  <p>My code is as follows:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;string.h&gt;
  
  int main(int argc,char *argv[])
  {
      int f, fd, r;
      char buf[100];
  
      if (argc &lt; 2)
      {
          printf("Error");
          return 0;
      }
      else
      {
          if (!strcmp(argv[2],"&gt;"))
          {
              f = open(argv[1],0,00777);
  
              if (f == -1)
                  printf("no file");
              else
              {
                  fd = creat(argv[3],00777);
                  while( (r = read(f,buf,50)) &gt; 0)
                      write(fd, buf, r);
              }
          }
      }
      return 0;
  }
  </code></pre>
  
  <p>Why am I getting a segmentaion error?</p>
  
  <p>I have a similar program where I open and create the file in the same manner, and that program is running, but this one is giving me a segmentation fault.</p>