title: C - printf output varies depending on subsequent code
body: <p><strong>Preface</strong>: I am just engaging C, so forgive my incompetence. The cause of this problem is probably basic.</p>
  
  <p><strong>Problem</strong>: I am trying to read a file and serve it over http with a socket. For some reason, the <code>printf</code> output of a previously read file varies depending on how much of the subsequent code is included.</p>
  
  <p>Here is my code.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  #include &lt;sys/socket.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;unistd.h&gt;
  
  #include &lt;netinet/in.h&gt;
  
  
  int main()
  {
  
      // open a file to serve
      FILE *file;
      file = fopen("index.html", "r");
      if (file == NULL)
      {
          printf("Failed to open file.");
          exit(EXIT_FAILURE);
      }
  
      // Get file content
      char file_content[1024];
      if (fgets(file_content, 1024, file) != NULL)
      {
  
          fclose(file);
  
          // Add header to file content
          char http_header[2048] = "HTTP/1.1 200 OK\r\n\n";    
          strncat(http_header, file_content, 1028);
  
          // This output varies depending on inclusion of proceeding code.
          printf("%s", http_header);
  
          // create a socket
          int server_socket;
          server_socket = socket(AF_INET, SOCK_STREAM, 0);        
  
          // define the address
          struct sockaddr_in server_address;
          server_address.sin_family = AF_INET;
          server_address.sin_port = htons(8001);
          server_address.sin_addr.s_addr = INADDR_ANY;
  
          bind(server_socket, (struct sockaddr *) &amp;server_address, sizeof(server_address));        
          listen(server_socket, 1);
  
          int client_socket;        
          while (1)
          {
              client_socket = accept(server_socket, NULL, NULL);
              send(client_socket, http_header, sizeof(http_header), 0);
              close(client_socket);
          }
          return 0;
      }
  
  }
  </code></pre>
  
  <p>If I comment out everything past the <code>printf</code> statement, I get this intended output..</p>
  
  <pre><code>HTTP/1.1 200 OK
  
  &lt;html&gt;&lt;body&gt;Hi&lt;/body&gt;&lt;/html&gt;
  </code></pre>
  
  <p>But if I run all the code, I get this instead..</p>
  
  <pre><code>HTTP/1.1 200 OK
  </code></pre>
  
  <p>If I can improve my question at all, please let me know how. Thank you.</p>