title: Send binary file over TCP/IP connection
body: <p>I will rephrase the whole question here so that it is answerable.</p>
  
  <p>I am able to copy binary file perfectly in the same machine not using sockets but just making a simple copy function. Trying to implement this code for copying onto a TCP/IP connection but can't get it to work.</p>
  
  <pre><code>FILE *filehandle = fopen("imagefile.jpg", "rb");
  FILE *dest  =fopen("imagecopy.jpg", "wb");    // copied image file
  fseek(filehandle, 0, SEEK_END);
  unsigned long filesize = ftell(filehandle);
  char *buffer = (char*)malloc(sizeof(char)*filesize);
  rewind(filehandle);
  int bytesread = fread(buffer, sizeof(char), filesize, filehandle);
  for( int i=0; i&lt;filesize; i++ )
  {
      fputc(buffer[i], filehandle);    // copies all the contents to dest
  }
  </code></pre>
  
  <p>The code above works perfectly for copying an image file in the computer but when implemented to copy on server, it is difficult to go about it.</p>
  
  <p>I am trying to send an image file from a <strong>server</strong> to a <strong>client</strong> both which have been made manually in C. The length of the file to be sent by the server is only known to the server when it's sending the file so the buffer is dynamically generated in the server, something like this:</p>
  
  <p><strong>SERVER</strong></p>
  
  <pre><code>fseek(filehandle, 0, SEEK_END);
  long filesize = ftell(filehandle);    // file could be 11000bytes
  char *buffer = (char*)malloc(sizeof(char)*filesize);    // char buffer with 11000 bytes to store the data from the file.
  // then I call the send() function
  rewind(filehandle);    // go back to beginning
  send(clientsocket, buffer, filesize, 0);    // this is being sent perfectly, no errors because in the actual code, I am checking for errors
  </code></pre>
  
  <p><strong>CLIENT</strong></p>
  
  <pre><code>// here is where I don't understand how to dynamically allocate the 11000 bytes to store the data in a client buffer
  // the filesize is not necessarily going to be 11000 so need to dynamically allocate
  // I did the following:
  #define BUFSIZE 10
  FILE *filehandle = fopen("imagefile.jpg", "wb");    // image file created by client
  char *buffer = (char*)malloc(sizeof(char)*BUFSIZE);
  int bytesread = recv(buffer, 1, strlen(buffer), 0);
  if( bytesread &gt; 0 )
  {
      printf("Bytes read: %d\n", bytesread);    // bytes read is 5
      printf("Buffer: %s\n", buffer);    // but buffer shows all the binary text like it normally would
      // when I try to store buffer in a file, it doesn't put full buffer because only 5 characters are written
      for( int i=0; i&lt;bytesread; i++ )
      {
          fputc(buffer[i], filehandle);    // this doesn't create full image
      }
  }
  </code></pre>
  
  <p><strong>How can I dynamically allocate the 11000 bytes sent by the server?</strong></p>