title: How to send a file with http with c++
body: <p>I want to write a server side code. It should work with popular browsers and wget. My server check that file exists or not, if exists then browser can download it. But I have some problems.
  Honestly, I read lots of question-answer (for example: <a href="https://stackoverflow.com/questions/5496200/send-binary-file-in-http-response-using-c-sockets">Send binary file in HTTP response using C sockets</a>) but I didn't find out. My browser (Chrome) can get text. But I cannot send any binary data or images etc. I am changing header according to downloading files. But I cannot send a downloadable files yet.</p>
  
  <p>I have some questions.</p>
  
  <pre><code>void *clientWorker(void * acceptSocket) {
       int newSocket = (int) acceptSocket;
       char okStatus[] = "HTTP/1.1 200 OK\r\n"
                         "Content-Type: text/html\r\n"
                         "Connection: close\r\n"
                         "Content-Length: 20\r\n"
                         "\r\n"
                         "s";
       writeLn(newSocket, okStatus);
       const char * fileName = "/home/tyra/Desktop/example.txt";
       sendF(newSocket, fileName);
  }
  </code></pre>
  
  <p><strong>1-</strong> If I wouldn't write "s" or something else in<code>okStatus</code>, my message cannot send. I don't understand anything of this.</p>
  
  <p>This is <code>writeLn</code> function :</p>
  
  <pre><code>void writeLn(int acceptSocket, const char * buffer) {
      int n = write(acceptSocket, buffer, strlen(buffer) - 1);
      if (n &lt; 0) {
          error("Error while writing");
      }
  }
  </code></pre>
  
  <p>This is <code>sendF</code> function :</p>
  
  <pre><code>string buffer;
  string line;
  ifstream myfile(fileName);
  struct stat filestatus;
  stat(fileName, &amp;filestatus);
  int fsize = filestatus.st_size;
  if (myfile.is_open()) {
      while (myfile.good()) {
          getline(myfile, line);
          buffer.append(line);
      }
      cout &lt;&lt; buffer &lt;&lt; endl;
  }
  writeLn(acceptSocket, buffer.c_str());
  cout &lt;&lt; fsize &lt;&lt; " bytes\n";
  </code></pre>
  
  <p>A little messy. I haven't used file size yet. If I send a file, then I rearrange these things.</p>
  
  <p><strong>2-</strong> I can send text and browser demonstrates it but browser didn't understand new lines.
  If text file contains (123\n456\n789), browser demonstrates (123456789). I think I should change Content-Type header, but I didn't find out. </p>
  
  <p>I don't want that browser demonstrates text files. Browser should download it. How can I send downloadable files?</p>
  
  <p>Sorry, I explain everything pretty complicated.</p>