home *** CD-ROM | disk | FTP | other *** search
/ Monster Media 1994 #1 / monster.zip / monster / PROG_C / SNPD9404.ZIP / FSIZE.C < prev    next >
C/C++ Source or Header  |  1994-04-03  |  2KB  |  79 lines

  1. /*
  2. **  FSIZE.C - Determine apparent file size of buffered file. Returns size
  3. **            corrected for text mode character translation.
  4. **
  5. **  public domain demo by Bob Stout
  6. */
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10.  
  11. long fsize(FILE *fp)
  12. {
  13.       size_t bufsize, bytes_read;
  14.       char *bufptr;
  15.       long size = 0L, pos;
  16.  
  17.       for (bufsize = 0x8000; NULL == (bufptr = malloc(bufsize)); bufsize /= 2)
  18.             ;
  19.       if (!bufptr)
  20.             return -1L;
  21.       pos = ftell(fp);
  22.       do
  23.       {
  24.             bytes_read = fread(bufptr, sizeof(char), bufsize, fp);
  25.             size += bytes_read;
  26.       } while (bytes_read);
  27.       free(bufptr);
  28.       fseek(fp, pos, SEEK_SET);
  29.       return size;
  30. }
  31.  
  32. #ifdef TEST
  33.  
  34. #include <string.h>
  35.  
  36. #ifdef MSDOS
  37.  #define fl(x) filelength(x)
  38.  #define getsize(fp) fl(fileno(fp))
  39. #else
  40.  #define fl(x) puts("Install compiler-specific file length function here")
  41.  #define getsize(fp) fl(fp)
  42. #endif
  43.  
  44. int main(int argc, char *argv[])
  45. {
  46.       FILE *fp;
  47.       long size, csize, lsize;
  48.       char buf[256];
  49.  
  50.       while (--argc)
  51.       {
  52.             if (NULL == (fp = fopen(*++argv, "r")))
  53.                   printf("Can't open %s\n", *argv);
  54.  
  55.             size = getsize(fp);
  56.             printf("\n\"Real\" size of %s is %ld\n", *argv, size);
  57.  
  58.             for (csize = 0L; EOF != fgetc(fp); ++csize)
  59.                   ;
  60.             rewind(fp);
  61.  
  62.             for (lsize = 0L; !feof(fp); )
  63.             {
  64.                   if (NULL != fgets(buf, 256, fp))
  65.                         lsize += strlen(buf);
  66.             }
  67.             rewind(fp);
  68.  
  69.             printf("fsize() returned a size = %s is %ld\n",
  70.                   *argv, fsize(fp));
  71.             printf("Reading chars returned an apparent size of %ld\n",
  72.                   csize);
  73.             printf("Reading lines returned an apparent size of %ld\n",
  74.                   lsize);
  75.       }
  76. }
  77.  
  78. #endif
  79.