title: Reading the whole text file into a char array in C
body: <p>I want to read the contents of a text file into a char array in C. Newlines must be kept.</p>
  
  <p>How do I accomplish this? I've found some C++ solutions on the web, but no C only solution.</p>
  
  <p>Edit: I have the following code now:</p>
  
  <pre><code>void *loadfile(char *file, int *size)
  {
      FILE *fp;
      long lSize;
      char *buffer;
  
      fp = fopen ( file , "rb" );
      if( !fp ) perror(file),exit(1);
  
      fseek( fp , 0L , SEEK_END);
      lSize = ftell( fp );
      rewind( fp );
  
      /* allocate memory for entire content */
      buffer = calloc( 1, lSize+1 );
      if( !buffer ) fclose(fp),fputs("memory alloc fails",stderr),exit(1);
  
      /* copy the file into the buffer */
      if( 1!=fread( buffer , lSize, 1 , fp) )
        fclose(fp),free(buffer),fputs("entire read fails",stderr),exit(1);
  
      /* do your work here, buffer is a string contains the whole text */
      size = (int *)lSize;
      fclose(fp);
      return buffer;
  }
  </code></pre>
  
  <p>I get one warning:  warning: assignment makes pointer from integer without a cast. This is on the line <code>size = (int)lSize;</code>. If I run the app, it segfaults.</p>
  
  <p><em>Update:</em> The above code works now. I located the segfault, and I posted another question. Thanks for the help.</p>