From b20733f3acc6a939cd83af59223cddda2b57cf88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20A=2E=20Ortega?= Date: Mon, 13 Feb 2017 09:47:47 +0100 Subject: [PATCH] Append new primes to the end of a file. --- src/files.c | 6 +++--- src/files.h | 4 +++- src/main.c | 5 ++++- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/files.c b/src/files.c index d101830..45be0e6 100644 --- a/src/files.c +++ b/src/files.c @@ -21,17 +21,17 @@ int inputPrimes(char *file, List *list) { return 0; } -int outputPrimes(char *file, List *list) { +int outputPrimes(char *file, List *list, size_t startPos) { // Assert safeguards assert(file); assert(list); - FILE *out = fopen(file, "w"); + FILE *out = fopen(file, "a"); if(!out) return 1; printf("Saving primes to `%s'...\n", file); puts("0%"); - for(size_t i = 0; i < list->end; ++i) { + for(size_t i = startPos; i < list->end; ++i) { if(!mpz_out_raw(out, list->list[i])) return 3; if(i == list->end / 4) puts("25%"); else if(i == list->end / 2) puts("50%"); diff --git a/src/files.h b/src/files.h index 68b081c..822063a 100644 --- a/src/files.h +++ b/src/files.h @@ -21,10 +21,12 @@ int inputPrimes(char *file, List *list); * @brief Output primes from a List into an Indivisible file. * @param file File to output primes to. * @param list List to read primes from. + * @param startPos The position in the List of primes at which to append + * to the file. * @returns If 0 then load was successful, if 1 then failed to open, * if 2 failed to close, if 3 failed when writing. */ -int outputPrimes(char *file, List *list); +int outputPrimes(char *file, List *list, size_t startPos); /** * @brief Export primes from a List to a plain text file. diff --git a/src/main.c b/src/main.c index c5dd96b..65e0a1f 100644 --- a/src/main.c +++ b/src/main.c @@ -128,6 +128,8 @@ int main(int argc, char *argv[]) { struct stat s; if(stat(dfile, &s) == 0) newFile = false; } + // Last position added from file + size_t startPos = 0; int exitCode = 0; @@ -169,6 +171,7 @@ int main(int argc, char *argv[]) { } else { // Load primes from file int err = inputPrimes(dfile, &primes); + startPos = primes.end; if(err == 0) { printf("Loaded %zu primes.\n", primes.end); @@ -244,7 +247,7 @@ int main(int argc, char *argv[]) { printf("Found %zu primes.\n", primes.end); if(dfile) { - int err = outputPrimes(dfile, &primes); + int err = outputPrimes(dfile, &primes, startPos); if(err == 0) { puts("Successfully saved primes."); } else {