tail 명령 구현
1295 단어 c 기초
cat t1.c
#include
#include
#include
#include
#include
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
",begin);
if(read(fd,&c,1)!=1) {
perror("tail");
exit(-1);
}
if(c=='
') line++;
end--;
printf("end=%d
",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
",argv[0]);
exit(-1);
}
lines=atoi(argv[1]);
fd=open(argv[2],O_RDONLY);
if(fd==-1) {
fprintf(stderr,"open() error.
");
exit(-1);
}
mytail(fd,lines);
close(fd);
exit(-1);
}