From 629e68cabff4cec60a3e0152184aeaa40171788e Mon Sep 17 00:00:00 2001 From: Alex Chew Date: Sun, 17 Jul 2022 11:09:29 -0700 Subject: [PATCH 1/2] fix: correct write count in savePPM Previously, the `fwrite` call always returned 3 if it succeeded, and so `savePPM` would return 1 even if the entire pixel buffer was successfully written to file (except in the trivial case `sx * sy == 1`). This changes `savePPM` to return 0 if it was successful. --- util.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/util.c b/util.c index c6643e6..19637f5 100644 --- a/util.c +++ b/util.c @@ -470,9 +470,10 @@ int savePPM(const char *path, const unsigned char *pixels, const unsigned int sx if (!fp) return -1; fprintf(fp, "P6\n%d %d\n255\n", sx, sy); - int written = fwrite(pixels, sx*sy, 3, fp); + size_t pixelsLen = 3 * sx * sy; + size_t written = fwrite(pixels, sizeof pixels[0], pixelsLen, fp); fclose(fp); - return (unsigned int)written != 3*sx*sy; + return written != pixelsLen; } From f8437428e758811bc1e17d1149154831379470d6 Mon Sep 17 00:00:00 2001 From: Alex Chew Date: Sun, 17 Jul 2022 11:14:15 -0700 Subject: [PATCH 2/2] add doc comment to savePPM --- util.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/util.h b/util.h index d640cc6..8c5bf97 100644 --- a/util.h +++ b/util.h @@ -29,6 +29,9 @@ int biomesToImage(unsigned char *pixels, const unsigned int sx, const unsigned int sy, const unsigned int pixscale, const int flip); +/// Save the pixel buffer (e.g. from biomesToImage) to the given path in PPM format. +/// Returns 0 if successful, or -1 if the file could not be opened, +/// or 1 if not all the pixel data could be written to the file. int savePPM(const char* path, const unsigned char *pixels, const unsigned int sx, const unsigned int sy);