Q: HOW DO I... determine a file's size by using only ANSI functions?
A: Determining the size of a file is a function that is specific to each computer environment and, as such, wasn't addressed directly in the ANSI C standard. It is, however, possible to write such a function using only the tools ANSI has provided. C Snippet #1 shows how.
/*
** 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 */
More C Snippets
- Determining a file's size
- Rounding floating-point values
- Sorting an array of strings
- Computing the wind chill factor
- Timers and default actions
- Copying overlapping strings
- Really random numbers
All the code in C Snippets is either public domain or freeware and may therefore freely be used by the C programming community without restrictions. In most cases, if the original author is someone other than myself he or she will be identified. Thanks to all who have contributed to this collection over the years. I hope Dr. Dobb's readers will find these useful.
— Bob Stout
rbs@snippets.org


