is there an easier way to figure out how big a file is other than to just read it until EOF? (in C obviously)
is there an easier way to figure out how big a file is other than to just read it until EOF? (in C obviously)
>is there an easier way to figure out how big a file is other than to just read it until EOF?
Fortunately, there is.
-PreludeCode:#include <stdio.h> int main ( void ) { FILE *fptr; int filesize; fptr = fopen ( "somefile", "r" ); if ( fptr != NULL ) { fseek ( fptr, 0, SEEK_END ); filesize = ftell ( fptr ); fclose ( fptr ); } return 0; }
My best code is written with the delete key.
excellent! thanks
and now if i want to read the file from the beginning i call
right?Code:fseek (fptr, 0, SEEK_SET);
the reason i wanted to know the size first before i read through the whole file anyway btw is that i needed to malloc() an array of structs to read the data into.
>fseek (fptr, 0, SEEK_SET);
That would work, I personally would use
rewind ( fptr );
since not only does it reset the file pointer to the beginning of the file, it clears any errors so the file is fresh for the first real use. Not like you will get many errors just by getting the size, but it never hurts to be extra careful.
If you are using the file size to allocate memory, be sure to divide it evenly for the structures. If filesize returns 100 but there are only 10 structures of 10 bytes and you allocate an array of 100 you've wasted a lot of space.
-PreludeCode:array = malloc ( filesize / sizeof ( struct something ) );
Last edited by Prelude; 07-31-2002 at 10:06 PM.
My best code is written with the delete key.
done and doneOriginally posted by Prelude
>fseek (fptr, 0, SEEK_SET);
That would work, I personally would use
rewind ( fptr );
since not only does it reset the file pointer to the beginning of the file, it clears any errors so the file is fresh for the first real use. Not like you will get many errors just by getting the size, but it never hurts to be extra careful.
If you are using the file size to allocate memory, be sure to divide it evenly for the structures. If filesize returns 100 but there are only 10 structures of 10 bytes and you allocate an array of 100 you've wasted a lot of space.
-PreludeCode:array = malloc ( filesize / sizeof ( struct something ) );