advent-of-code

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

commit abd4bb6e8d3f1740d35d41971ea6284c2a292267
parent ded437a4a7e4dc99209d9412a9351bab2107f69a
Author: aabacchus <ben@bvnf.space>
Date:   Tue,  6 Dec 2022 13:46:08 +0000

add while(getline) C template

Diffstat:
Agetline_tmpl.c | 33+++++++++++++++++++++++++++++++++
1 file changed, 33 insertions(+), 0 deletions(-)

diff --git a/getline_tmpl.c b/getline_tmpl.c @@ -0,0 +1,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; +}