Advent-of-Code/day1/solution-part2.c
Jonathan Hodgson f6a7e1dbfe Day 1
2021-12-01 22:03:50 +00:00

54 lines
859 B
C

#include <stdio.h>
int countLines(char filename[]){
FILE *fp;
fp=fopen(filename, "r");
long int lines =0;
if ( fp == NULL ) {
return -1;
}
while (EOF != (fscanf(fp, "%*[^\n]"), fscanf(fp,"%*c")))
++lines;
fclose(fp); // closing file
return lines;
}
int main( int argc, char *argv[] ){
if( argc == 2 ) {
// 1 less because file ends with trailing new line
int lines=countLines(argv[1]);
int values[lines];
int line=0;
FILE *fp=fopen(argv[1], "r");
int increasing = 0;
// Read the values into an array
while (!feof (fp)){
fscanf(fp, "%d\n", &values[line]);
if ( (line >= 3) && (values[line] > values[line-3]) ){
increasing++;
}
line++;
}
fclose(fp); // closing file
printf( "Increasing: %d\n", increasing );
return 0;
} else {
printf("You need to provide a file\n");
return 1;
}
}