求优化文件已行为单位反向输出程序
如题:下面算法是每次都从文件尾开始算,想优化为每次在输出的行的下行为起点。谢谢!
若文件太大现在程序效率太低了,意思是找第二行b时,以c行为起点;找第一行a时,以b行为起点
现在结果:
> ./reverse_1 a.txt
cccccccccc
bbbbbbbbbb
aaaaaaaaaa
a.txt内容
> cat a.txt
aaaaaaaaaa
bbbbbbbbbb
cccccccccc
程序内容:
cat reverse_1.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[]) {
int ret;
FILE *fp;
int c;
int begin,end=-1;
char readbuf[1024];
fp=fopen(argv[1],"r");
while((begin=fseek(fp,end,SEEK_END))==0) {
if((ret=ftell(fp))==0 || (c=fgetc(fp))=='\n') {
memset(readbuf,0,sizeof(readbuf));
fgets(readbuf,1024,fp);
printf("%s",readbuf);
}
end--;
}
fclose(fp);
exit(0);
}
/**
* @file rcat.c
* @brief
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp;
long *pos;
int num, siz;
char buf[1024];
if (argc != 2)
exit(1);
fp = fopen(argv[1], "r");
if (fp == NULL){
perror(argv[1]);
exit(2);
}
num = 0;
siz = 1024;
pos = (long *)malloc(sizeof(long) * siz);
pos[0] = 0;
while (fgets(buf, sizeof(buf), fp)) {
if (++num == siz) {
siz *= 2;
pos = (long *)realloc(pos, sizeof(long) * siz);
}
pos[num] = ftell(fp);
}
while (num--) {
fseek(fp, pos[num], SEEK_SET);
fgets(buf, sizeof(buf), fp);
printf("%s", buf);
}
fclose(fp);
return 0;
}