home *** CD-ROM | disk | FTP | other *** search
- /*
- * TRIMFILE file1 file2 .. filen -lines
- *
- * (C) Copyright 1989-1990 by Matthew Dillon, All Rights Reserved.
- *
- * Trims the specified files to the specified number of lines. Each
- * file is read and the last N lines written back.
- *
- * Normally used to trim log files based on a crontab entry. If no
- * -lines argument is given the file is trimmed to 100 lines.
- *
- * Each line may be up to 255 characters in length.
- */
-
- #include <ctype.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include "version.h"
- #include "config.h"
- #include <owndevunit.h>
-
- IDENT (".02");
-
- #define LINSIZE 256
-
- char
- **LineBuf = NULL;
- long
- Lines = 100;
- struct Library
- *OwnDevUnitBase = NULL;
- static const char
- LockLib [] = { ODU_NAME },
- LockName [] = { "LOG-UPDATE" };
-
- Local void myexit (void);
- Local void MemErr (void);
- Local void TrimFile (const char *);
-
- int
- main (int ac, char **av)
- {
- int
- lineset = 0,
- i;
-
- atexit (myexit);
- if ((OwnDevUnitBase = OpenLibrary ((UBYTE *) LockLib, 0)) == NULL) {
- fprintf (stderr, "Couldn't open %s\n", LockLib);
- exit (30);
- }
-
- for (i = 1; i < ac; ++i) {
- if (av [i] [0] == '-') {
- if (lineset) {
- fprintf (stderr, "Can't set linesize more than once\n");
- exit (30);
- }
- if (!isdigit (av [i] [1])) {
- fprintf (stderr, "Linesize must be an integer\n");
- exit (30);
- }
- lineset = 1;
- Lines = atol (av [i] + 1);
- }
- }
-
- /*
- * Allocating one more than necessary handles the Lines == 0 case
- * as well as supplying a scratch buffer for the last fgets that
- * fails.
- */
-
- LineBuf = malloc (sizeof (char *) * (Lines + 1));
- if (LineBuf == NULL)
- MemErr ();
-
- for (i = 0; i <= Lines; ++i) {
- LineBuf [i] = malloc (LINSIZE);
- if (LineBuf [i] == NULL)
- MemErr ();
- }
-
- for (i = 1; i < ac; ++i) {
- char
- *ptr = av [i];
-
- if (*ptr == '-')
- continue;
-
- LockFile (LockName);
- TrimFile (ptr);
- UnLockFile (LockName);
- }
-
- exit (0);
- }
-
- void
- myexit (void)
- {
- UnLockFiles ();
-
- if (OwnDevUnitBase) {
- CloseLibrary (OwnDevUnitBase);
- OwnDevUnitBase = NULL;
- }
-
- return;
- }
-
- void
- MemErr (void)
- {
- fprintf (stderr, "Not enough memory!\n");
- exit (30);
- }
-
- void
- TrimFile (const char *name)
- {
- FILE
- *fi = fopen (name, "r");
- long
- rep,
- i;
-
- if (fi == NULL)
- return;
-
- i = 0;
- rep = 0;
- while (fgets (LineBuf [i], LINSIZE, fi)) {
- if (++i > Lines) {
- i = 0;
- rep = 1;
- }
- }
- fclose (fi);
-
- if (rep == 0)
- return;
-
- if (fi = fopen (name, "w")) {
- long
- j;
-
- for (j = Lines; j; --j) {
- if (++i > Lines)
- i = 0;
- fputs (LineBuf [i], fi);
- }
- fclose (fi);
- }
-
- return;
- }
-