/* * CutLog * * Keeps the last nn lines of a text file. * * Syntax: cutlog * * Note: this program is slow * * A public domain program that may be distributed, sold, * etc without restrictions. You can use this source in * your own programs without credits. Use it at your own risk. * * FA 16/01/92 */ #include #include #include #define TEMPLEN 255 #define SEPAR '\\' int main(int argc, char **argv) { int nl,max,start; char *ptr; char tempnm[FILENAME_MAX], temp[TEMPLEN]; FILE *fl,*dl; if(argc!=3) { printf("usage: cutlog \n" " : number of lines to keep\n" " : file name\n\n"); return 0; } nl=atoi(argv[1]); max=0; /* first run, count the lines */ fl=fopen(argv[2],"r"); if(!fl) { fprintf(stderr, "cutlog: can't open %s\n.",argv[2]); return 1; } while(fgets(temp,TEMPLEN,fl)) max++; fclose(fl); start=max-nl; if(start>0) { /* find a temp name */ strcpy(tempnm,argv[2]); ptr=strrchr(tempnm,SEPAR); if(ptr) strcpy(ptr+1,"cutlog.tmp"); else strcpy(tempnm,"cutlog.tmp"); if(rename(argv[2],tempnm)) { fprintf(stderr,"cutlog: can't rename %s to %s.\n",argv[2],tempnm); return 1; } /* second run, copy */ fl=fopen(tempnm,"r"); if(!fl) fprintf(stderr, "cutlog: can't open %s.\n",tempnm); else { dl=fopen(argv[2],"w"); if(!dl) fprintf(stderr, "cutlog: can't open %s.\n",argv[2]); else { max=0; while(fgets(temp,TEMPLEN,fl)) { max++; if(max>start) { if(fputs(temp,dl)<0) fprintf(stderr,"can't write %s.\n",argv[2]); } } fclose(dl); } fclose(fl); } remove(tempnm); } else printf("%s is not too long.\n",argv[2]); return 0; }