title: c sending image through socket
body: <p>I'm making a simple http server. So far socket works for html files, now I'm trying to make work images.</p>
  
  <p>This is how I read files:</p>
  
  <pre><code>char * fbuffer = 0;
  long length;
  FILE *f;
  
  if ((f = fopen(file, "r")) == NULL)
  {
      perror("Error opening file");
      exit(1);
  }
  
  fseek (f, 0, SEEK_END);
  length = ftell(f);
  fseek (f, 0, SEEK_SET);
  fbuffer = malloc(length);
  int total = 0;
  if (fbuffer)
  {
      while (total != length)
      {
          total += fread(fbuffer, 1, length, f);
      }
  }
  fclose (f);
  </code></pre>
  
  <p>Then I just send data to socket:</p>
  
  <pre><code>char response[20048];
  snprintf(response, sizeof(response), "HTTP/1.1 200 OK\nContent-Type: %s\nContent-Length: %i\n\n%s", type, (int) strlen(fbuffer), fbuffer);
  n = send(newsockfd, response, strlen(response)+1, 0);
  </code></pre>
  
  <p>Why it doesn't work for images? Browser is showing an error <code>The image “http://127.0.0.1:1050/image.gif” cannot be displayed because it contains errors.</code> Http response is:</p>
  
  <pre><code>Content-Length: 7
  Content-Type: image/gif
  </code></pre>
  
  <p>The image has 247 bytes. In variables length and total are values 247. Variable fbuffer contains GIF89a(+one char -> some binary square with values 0 0 1 0).</p>
  
  <p>What am I doing wrong?</p>
  
  <p>Thanks.</p>