72 lines
1.3 KiB
C
72 lines
1.3 KiB
C
#include <ctype.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
unsigned int getSum(FILE *file);
|
|
char getFirstDigit(const char *line, size_t len);
|
|
char getLastDigit(const char *line, size_t len);
|
|
|
|
int main(int argc, char *argv[]) {
|
|
|
|
if (argc != 2) {
|
|
printf("error: missing file input\n");
|
|
return 1;
|
|
}
|
|
|
|
FILE *file = fopen(argv[1], "r");
|
|
if (file == NULL) {
|
|
printf("could not open file: %s\n", argv[1]);
|
|
return 1;
|
|
}
|
|
|
|
unsigned int sum = getSum(file);
|
|
printf("%d\n", sum);
|
|
|
|
fclose(file);
|
|
|
|
return 0;
|
|
}
|
|
|
|
unsigned int getSum(FILE *file) {
|
|
|
|
unsigned int sum = 0;
|
|
size_t len = 0;
|
|
size_t read;
|
|
char *line = NULL;
|
|
|
|
while ((read = getline(&line, &len, file)) != -1) {
|
|
char first = getFirstDigit(line, read);
|
|
char last = getLastDigit(line, read);
|
|
|
|
char digits[3] = {first, last, '\0'};
|
|
sum += atoi(digits);
|
|
}
|
|
|
|
// free(line);
|
|
return sum;
|
|
}
|
|
|
|
char getFirstDigit(const char *line, size_t len) {
|
|
|
|
char digit;
|
|
for (int i = 0; i < len; i++) {
|
|
if (isdigit(line[i])) {
|
|
digit = (char)line[i];
|
|
break;
|
|
}
|
|
}
|
|
return digit;
|
|
}
|
|
|
|
char getLastDigit(const char *line, size_t len) {
|
|
|
|
char digit;
|
|
for (int i = len - 1; i >= 0; i--) {
|
|
if (isdigit(line[i])) {
|
|
digit = (char)line[i];
|
|
break;
|
|
}
|
|
}
|
|
return digit;
|
|
}
|