From 9a5359bcc8d47de7222d07035ae99459d49e810e Mon Sep 17 00:00:00 2001 From: JSDurand Date: Tue, 18 Jul 2023 11:49:43 +0800 Subject: test.c: Save the forest to a file. This is not of much use right now, but can be helpful later. --- src/test.c | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 68 insertions(+), 4 deletions(-) diff --git a/src/test.c b/src/test.c index 5ec2d58..5a5118d 100644 --- a/src/test.c +++ b/src/test.c @@ -57,7 +57,7 @@ main(int argc, char **argv) } unsigned char *input = malloc (sizeof(unsigned char) * 10 * 8); - + if (input == NULL) { clean_parser(parser); clean_signed(&error_vec, 4); @@ -68,11 +68,11 @@ main(int argc, char **argv) int input_unenc[10] = { 3, 0, 2, 2, 2, 1, 1, 1, 0, 1 }; - for (int i = 0; i < 10; i++) + for (int i = 0; i < 10; i++) to_big_endian(input_unenc[i], input + (8 * i)); unsigned char input_len[8] = { 0 }; - input_len[7] = 8*2; + input_len[7] = 8*6; struct UnsignedVec input_vec = (struct UnsignedVec) { input_len, NULL, input }; @@ -82,7 +82,7 @@ main(int argc, char **argv) &input_vec, &error_vec, (unsigned char) 0); - + error_length = from_big_endian(error_vec.len); if (error_length) { @@ -242,6 +242,70 @@ main(int argc, char **argv) printf("the forest has the correct length according to the format\n"); + printf("saving to the file \"forest.rep\"\n"); + + char *open_mode = "a"; + + if (fopen("forest.rep", "r") != NULL) { + printf("The file \"forest.rep\" already exists.\n" + "Do you want to overwrite it? [y/n] "); + + fflush(stdout); + + #define UNANSWERED 0 + #define YES 1 + #define NO 2 + + int yes = UNANSWERED; + + while (yes == UNANSWERED) { + char input = getchar(); + + switch (input) { + case 'y': + yes = YES; + break; + case 'n': + yes = NO; + break; + default: + printf("Please answer 'y' or 'n'.\n"); + yes = UNANSWERED; + break; + } + } + + if (yes == NO) { + printf("Exiting without saving...\n"); + + clean_unsigned(forest_ptr, 15); + + return 0; + } + + open_mode = "w"; + + #undef UNANSWERED + #undef YES + #undef NO + } + + FILE *forest_file = fopen("forest.rep", open_mode); + + if (forest_file == NULL) { + fprintf(stderr, "Cannot open file \"forest.rep\" to write\n"); + + clean_unsigned(forest_ptr, 15); + + return 1; + } + + fwrite(forest, 1, forest_len, forest_file); + + fclose(forest_file); + + printf("Successfully saved the forest to the file \"forest.rep\"\n"); + clean_unsigned(forest_ptr, 15); } else { printf("no forest\n"); -- cgit v1.2.3-18-g5258