Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading the whole text file into a char array in C

Tags:

c

text

file-io

I want to read the contents of a text file into a char array in C. Newlines must be kept.

How do I accomplish this? I've found some C++ solutions on the web, but no C only solution.

Edit: I have the following code now:

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; } 

I get one warning: warning: assignment makes pointer from integer without a cast. This is on the line size = (int)lSize;. If I run the app, it segfaults.

Update: The above code works now. I located the segfault, and I posted another question. Thanks for the help.

like image 443
friedkiwi Avatar asked Sep 19 '10 19:09

friedkiwi


1 Answers

FILE *fp; long lSize; char *buffer;  fp = fopen ( "blah.txt" , "rb" ); if( !fp ) perror("blah.txt"),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 */  fclose(fp); free(buffer); 
like image 149
user411313 Avatar answered Oct 01 '22 11:10

user411313