gif

read/write GIFs
git clone git://bvnf.space/gm.git
Log | Files | Refs | README

commit 6c8797ad5b3a3caef409000333e6671a26d73b5e
parent 7cc60d17c3dbfbf4c73c2b60a073162d363d8857
Author: phoebos <ben@bvnf.space>
Date:   Wed, 25 Aug 2021 19:51:42 +0100

it reads the whole file into a buffer. oh wow

why does it always take me so long to get to this stage
note: don't free(3) tmp

Diffstat:
Mgif.c | 71++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
1 file changed, 52 insertions(+), 19 deletions(-)

diff --git a/gif.c b/gif.c @@ -7,39 +7,72 @@ #include <fcntl.h> #include <stdio.h> +#include <stdlib.h> #include <strings.h> #include <unistd.h> -#define BUF_SIZE 10 -#define FAIL_SYS 1 -#define FAIL_GIF 2 +#define BUF_SIZE 100 +#define FAIL_GIF 1 +#define FAIL_SYS 2 int main(int argc, char **argv){ int fd; + + /* only work on one file */ + if (argc > 2) { + fprintf(stderr, "too many args\n"); + return FAIL_SYS; + } + ++argv; - do { - fd = 0; - if (*argv && **argv != '-') { - fd = open(*argv, O_RDONLY); - if (fd == -1) { - perror("open"); + /* stdin */ + if (argc == 1 || **argv == '-') fd = 0; + else { + /* open named file */ + fd = open(*argv, O_RDONLY); + if (fd == -1) { + perror(*argv); + return FAIL_SYS; + } + } + + unsigned char *buf; + buf = (unsigned char *) malloc(BUF_SIZE); + + /* read the whole file from fd into buf. */ + ssize_t bytes; + size_t size, used; + unsigned char *tmp; + used = 0; + size = BUF_SIZE; /* initial size from malloc(BUF_SIZE) above */ + + while (1) { + if (used + BUF_SIZE + 1 > size) { + size = used + BUF_SIZE + 1; + tmp = realloc(buf, size); + if (tmp == NULL) { + /* out of memory */ + perror("realloc"); + free(buf); return FAIL_SYS; } + buf = tmp; } - char buf[BUF_SIZE]; - fprintf(stderr, "reading from %s\n", *argv); - ssize_t bytes = read(fd, buf, BUF_SIZE); + bytes = read(fd, buf + used, BUF_SIZE); + if (bytes == 0) break; /* EOF */ if (bytes < 0) { perror("read"); return FAIL_SYS; } - if (close(fd) != 0) { - perror("close"); - return FAIL_SYS; - } - buf[bytes] = '\0'; - printf("%s\n", buf); - } while (*++argv); + used += bytes; + } + + if (close(fd) != 0) { + perror("close"); + return FAIL_SYS; + } + + free(buf); return 0; }