Code:
#include <stdio.h>
#include <string.h>
#include <time.h>
time_t string_to_time_t(char *s)
{
time_t rawtime;
struct tm * timeinfo;
char month_s[4] ;
int month,day,hour,minute,second;
sscanf(s, "%3s %d %d:%d:%d", month_s, &day, &hour, &minute, &second);
char * month_names[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
int i=0;
while( strcmp(month_s,month_names[i]) != 0 )
i++;
month=i;
time (&rawtime);
timeinfo=localtime(&rawtime);
timeinfo->tm_mon=month;
timeinfo->tm_mday=day;
timeinfo->tm_hour=hour;
timeinfo->tm_min=minute;
timeinfo->tm_sec=second;
return mktime(timeinfo);
}
time_t get_date(FILE *fp)
{
char s[16];
return string_to_time_t(fgets(s,16,fp));
}
int goto_nextline(FILE *fp)
{
int c; //EOF is a int
do c=fgetc(fp) ;
while ((c != '\n') && (c !=EOF));
if (c=='\n')
return 0;
else
return 1;
}
void goto_beginning_of_line(FILE *fp)
{
int c;
if (ftell(fp) !=0)
{
fseek(fp,1,SEEK_CUR);
do
{
fseek(fp,-2,SEEK_CUR);
c=fgetc(fp);
}
while ( ftell(fp)-2>=0 && c != '\n' );
if( ftell(fp)==1 )
fseek(fp,-1,SEEK_CUR);
}
}
int search_date(FILE *fp, time_t time)
{
FILE *fpmin, *fpmax, *fptmp;
time_t timemin, timemax;
fpos_t pos;
fpmin=fpmax=fptmp=fp;
fseek(fpmin,0,SEEK_SET);
fseek(fpmax,0,SEEK_END);
fseek(fptmp,0,SEEK_SET);
timemin=get_date(fpmin);
goto_beginning_of_line(fpmax);
timemax=get_date(fpmax);
fgetpos(fpmin,&pos);
while(goto_nextline(fpmin)==0 && get_date(fpmin)<time)
{
fsetpos(fpmin,&pos);
fsetpos(fptmp,&pos);
float weight=(float)(time-timemin)/(float)(timemax-timemin);
long difference=ftell(fpmax)-ftell(fpmin);
fseek(fptmp,(long) weight * difference,SEEK_CUR);
goto_beginning_of_line(fptmp);
if (time < get_date(fptmp))
{
fpmax=fptmp;
timemax=get_date(fpmax);
}
else
{
fpmin=fptmp;
timemin=get_date(fpmin);
fgetpos(fpmin,&pos);
}
}
fp=fpmin;
return 0;
}
int main(int argc, char **argv)
{
FILE *fp=fopen("log.txt","r");
if (fp==NULL)
fprintf(stderr,"File can't be opened\n");
else
{
time_t time=string_to_time_t("Dec 11 12:00:00");
search_date(fp,time);
//do some things here
}
fclose(fp);
return 0;
}
This program doesn't work (segmentation fault).