C/C++从文件末尾往前一行一行的读

<span style="font-size:14px;color:#006600;">
int read_tail_line(FILE *fd,char *buf){  //从后往前一行一行的读取
        int c,ret;
        long offset;
		if(ftell(fd)==0){
			return -1;
		}
        while(1){
                c=fgetc(fd);
                if(c=='\n'){
                        offset=ftell(fd);
			if(buf){
				fgets(buf,LINE_BUF_SIZE,fd);
			}
                        fseek(fd,offset-2,SEEK_SET);
                        ret=1;
                        break;
                }else if(fseek(fd,-2,SEEK_CUR)==-1){
                        fseek(fd,0,SEEK_SET);
                        if(buf){
				fgets(buf,LINE_BUF_SIZE,fd);
			}
		<span style="white-space:pre">	</span>fseek(fd,0,SEEK_SET);
                        ret=0;
                        break;
                }
        }
        return ret;
}

int read_tail(int index,int num){ //从文件末尾第index行开始,向上读取num行
		
		int ret=0;
		FILE*fd;
		int i=0;
		char buf[512]={0};
		fd=fopen(LOG_FILE,"rb"); //open file 
        fseek(fd,-1,SEEK_END);
		i=index;
		while(i){
			readline(fd,NULL);
			i--;
		}
		i=num;
		while(i){
			memset(buf,0,LINE_BUF_SIZE);
			ret=readline(fd,buf);
			printf("%s",buf);
			i--;
			if(!ret)
			    break;
		}
		printf("retcode:%d\n",num-i);
		fclose(fd);
		return 0;
}
</span>


你可能感兴趣的:(C/C++从文件末尾往前一行一行的读)