sumNums.c (1387B)
1 //: generator/pp comment config 2 //:not cScript 3 #include "../release/libsheepy.h" 4 //:end 5 6 #define internal static 7 8 #include <stdlib.h> 9 #include <stdint.h> 10 #include <stdio.h> 11 12 #ifndef unitTest 13 #endif 14 int MAIN(int ARGC, char** ARGV); 15 16 int argc; char **argv; 17 18 #ifndef unitTest 19 // Remove main when running the unit tests 20 #define MAIN main 21 #endif 22 int MAIN(int ARGC, char** ARGV) { 23 char **list = NULL; 24 int64_t sumResult = 0;; 25 26 argc = ARGC; argv = ARGV;;// sum numbers from a text file 27 28 // Steps 29 // load text 30 // remove empty lines 31 // sum lines 32 33 if (argc < 2) { 34 printf("TODO: sum numbers from stdin"); 35 printf("\n"); 36 exit(1); 37 } 38 39 // load text 40 list = readText(argv[1]); 41 42 // remove empty lines 43 char **compactList = listCompactS(list); 44 45 // sum lines 46 forEachCharP(compactList, e) { 47 // remove spaces 48 char *line = trimS(*e); 49 // space is the intra line seperator 50 char **splitE = split(line, " "); 51 // keep only non-empty strings 52 char **compactSplit = listCompactS(splitE); 53 // get number in first column 54 char *numS = listGetS(compactSplit, 0); 55 // convert to int 56 int64_t v = parseInt(numS); 57 // add 58 sumResult += v; 59 free(line); 60 listFreeS(splitE); 61 listFreeS(compactSplit); 62 free(numS); 63 } 64 65 listFreeS(compactList); 66 listFreeS(list); 67 68 printf("Sum of %s: %lld", argv[1], sumResult); 69 printf("\n"); 70 }