From b1d4e30974dea432cae98a6ed149988d1063e1e6 Mon Sep 17 00:00:00 2001 From: Benjamin Franzke Date: Thu, 31 Jan 2013 22:27:36 +0100 Subject: util: Add pgm_read function --- src/util.c | 41 +++++++++++++++++++++++++++++++++++++++++ src/util.h | 3 +++ 2 files changed, 44 insertions(+) diff --git a/src/util.c b/src/util.c index 8b73466..7b7077d 100644 --- a/src/util.c +++ b/src/util.c @@ -1,8 +1,49 @@ +#define _XOPEN_SOURCE 700 #include +#include +#include +#include #include "video_decode.h" #include "util.h" +int +pgm_read(char *filename, unsigned char **buf, int *xsize, int *ysize) +{ + FILE *f = NULL; + unsigned char *b = NULL; + int width, height; + ssize_t n; + + f = fopen(filename, "r"); + if (f == NULL) + return -1; + + if (fscanf(f, "P5\n%d %d\n255\n", &width, &height) == 0) + return -1; + + if (width * height <= 0) + goto fail; + + if ((b = malloc(width * height)) == NULL) + goto fail; + if ((n = fread(b, 1, width * height, f)) == 0 || n != width * height) + goto fail; + + fclose(f); + + *buf = b; + *xsize = width; + *ysize = height; + + return 0; + +fail: + if (f) fclose(f); + if (b) free(b); + return -1; +} + int pgm_save(unsigned char *buf, int wrap, int xsize, int ysize, char *filename) { diff --git a/src/util.h b/src/util.h index 649e9ee..5921a86 100644 --- a/src/util.h +++ b/src/util.h @@ -3,6 +3,9 @@ #include +int +pgm_read(char *filename, unsigned char **buf, int *xsize, int *ysize); + int pgm_save(unsigned char *buf, int wrap, int xsize, int ysize, char *filename); -- cgit