diff --git a/main.c b/main.c index 69dcace..77c81d0 100644 --- a/main.c +++ b/main.c @@ -206,6 +206,27 @@ char *get_file(char *dir, struct tm *t) return buffer; } +void save_activities(FILE *f, char *file_path, U32 current_activity, activity *activities) +{ + // NOTE: We want to clear file contents before the next write. + f = freopen(file_path, "w+", f); + if(f) { + char write_buffer[128]; + for(U32 i = 0; i <= current_activity; i++) { + snprintf(write_buffer, sizeof(write_buffer), "%s %llu %llu\n", activity_type_string_representation[activities[i].type], activities[i].began, activities[i].ended); + + size_t write_buffer_len = strlen(write_buffer); + if(fwrite(write_buffer, 1, write_buffer_len, f) != write_buffer_len) { + // NOTE: We do not care, probably for now, that it might have failed to write some data. + // The program will either overwrite everything again or the next launch will ignore the corrupted line. + } + } + + if(fflush(f) != 0) + perror("fflush"); + } +} + int main(int argc, char *argv[]) { activity activities[256]; // TODO: This should be a dynamic array. @@ -307,7 +328,7 @@ int main(int argc, char *argv[]) activities[current_activity].type = other; activities[current_activity].color = RED; activities[current_activity].began = now(); - activities[current_activity].ended = lower_bound_s; + activities[current_activity].ended = now(); state.font_size = 30; @@ -405,27 +426,12 @@ int main(int argc, char *argv[]) // Save the state every 5 seconds. if((now_s - last_save) >= 5) { - f = freopen(file_path, "w+", f); // NOTE: We want to clear file contents before the next write. - if(f) { - char write_buffer[128]; - for(U32 i = 0; i <= current_activity; i++) { - snprintf(write_buffer, sizeof(write_buffer), "%s %llu %llu\n", activity_type_string_representation[activities[i].type], activities[i].began, activities[i].ended); - - size_t write_buffer_len = strlen(write_buffer); - if(fwrite(write_buffer, 1, write_buffer_len, f) != write_buffer_len) { - // NOTE: We do not care, probably for now, that it might have failed to write some data. - // The program will either overwrite everything again or the next launch will ignore the corrupted line. - } - } - - if(fflush(f) != 0) - perror("fflush"); - } - + save_activities(f, file_path, current_activity, activities); last_save = now_s; } } + save_activities(f, file_path, current_activity, activities); fclose(f); CloseWindow();