home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 8 / FreshFishVol8-CD1.bin / new / comm / bbs / eazybbs / source / trimfile.c < prev    next >
C/C++ Source or Header  |  1994-03-12  |  2KB  |  82 lines

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. main (int argc, char *argv[])
  6. {
  7.     FILE *fp;
  8.     char *p;
  9.     char *x;
  10.     long size;
  11.     long lines;
  12.     long maxlines = 200L;
  13.     int arg = 1;
  14.  
  15.     if (sizeof (int) < 4) {
  16.         fprintf (stderr, "sorry, program needs at least 4-byte-integers\n");
  17.         exit (20);
  18.     }
  19.  
  20.     if (argc < 2) {
  21.         fprintf (stderr, "usage: trimfile [-l <maxlines>] <filename> ...\n");
  22.         exit (5);
  23.     }
  24.  
  25.     if (!strcmp (argv[1], "-l") && argc > 3) {
  26.         maxlines = atol (argv[2]);
  27.         arg += 2;
  28.     }
  29.  
  30.     for (; arg < argc; arg++) {
  31.         if (!(fp = fopen (argv[arg], "r"))) {
  32.             fprintf (stderr, "trimfile: cannot open file %s for reading\n", argv[arg]);
  33.             continue;
  34.         }
  35.  
  36.         fseek (fp, 0L, 2);
  37.         if (size = ftell (fp)) {
  38.             if (!(p = malloc (size))) {
  39.                 fprintf (stderr, "trimfile: cannot allocate %ld bytes for %s\n", size, argv[arg]);
  40.                 fclose (fp);
  41.                 continue;
  42.             }
  43.  
  44.             rewind (fp);
  45.             if (fread (p, 1, size, fp) != size) {
  46.                 fprintf (stderr, "trimfile: cannot read %ld bytes from %s\n", size, argv[arg]);
  47.                 free (p);
  48.                 fclose (fp);
  49.                 continue;
  50.             }
  51.             fclose (fp);
  52.  
  53.             for (lines = 0L, x = p + size - 1; x >= p && lines <= maxlines; x--) {
  54.                 if (*x == '\n')
  55.                     lines++;
  56.             }
  57.             x++;
  58.  
  59.             if (*x == '\n' && x != p)
  60.                 x++;
  61.  
  62.             if (!(fp = fopen (argv[arg], "w"))) {
  63.                 fprintf (stderr, "trimfile: cannot open file %s for writing\n", argv[arg]);
  64.                 free (p);
  65.                 continue;
  66.             }
  67.  
  68.             if (fwrite (x, 1, p + size - x, fp) != p + size - x) {
  69.                 fprintf (stderr, "trimfile: cannot read %ld bytes from %s\n", size, argv[arg]);
  70.                 free (p);
  71.                 fclose (fp);
  72.                 continue;
  73.             }
  74.  
  75.             fclose (fp);
  76.             free (p);
  77.         }
  78.         else
  79.             fclose (fp);
  80.     }
  81. }
  82.