From bf21c13f80c8199f079d227db05270e25077e557 Mon Sep 17 00:00:00 2001 From: Misa Date: Mon, 18 May 2020 14:03:14 -0700 Subject: [PATCH] Handle return values from fread() and fwrite() in PLATFORM_copyFile() Whenever I compile with -O2, GCC gives me a warning that the return value of fread() is being ignored. Which is a fair point, it means that we're not doing proper error handling if something goes wrong. But I'm also going to check the return value of fwrite() for good measure. I believe that checking that this number is not equal to length is the way to catch all errors and output an error message accordingly. I didn't use ferror() or feof() mostly because I think it takes up too much code. Also an error from fwrite() only says "Warning" because I don't think there's much we can do if we don't fully write all bytes to the intended file. --- desktop_version/src/FileSystemUtils.cpp | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/desktop_version/src/FileSystemUtils.cpp b/desktop_version/src/FileSystemUtils.cpp index d620593b..1710e080 100644 --- a/desktop_version/src/FileSystemUtils.cpp +++ b/desktop_version/src/FileSystemUtils.cpp @@ -438,7 +438,7 @@ void PLATFORM_migrateSaveData(char* output) void PLATFORM_copyFile(const char *oldLocation, const char *newLocation) { char *data; - long int length; + size_t length, bytes_read, bytes_written; /* Read data */ FILE *file = fopen(oldLocation, "rb"); @@ -451,8 +451,14 @@ void PLATFORM_copyFile(const char *oldLocation, const char *newLocation) length = ftell(file); fseek(file, 0, SEEK_SET); data = (char*) malloc(length); - fread(data, 1, length, file); + bytes_read = fread(data, 1, length, file); fclose(file); + if (bytes_read != length) + { + printf("An error occurred when reading from %s\n", oldLocation); + free(data); + return; + } /* Write data */ file = fopen(newLocation, "wb"); @@ -462,12 +468,16 @@ void PLATFORM_copyFile(const char *oldLocation, const char *newLocation) free(data); return; } - fwrite(data, 1, length, file); + bytes_written = fwrite(data, 1, length, file); fclose(file); free(data); /* WTF did we just do */ printf("Copied:\n\tOld: %s\n\tNew: %s\n", oldLocation, newLocation); + if (bytes_written != length) + { + printf("Warning: an error occurred when writing to %s\n", newLocation); + } } bool FILESYSTEM_openDirectoryEnabled()