title: Using open(), read() and write() system calls to copy a file
body: <p>I'm having trouble using <code>read()</code>, <code>write()</code>, and <code>open()</code> to copy a file into a new directory. I'm able to create a new file with <code>open()</code> and I'm able to write to the terminal with <code>write()</code> but I was under the assumption that if I passed my <code>int</code> file descriptor from open to write, write would write to the specified file.</p>
  
  <p>In addition to this, once I open a file the permissions are all funky and I can only open it as root. Each time I create a file, it's completely empty but I can see the entire file I just read be printed out in the terminal.</p>
  
  <p>I've read through the man files for each system call but I'm still not grasping what the issue is here.</p>
  
  <p>Here's my code:</p>
  
  <pre><code>void *scanFile( s_request *request )
  {
      //TODO Print out all struct variables.
      pthread_mutex_lock(&amp;mutex);
  
      int readFileReference;
      int writeFileReference;
      int bufferSize = request-&gt;bufferSize;
      int numberOfBytesRead = bufferSize;
      int *buffer[bufferSize];
  
      if ((readFileReference = open(request-&gt;file, O_RDONLY)) == -1)
      {
          printf("Failed to open file. Aborting.\n");
          exit(EXIT_FAILURE);
      }
  
      if ((writeFileReference = open("newfile.txt", O_CREAT | O_APPEND | O_RDWR) == -1))
      {
          printf("Failed to open write file. Aborting.\n");
          exit(EXIT_FAILURE);
      }
  
      while ((read(readFileReference, buffer, numberOfBytesRead)) != 0)
      {
          write(writeFileReference, buffer, bufferSize);
          bzero(buffer, bufferSize);
      }
  
      pthread_mutex_unlock(&amp;mutex);
  }
  </code></pre>
  
  <p>Fixed the issue:</p>
  
  <p>Updated code:</p>
  
  <pre><code>void *scanFile( s_request *request )
  {
      //TODO Print out all struct variables.
      pthread_mutex_lock(&amp;mutex);
  
      int readFileReference;
      int writeFileReference;
      int bufferSize = request-&gt;bufferSize;
      int numberOfBytesRead = bufferSize;
      int *buffer[bufferSize];
  
      if ((readFileReference = open(request-&gt;file, O_RDONLY)) == -1)
      {
          printf("Failed to open file. Aborting.\n");
          exit(EXIT_FAILURE);
      }
  
      if ((writeFileReference = open("newfile.txt", O_CREAT | O_WRONLY, 0777)) == -1)
      {
          printf("Failed to open write file. Aborting.\n");
          exit(EXIT_FAILURE);
      }
  
      while ((read(readFileReference, buffer, numberOfBytesRead)) != 0)
      {
          write(writeFileReference, buffer, bufferSize);
          bzero(buffer, bufferSize);
      }
  
      close(writeFileReference);
      close(readFileReference);
  
      pthread_mutex_unlock(&amp;mutex);
  }
  </code></pre>