#-h- tail.r 2038 asc 6-oct-80 07:46:55 #-h- defns 160 asc 6-oct-80 07:42:55 # include standard symbol definitions # include ratdef define(MAXBUF,3000) # line buffer size define(DEFAULT,23) # default if no argument #-h- tail 1027 asc 6-oct-80 07:42:57 # tail - print tail portion of a file subroutine main character arg(MAXLINE) integer n, i, fd integer ctoi, getarg, open n = DEFAULT for (i=1; getarg(i, arg, MAXLINE) != EOF; i=i+1) { if (arg(1) == QMARK & arg(2) == EOS) call error ("usage: tail [-n] [files].") else if (arg(1) == MINUS & arg(2) != EOS) { j = 2 n = ctoi(arg, j) if (n <= 0) call error ("invalid size.") } else if (arg(1) == MINUS & arg(2) == EOS) { fd = STDIN call ptail (n, fd) } else { fd = open(arg, READ) if (fd == ERR) call cant(arg) call ptail (n, fd) call close(fd) } } if (fd == ERR) #no files specified, read STDIN call ptail (n, STDIN) return end #-h- ptail 704 asc 6-oct-80 07:43:00 ## ptail - print last 'n' lines of file 'fd' subroutine ptail (nlins, fd) integer n, fd, nlins character buf(MAXBUF) character getch integer head, tail, i head = 1 tail = 1 n = nlins while (getch(buf(tail), fd) ^= EOF) { tail = mod(tail, MAXBUF) + 1 if (tail == head) head = mod(head, MAXBUF) + 1 } for (i = tail; i ^= head; ) { i = i - 1 if (i == 0) i = MAXBUF if (buf(i) == NEWLINE) { n = n - 1 if (n < 0) { i = mod(i, MAXBUF) + 1 break } } } for (head = i; head ^= tail; head = mod(head, MAXBUF) + 1) call putch(buf(head), STDOUT) return end