diff --git a/logger.c b/logger.c index 380250a..834ab3e 100644 --- a/logger.c +++ b/logger.c @@ -22,6 +22,7 @@ struct Logger { char old[132]; int period; time_t last; + long pos; }; static char *dir = NULL; @@ -34,6 +35,7 @@ void LoggerWrite(Logger *log, time_t now, int period, char *value) { int l; int newday; FILE *fil; + long pos; if (dir == NULL) return; if (now == 0) { @@ -44,36 +46,46 @@ void LoggerWrite(Logger *log, time_t now, int period, char *value) { tm = localtime(&now); if (tm->tm_yday != yday) { log->period = 0; - } else if (0 == strncmp(value, log->old, sizeof(log->old))) { /* value has not changed */ - return; } log->last = now; snprintf(path, sizeof path, "%s/%s/", dir, log->name); l = strlen(path); strftime(path + l, sizeof path - l, "%m-%d.log", tm); - fil = fopen(path, "a+"); - if (fil == NULL) return; - fseek(fil, 0, SEEK_SET); - fgets(buf, sizeof buf, fil); - strftime(stim, sizeof stim, "#%Y-%m-%d %H:%M:%S\n", tm); - if (0 != strncmp(buf, stim, 11)) { - fclose(fil); - fil=fopen(path, "w+"); /* overwrite old logfile */ + fil = fopen(path, "r+"); + if (fil == NULL) { /* create new file */ + fil = fopen(path, "w+"); if (fil == NULL) return; fputs(stim, fil); - } else { - fseek(fil, 0, SEEK_END); /* set position to end */ + } else { /* check if file is actual */ + fgets(buf, sizeof buf, fil); + if (0 != strncmp(buf, stim, 11)) { + fclose(fil); + fil=fopen(path, "w+"); /* overwrite old logfile */ + if (fil == NULL) return; + fputs(stim, fil); + } else { + fseek(fil, 0, SEEK_END); /* set position to end */ + } } if (period != log->period) { log->period = period; snprintf(buf, sizeof buf, "\t%d", period); + log->pos = 0; } else { buf[0]='\0'; } + if (log->pos > 0) { + fseek(fil, log->pos, SEEK_SET); + } + log->pos = ftell(fil); strftime(stim, sizeof stim,"%H:%M:%S", tm); fprintf(fil, "%s\t%s%s\n", stim, value, buf); + if (0 != strncmp(value, log->old, sizeof(log->old)) || buf[0]!='\0') { /* value has changed */ + log->pos = ftell(fil); /* next time append to the end */ + } + l = strlen(value); if (l >= sizeof(log->old)) { l = sizeof(log->old) - 1; @@ -126,6 +138,7 @@ Logger *LoggerMake(char *name, int period) { log->period = 0; log->old[0] = '\0'; log->last = 0; + log->pos = 0; LoggerWrite(log, time(NULL) - 1, period, ""); return log; }