kid joe said:
Hi all,
What do people think of this snippet on Dr Dobbs today?
<URL:
http://www.ddj.com/cpp/219100141>
Here's the code:
==================================================
/*
** FLENGTH.C - a simple function using all ANSI-standard functions
** to determine the size of a file.
**
** Public domain by Bob Jarvis.
*/
#include <stdio.h>
#include <io.h>
long flength(char *fname)
{
FILE *fptr;
long length = 0L;
fptr = fopen(fname, "rb");
if(fptr != NULL)
{
fseek(fptr, 0L, SEEK_END);
length = ftell(fptr);
fclose(fptr);
}
return length;
}
#ifdef TEST
void main(int argc, char *argv[])
{
printf("Length of %s = %ld\n", argv[0], flength(argv[0]));
}
#endif /* TEST */
==================================================
I see these problems:
1) no error checking of fseek, ftell or fclose - could be problems if the
file is "special" in some way or if I/O errors occur
If fseek fails but ftell succeeds, ftell will probably return 0.
If ftell fails, it returns -1.
If fopen fails, flength returns 0.
This all might be reasonable if it were documented, but I think the
author just assumed nothing would go wrong (other than failing to open
the file).
2) main should return int not void
Absolutely.
3) using argv[1] instead of argv[0] would make more sense, but then need
to check argc>0
I think the intent is that, in test mode, the program reports the size
of its own executable. Using argv[1] would certainly enable more
thorough testing. (Or maybe the author forgot what argv[0] means.)
Also this program makes me wonder why ftell returns long and not size_t.
size_t is for the size of an object, not of a file. A system could
support files bigger than either SIZE_MAX or LONG_MAX bytes; for
example, 32-bit systems often support files bigger than 4 gigabytes.
fsetpos and fgetpos allow for files whose sizes can't be represented
as integers, by using an opaque type, fpos_t, that can represent any
position in a file. When they were invented (1989 or earlier(?)),
there was no requirement for integers wider than 32 bits, so there was
a real possibility of files whose size couldn't be represeented in
*any* integer type. If this were being invented today, we'd probably
just use 64-bit integers.
One thing you missed: there's no <io.h> header in standard C.