A
Andrew Clark
Hello all,
I recall several threads over the years about how reading file size
cannot be done consistantly or portably, but I don't remember any good
reasons (not that I haven't read them, I'm sure, but it's more of a
failure to hold them in my brain). Here is an attempt that I was
commissioned to write, and I'd appreciate any comments and/or criticism
(specific or general) before I release it to my customer. Thanks!
Andrew
/* begin filesize.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main ( int argc, char *argv [] )
{
int status;
if ( 2 != argc )
{
fprintf ( stderr, "Usage: %s <filename>\n", argv [ 0 ] );
status = EXIT_FAILURE;
}
else
{
FILE *fp;
fp = fopen ( argv [ 1 ], "rb" );
if ( !fp )
{
fprintf ( stderr, "Cannot open file \"%s\" for reading.
[Error %d]\n", argv [ 1 ], errno );
status = EXIT_FAILURE;
}
else
{
char c;
long unsigned size = 0;
while ( fread ( &c, sizeof c, 1, fp ) )
{
size++;
}
fclose ( fp );
printf ( "Size of file (in bytes): %lu\n", size );
#if 0
if ( size > 1 << 10 )
{
/*** 1 KB ***/
printf ( "[%lu KB]\n", size / ( 1 << 10 ) );
}
#endif
status = EXIT_SUCCESS;
}
}
#if 0
printf ( "Returning status code: %d\n", status );
#endif
return status;
}
/* end filesize.c */
I recall several threads over the years about how reading file size
cannot be done consistantly or portably, but I don't remember any good
reasons (not that I haven't read them, I'm sure, but it's more of a
failure to hold them in my brain). Here is an attempt that I was
commissioned to write, and I'd appreciate any comments and/or criticism
(specific or general) before I release it to my customer. Thanks!
Andrew
/* begin filesize.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main ( int argc, char *argv [] )
{
int status;
if ( 2 != argc )
{
fprintf ( stderr, "Usage: %s <filename>\n", argv [ 0 ] );
status = EXIT_FAILURE;
}
else
{
FILE *fp;
fp = fopen ( argv [ 1 ], "rb" );
if ( !fp )
{
fprintf ( stderr, "Cannot open file \"%s\" for reading.
[Error %d]\n", argv [ 1 ], errno );
status = EXIT_FAILURE;
}
else
{
char c;
long unsigned size = 0;
while ( fread ( &c, sizeof c, 1, fp ) )
{
size++;
}
fclose ( fp );
printf ( "Size of file (in bytes): %lu\n", size );
#if 0
if ( size > 1 << 10 )
{
/*** 1 KB ***/
printf ( "[%lu KB]\n", size / ( 1 << 10 ) );
}
#endif
status = EXIT_SUCCESS;
}
}
#if 0
printf ( "Returning status code: %d\n", status );
#endif
return status;
}
/* end filesize.c */