If you want to read the whole file, just use fread():
Code:
#include <stdio.h>
#include <malloc.h>
int main()
{
long length;
char* buf;
size_t bytes;
FILE* file = fopen( "c:/file.txt", "rb" );
if ( file == NULL )
{
printf( "Error opening file!" );
return 1;
}
if ( fseek( file, 0, SEEK_END ) != 0 )
{
fclose( file );
printf( "fseek() failed!" );
return 2;
}
if ( (length = ftell( file )) < 0 )
{
fclose( file );
printf( "ftell() failed!" );
return 3;
}
if ( fseek( file, 0, SEEK_SET ) != 0 )
{
fclose( file );
printf( "fseek() failed!" );
return 2;
}
if ( (buf = malloc( length + 1 )) == NULL )
{
fclose( file );
printf( "malloc() failed!" );
return 4;
}
if ( (bytes = fread( buf, 1, length, file )) != (size_t)length )
{
free( buf );
fclose( file );
printf( "fread() didn't read %d bytes!", length );
return 5;
}
fclose( file );
buf[length] = '\0';
printf( "Text file contents:\n%s", buf );
free( buf );
return 0;
}