#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
ssize_t readline(int fd, char *buf, ssize_t maxlen)
{
ssize_t count = 0;
memset(buf, '\0', sizeof(buf));
char *ptr = buf;
char tmp = 0;
while(1){
read(fd, &tmp, sizeof(char));
if(tmp == '\n' || tmp == '\0') break;
(*ptr) = tmp;
ptr ++;
count ++;
if(count >= maxlen){
printf("Out of bufffer!\n");
return -1;
}
}
return count;
}
ssize_t read_last_line(int fd, char *buf, ssize_t maxlen){
if( lseek(fd, 0, SEEK_END) == 0 ) {
printf("空文件\n");
return -1;
}
lseek(fd, -1, SEEK_CUR);
char tmp = '\0';
while(lseek(fd, -1, SEEK_CUR) > 0){
read(fd, &tmp, sizeof(char));
if(tmp == '\n') break;
else lseek(fd, -1, SEEK_CUR);
}
ssize_t offset;
while((offset = readline(fd, buf, maxlen)) != -1){
if(offset > 0) return offset;
else if( offset == 0 ){
lseek(fd, -2, SEEK_CUR);
tmp = '\0';
while(lseek(fd, -1, SEEK_CUR) > 0){
read(fd, &tmp, sizeof(char));
if(tmp == '\n') break;
else lseek(fd, -1, SEEK_CUR);
}
continue;
}
}
return -1;
}
int main(){
int fd = -1;
fd = open("t.txt", O_RDONLY);
if( fd == -1 ){
printf("failed~!\n");
}
char readbuf[1024] = {0};
read_last_line(fd, readbuf, sizeof(readbuf));
printf("最后一行:%s\n",readbuf);
close(fd);
return 0;
}
|