[NEWBIE] [CODE] file_length()

From: Jarratt Davis (Jarratt.Davis@camtech.com.au)
Date: 05/11/00


Hi there,
Here is a little function you may or may not find useful.
It finds the size of the file on the given file stream and returns its size
in bytes.  Many thanks to George for reminding me about the existence of
fstat().  Now the reason why Im supplying this is that fstat() generally
only supplies the file size when you are using open() (which has an int
file handle) as opposed to fopen() (which uses file streams).  Will work
under MSVC 5, and FreeBSD, so should work under most other OS's too but you
have to throw in #include <sys/types.h> and #include <sys/stat.h> (You
should probably already have #include stdio.h>) at the head of your file.
MSVC 5 has a function called _filelength(int handle) which looks like it
pretty much just returns fstat() and works with open() only.
The only reason why Im going to such lengths is Im trying to stick to ANSI
C mostly so that my MUD will (hopefully) compile on most System 5 based
UN*Xs, BSD UN*Xs and Win9x - so thats why I seem a little pedantic here :)
Not really drop in code as Im not using mudlog(), and it could use some
cleaning up - more like reference.

int file_length(FILE *fp)
{
  struct stat sb;
  int err;
  int filesize;

  /* Note: _file is part of the structure of FILE in stdio.h
     It lists the filenumber associated with the opened file.
     This is needed as fstat wont accept a filestream as its
     first argument (at least not under MSVC5) - it has to be a file
     handle usually seen when using open(), while filestreams are
     usually related to fopen().
   */
  err = fstat(fp->_file, &sb);
  if (err < 0 || sb.st_size <= 0)
  {
          printf("Bad file handle.\n");
      return -1;
  } else {
    filesize = sb.st_size;
  }

  return filesize;
}

Sorry about the length of this email for such a little function :P

Cya

Jarratt


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     |  http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html  |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 04/10/01 PDT