From f01e0b9e316c2ceca8765503c652051f17c8cc05 Mon Sep 17 00:00:00 2001 From: Myles Busig Date: Wed, 30 Oct 2024 00:34:59 -0700 Subject: [PATCH] Add solution for problem 3 --- include/p3.h | 7 +++++++ input_p3.dat | 4 ++++ src/main.c | 6 ++++++ src/p3.c | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+) create mode 100644 include/p3.h create mode 100644 input_p3.dat create mode 100644 src/p3.c diff --git a/include/p3.h b/include/p3.h new file mode 100644 index 0000000..097e665 --- /dev/null +++ b/include/p3.h @@ -0,0 +1,7 @@ +#ifndef P3_H +#define P3_H + +double sum_file(const char* filename); + +#endif + diff --git a/input_p3.dat b/input_p3.dat new file mode 100644 index 0000000..1f301c5 --- /dev/null +++ b/input_p3.dat @@ -0,0 +1,4 @@ +1.0 +2.2 +3.0 +5.4 diff --git a/src/main.c b/src/main.c index dbc268c..e80b917 100644 --- a/src/main.c +++ b/src/main.c @@ -2,6 +2,7 @@ #include "p1.h" #include "p2.h" +#include "p3.h" int main(void) { // Problem 1 @@ -21,6 +22,11 @@ int main(void) { printf("Average: %.2lf, Min: %.2lf, Max: %.2lf\n", avg, min, max); + // Problem 3 + double sum_of_file = sum_file("input_p3.dat"); + + printf("Sum of file: %.2lf\n", sum_of_file); + return 0; } diff --git a/src/p3.c b/src/p3.c new file mode 100644 index 0000000..3a62ad0 --- /dev/null +++ b/src/p3.c @@ -0,0 +1,48 @@ +#include "p3.h" + +#define _CRT_SECURE_NO_WARNINGS + +#include + +double sum_file(const char* filename) { + FILE* infile = fopen(filename, "r"); + + double sum = 0.0; + double value = 0.0; + + // NOTE: Using feof may fail if you're not careful! For example, if the file + // being read from contains trailing whitespace characters, EOF may not + // be set until one additional read is performed. In this case, this would + // cause fscanf to attempt to read one additional value that does not exist. + // On Linux, this additional read is needed even if there is no trailing + // whitespace, although this may differ on other systems. + // + // As another example, if fscanf encounters an unexpected value, the position + // inside of the file will not be increased. Since we are attempting to read + // floating-point numbers, if we add an alphabetic character to the input file, + // fscanf will be stuck in an infinite loop trying to read invalid data and + // never progressing. + /*while (!feof(infile)) { + value = 0.0; + fscanf(infile, "%lf", &value); + + // Try changing the input file and see what this prints! + printf("(feof) Adding value %.2lf to sum\n", value); + + sum += value; + }*/ + + // A more reliable way of repeatedly reading from a file is checking + // the return value of fscanf. On success, fscanf will return the number + // of values read. + while (fscanf(infile, "%lf", &value) == 1) { + printf("(fscanf) Adding value %.2lf to sum\n", value); + + sum += value; + } + + fclose(infile); + + return sum; +} +