advent-of-code

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

getline_tmpl.c (547B)


      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
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char **argv) {
    char *buf = NULL;
    size_t buflen = 0;
    ssize_t n;
    FILE *f;

    if (argc != 2) {
        fprintf(stderr, "usage: %s input\n", argv[0]);
        return 1;
    }

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

    while ((n = getline(&buf, &buflen, f)) != -1) {
        if (buf[n - 1] == '\n') {
            buf[n - 1] = '\0';
            n--;
        }
    }

    free(buf);
    fclose(f);

    return 0;
}