Merge pull request #268 from N-R-K/stdio_errcheck

More strict stdio error checking
This commit is contained in:
Dominic Szablewski 2023-06-15 18:03:53 +02:00 committed by GitHub
commit ef61984291
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

12
qoi.h
View File

@ -594,7 +594,7 @@ void *qoi_decode(const void *data, int size, qoi_desc *desc, int channels) {
int qoi_write(const char *filename, const void *data, const qoi_desc *desc) { int qoi_write(const char *filename, const void *data, const qoi_desc *desc) {
FILE *f = fopen(filename, "wb"); FILE *f = fopen(filename, "wb");
int size; int size, err;
void *encoded; void *encoded;
if (!f) { if (!f) {
@ -608,10 +608,12 @@ int qoi_write(const char *filename, const void *data, const qoi_desc *desc) {
} }
fwrite(encoded, 1, size, f); fwrite(encoded, 1, size, f);
fflush(f);
err = ferror(f);
fclose(f); fclose(f);
QOI_FREE(encoded); QOI_FREE(encoded);
return size; return err ? 0 : size;
} }
void *qoi_read(const char *filename, qoi_desc *desc, int channels) { void *qoi_read(const char *filename, qoi_desc *desc, int channels) {
@ -625,11 +627,10 @@ void *qoi_read(const char *filename, qoi_desc *desc, int channels) {
fseek(f, 0, SEEK_END); fseek(f, 0, SEEK_END);
size = ftell(f); size = ftell(f);
if (size <= 0) { if (size <= 0 || fseek(f, 0, SEEK_SET) != 0) {
fclose(f); fclose(f);
return NULL; return NULL;
} }
fseek(f, 0, SEEK_SET);
data = QOI_MALLOC(size); data = QOI_MALLOC(size);
if (!data) { if (!data) {
@ -639,8 +640,7 @@ void *qoi_read(const char *filename, qoi_desc *desc, int channels) {
bytes_read = fread(data, 1, size, f); bytes_read = fread(data, 1, size, f);
fclose(f); fclose(f);
pixels = (bytes_read != size) ? NULL : qoi_decode(data, bytes_read, desc, channels);
pixels = qoi_decode(data, bytes_read, desc, channels);
QOI_FREE(data); QOI_FREE(data);
return pixels; return pixels;
} }