diff --git a/src/file.c b/src/file.c index 77e4a27..2ce8eb8 100644 --- a/src/file.c +++ b/src/file.c @@ -1,3 +1,4 @@ +#include #include #include @@ -5,9 +6,12 @@ const char* basename(const char* filename) { - const char* slash = filename; - for ( ; *slash && *slash != '\\' && *slash != '/'; ++slash); - return (*slash ? (&slash[1]) : filename); + const char* slash = filename + strlen(filename) - 1; + for ( ; slash >= filename && + *slash != '\\' && + *slash != '/'; + --slash ); + return &slash[1]; } int replace_extension(char* filename, int max_len, @@ -49,8 +53,15 @@ int write_file(const char* filename, const void* data, int len) { int status = -1; FILE* file = fopen(filename, "wb"); - if (NULL != file && 1 == fwrite(data, len, 1, file)) { - status = 0; + if (NULL != file) { + if (1 == fwrite(data, len, 1, file)) { + status = 0; + } else { + fprintf(stderr, "Failed to write %d bytes from %s: %d\n", len, filename, errno); + } + fclose(file); + } else { + fprintf(stderr, "Failed to open %s: %d\n", filename, errno); } return status; @@ -61,8 +72,15 @@ int read_file(const char* filename, void* data, int len) { int status = -1; FILE* file = fopen(filename, "rb"); - if (NULL != file && 1 == fread(data, len, 1, file)) { - status = 0; + if (NULL != file) { + if (1 == fread(data, len, 1, file)) { + status = 0; + } else { + fprintf(stderr, "Failed to read %d bytes from %s: %d\n", len, filename, errno); + } + fclose(file); + } else { + fprintf(stderr, "Failed to open %s: %d\n", filename, errno); } return status;