title: c socket file transfer
body: <p>Let me start by saying this is a homework assignment and I am not a c programmer.  I have been working on this for days and I am stuck.  I have read the beej guide from cover to cover and have been searching google for a week, it's time to ask for help.  I have a client-server TCP socket application that sends and receives messages as expected, now I need to implement simple file upload/download functionality.  </p>
  
  <p>The code below almost works but it adds 4 bytes to the beginning of the copied file, two non-printable characters followed by \00\00 and the client no longer responds.  </p>
  
  <p>The client is connected by a non-blocking socket using the select command.  </p>
  
  <p>I know there is lots of room for improvement but can someone help me get started?</p>
  
  <p>// Server</p>
  
  <pre><code>void put (int sockfd, char *localfile) {
  
      // Get file Size
      FILE *file;
      int size;
  
      file = fopen(localfile, "rb");
      fseek(file, 0, SEEK_END);
      size = ftell(file);
      fseek(file, 0, SEEK_SET);
  
      //Send file Size
      write(sockfd, &amp;size, sizeof(int));
  
      //Send file as Byte Array
      char send_buffer[size];
  
      memset(send_buffer, 0, sizeof(send_buffer));
      //while(!feof(file)) {
      //    fread(send_buffer, 1, sizeof(send_buffer), file);
      //    write(sockfd, send_buffer, sizeof(send_buffer));
      //    memset(send_buffer, 0, sizeof(send_buffer));
      //}
  
      int sent;
  
      while((sent = fread(send_buffer, sizeof(char), sizeof(send_buffer), file)) &gt; 0)
      {
          if(send(sockfd, send_buffer, sent, 0) &lt; 0)
          {
              fprintf(stderr, "[Server] ERROR: Failed to send file %s. (errno = %d)\n", localfile, errno);
              break;
          }
          memset(send_buffer, 0, sizeof(send_buffer));
      }
      fclose(file);
  }
  </code></pre>
  
  <p>//Client</p>
  
  <pre><code>void get(int sockfd, char *remotefile) {
  
      FILE *file;
      int size;
  
      //Read file Size
      read(sockfd, &amp;size, sizeof(int));
  
      //Read file Byte Array
      char p_array[size];
      memset(&amp;p_array, 0, sizeof(p_array));
  
      read(sockfd, p_array, size);
  
      //Convert it Back into file
      file = fopen(remotefile, "wb");
      fwrite(p_array, 1, sizeof(p_array), file);
      fclose(file);
  }
  </code></pre>