tail命令实现

使用方法:t1 行数 文件名

cat t1.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void mytail(int fd,int lines) {
        char c;
        int line;

        off_t end,begin;

        line=0;
        end=-1;

        while(line<=lines && (begin=lseek(fd,end,SEEK_END))>=0) {
                printf("begin=%d\n",begin);

                if(read(fd,&c,1)!=1) {
                        perror("tail");
                        exit(-1);
                }

                if(c=='\n') line++;

                end--;
                printf("end=%d\n",end);
        }

//      if(begin<0)
//              lseek(fd,0L,0);

        while(read(fd,&c,1)==1)
                putchar(c);
}

int main(int argc,char *argv[]) {
        int fd,lines;

        if(argc!=3) {
                fprintf(stderr,"input: %s n filename\n",argv[0]);
                exit(-1);
        }

        lines=atoi(argv[1]);

        fd=open(argv[2],O_RDONLY);
        if(fd==-1) {
                fprintf(stderr,"open() error.\n");
                exit(-1);
        }

        mytail(fd,lines);

        close(fd);

        exit(-1);
}


版权声明:本文为ccjsj1原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。