C/C++ code#include
#include
#include
#include
#include
void tail(int fd, int nline);
int main(int argc, char *argv[])
{
int line;
char *fname;
int fd;
if (argc != 3) {
fprintf(stderr, "Usage: a.out line file\n");
exit(1);
}
line = atoi(argv[1]);
fname = argv[2];
if ((fd = open(fname, O_RDONLY)) == 0) {
perror(NULL);
exit(1);
}
tail(fd, line);
close(fd);
return 0;
}
void tail(int fd, int nline)
{
char buf[100] = { 0 };
long n = 0;
nline++;
while (lseek(fd, n, SEEK_END) && nline) {
read(fd, buf, 1);
if (!strcmp(buf, "\n"))
nline--;
n--;
}
n += 2; /*read postion is before "\n", add 2 to skip to the next line's start */
lseek(fd, n, SEEK_END);
while (read(fd, buf, 1))
write(1, buf, 1);
}