#include #include #include #include #include #include #define MAXLINESIZE 1024 /* Print lines of a file in reverse order. Adapted from Rochkind, Advanced Unix Programming, p. 109 */ int main(int argc, char * argv[]) { char c, line[MAXLINESIZE]; int i, fd; off_t file_size, loc; if (argc !=2) { fprintf(stderr, "Usage: %s file\n", argv[0]); exit(1); } fd = open(argv[1], O_RDONLY); if (fd == -1) { perror(argv[0]); exit(1); } file_size = lseek(fd, 0L, SEEK_END); if (file_size == -1) { perror(argv[0]); exit(1); } i = sizeof(line) - 1; line[i] = '\0'; for (loc = file_size-1; loc >= 0; --loc) switch (pread(fd, &c, 1, loc)) { case 1: if (c == '\n') { printf("%s", &line[i]); i = sizeof(line) - 1; } if (i <= 0 ) { fprintf(stderr, "%s: line too big\n", argv[0]); exit(E2BIG); } line[--i] = c; break; case -1: perror(argv[0]); exit(1); break; default: /* will never happen */ exit(1); } printf("%s", &line[i]); /* one more line to do */ if (close(fd) == -1) { perror("argv[0]"); exit(1); } return 0; }