FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
C++
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
August 05, 2009
C Snippet #1

Bob Stout
Determining a file's size

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

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

TOP 5 ARTICLES
No Top Articles.



MICROSITES
FEATURED TOPIC

ADDITIONAL TOPICS

INFO-LINK