commit 2c6fea4082058ef748afe6a798ec7319ebda4d70
parent 0e418aa8173f97591207438238bf55395932d2ac
Author: Paco Esteban <paco@e1e0.net>
Date: Mon, 22 Jun 2020 19:26:43 +0200
better handle fseek, ftell and fclose
Diffstat:
1 file changed, 13 insertions(+), 4 deletions(-)
diff --git a/helpers.c b/helpers.c
@@ -111,13 +111,22 @@ load_from_file(char **buffer, char *path)
return 0;
if (f) {
- fseek(f, 0, SEEK_END); /* go to the end of file */
- length = ftell(f); /* record the length of the file */
- fseek(f, 0, SEEK_SET); /* go to the start again */
+ /* Go to the end of the file. Record it's length, and return to
+ * the start
+ */
+ if (fseek(f, 0, SEEK_END) == -1)
+ return 0;
+ if ((length = ftell(f)) == -1)
+ return 0;
+ if (fseek(f, 0, SEEK_SET) == -1)
+ return 0;
+
*buffer = malloc(length + 1);
if (*buffer)
fread(*buffer, 1, length, f);
- fclose(f);
+
+ if (fclose(f) != 0)
+ return 0;
/* add null terminator to string.
* apparently this is not the same as:
* *buffer[length] = '\0';