tags:

views:

166

answers:

2

Hi,

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.

Thanks!

Yvan

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.

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

+1  A: 

fgets() is a C function that can be used to accomplish this.

Edit: You can also consider using fread().

Gunner
on windows you might want to open in binary mode so it doesn't translate cr
Martin Beckett
Does it read the whole file at once?
Yvan JANSSENS
No it doesn't. It reads upto newline or end of file. However, the newline read is preserved. Therefore, you could append the read characters directly to the char array and newlines will appear in same manner as the file.
Gunner
Using `fgets` for this purpose makes no sense. It'll be a lot more complicated than a single `fread` and more errorprone. Consider the extra work you'd have to do to handle embedded NUL bytes, for instance..
R..
Oh Yes, fread is an option as well.
Gunner
+2  A: 
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);
You can close the file before working on the data, rather than after.
R..