tail命令实现

来源:互联网 发布:ppt模版打开软件 编辑:程序博客网 时间:2024/04/29 17:10

使用方法: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);}

原创粉丝点击