#include "tlpi_hdr.h" #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <stdbool.h> #include <getopt.h>
#define BUFFSIZE 4096 char buf[BUFFSIZE] = {0}; int cntline = 0; int showline = 10; bool over = false;
int serchline(int fd, int pos) { while (pos > BUFFSIZE) { pos = lseek(fd, -BUFFSIZE, SEEK_END); read(fd, buf, BUFFSIZE); for (int i = (BUFFSIZE - 1); i > 0; i--) { if (buf[i] == '\n') { cntline++; } if (cntline > showline) { pos += i; over = true; return pos; } } memset(buf,0,BUFFSIZE); } lseek(fd, 0, SEEK_SET); read(fd, buf, pos); for (int i = pos; i > 0; i--) { if (buf[i] == '\n') { cntline++; } if (cntline > showline) { pos = i; over = true; return pos; } } memset(buf,0,BUFFSIZE); return -1; }
int main(int argc, char *argv[]) { int fd = -1; char ch; int postion = -1; int readsize=0; if (argc == 1) { usageErr("[ -n num ] filename \n to printf last num line of file\n"); } while ((ch = getopt(argc, argv, "n:num")) != -1) { switch (ch) { case 'n': showline = atoi(optarg); break; default: usageErr("[ -n num ] filename \n to printf last num line of file\n"); break; } } if (showline > 0) { if ((fd = open(argv[optind], O_RDONLY)) == -1) { errExit("open"); }
if ((postion = lseek(fd, 0, SEEK_END)) == -1) { errExit("lseek"); } postion = serchline(fd, postion); if (postion != -1) lseek(fd, postion, SEEK_SET); do { readsize=read(fd, buf, BUFFSIZE); printf("%s",buf); memset(buf,0,BUFFSIZE); } while(readsize > BUFFSIZE); } else { usageErr("[ -n num ] filename \n to printf last num line of file\n"); } return 0; }
|