#include #include #include #include #include #include #include "lock.h" /* Subroutines for managing the hitcount list */ /* We keep track of the hitcount in a file names hitcount */ char *hitfile = "hitcount"; /* The format of the countfile is this: 1 line of ascii text for each day recorded. each line contains the date as 3 integers mm dd yyyy followed by 24 integers, one for each hour (the number of hits for each hour). there are spaces seperating each of these values. Here is an example: 4 16 1998 0 30 10101 22 28 0 0 0 0 0 0 0 0 1 3 4 7 8 9 6 5 2 3 4 on 4/16/1998 there were 30 hits between 1 and 2 AM, 10,101 between 2 and 3 AM, and so on... */ typedef struct hitrec { int mon,day,year; int hours[24]; } hitrec; #define MAXDAYS 1000 /* maximum number of days we keep track of */ typedef hitrec hitlist[MAXDAYS]; /* parse_countline parses a single line of text and fills in a hitrec; Return value is 1 if successful, 0 if not. NOTE: the line is corrupted, strtok is used! */ int parse_countline( char *s, hitrec *h) { int i; char *ptr; if (! (ptr = strtok(s," "))) return(0); h->mon = atoi(ptr); if (! (ptr = strtok(NULL," "))) return(0); h->day = atoi(ptr); if (! (ptr = strtok(NULL," "))) return(0); h->year = atoi(ptr) ; i=0; while ((i<24)&&(ptr)) { if (! (ptr = strtok(NULL," "))) return(0); h->hours[i] = atoi(ptr); i++; } printf("GOT DATE AS %d %d %d\n",h->mon, h->day, h->year); /* as long as i is 24 - we got a good line */ /* (we assume any date is OK) */ if (i!=24) return(0); printf("Valid Stuff\n"); return(1); } hitlist hl; int n_days; #define MAXLINE 1000 /* reads the hit count file and returns 1 on success, 0 on error */ /* fills in the array hl with the records from the file */ int read_countfile( FILE *f) { char aline[MAXLINE]; n_days=0; while (fgets(aline,MAXLINE,f)) { if (!parse_countline(aline,&hl[n_days])) { return(0); } n_days++; } return(1); } /* writes the count file and returns 1 on success, 0 on error */ void write_countfile( FILE *f) { int i,j; printf("Writing the countfile - ndays is %d\n",n_days); for (i=0;i=EHIT_MAX)) hiterror=0; return(hiterrors[hiterror]); } int hit_me() { FILE *f; struct tm *timerec; time_t t; /* get the current time and date */ t = time(NULL); timerec = localtime( &t ); /* now we need to update the hitfile */ /* if file doesn't exist - create it */ if ((f = fopen(hitfile,"r+"))==NULL) { if ((f=fopen(hitfile,"w+"))==NULL) { hiterror = EHIT_HITFILE; return(0); } } /* lock the count file so nobody else is mucking with it */ if (lock_fd(fileno(f))!=0) { hiterror = EHIT_LOCK; return(0); } /* now read the countfile */ if (!read_countfile(f)) { hiterror = EHIT_HITFILE; return(0); } /* update the hit records to include our hit */ update_hits(timerec->tm_mon+1, timerec->tm_mday, timerec->tm_year+1900, timerec->tm_hour); /* and write the update to disk */ rewind(f); write_countfile(f); /* release the file */ if (!unlock_fd(fileno(f))) { hiterror = EHIT_HITFILE; return(0); } fclose(f); /* everything is OK */ return(1); }