advent-of-code

advent of code attempts
git clone git://bvnf.space/advent-of-code.git
Log | Files | Refs

1.c (712B)


      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
#include <stdio.h>
#include <stdlib.h>

int
main (int argc, char **argv) {
	if (argc < 2) {
		fprintf(stderr, "usage: %s datafile\n", argv[0]);
		return 1;
	}

	FILE *fd = fopen(argv[1], "r");
	if (fd == NULL) {
		perror(argv[1]);
		return 1;
	}

	int i = 0;
	int prev = 0;
	int numlarger = 0;

	char *buf = NULL;
	size_t buflen = 0;

	while (getline(&buf, &buflen, fd) != -1) {
		if (++i == 1)
			continue;
		int l = 0;
		l = atoi(buf);
		if (l == 0) {
			fprintf(stderr, "error parsing line %d '%s'\n", i, buf);
			continue;
		}

		if (l > prev)
			numlarger++;

		prev = l;
	}

	free(buf);
	if (fclose(fd) == EOF) {
		perror("fclose");
	}

	printf("of %d lines, %d are greater\n", i, numlarger);
	return 0;
}