REDESIGNED: GetFileNameWithoutExt()

Removed possible memory leak when using this function
This commit is contained in:
Ray 2019-03-13 10:07:01 +01:00
parent b6dd31c653
commit 5e8427a8b5

View File

@ -180,15 +180,14 @@
//#define GLFW_EXPOSE_NATIVE_COCOA // WARNING: Fails due to type redefinition //#define GLFW_EXPOSE_NATIVE_COCOA // WARNING: Fails due to type redefinition
#include <GLFW/glfw3native.h> // Required for: glfwGetCocoaWindow() #include <GLFW/glfw3native.h> // Required for: glfwGetCocoaWindow()
#endif #endif
#endif #endif
#if defined(__linux__) #if defined(__linux__)
#include <linux/limits.h> // for NAME_MAX and PATH_MAX defines #include <linux/limits.h> // for NAME_MAX and PATH_MAX defines
#define MAX_FILEPATH_LENGTH PATH_MAX // Use Linux define (4096) #define MAX_FILEPATH_LENGTH PATH_MAX // Use Linux define (4096)
#else #else
#define MAX_FILEPATH_LENGTH 256 // Use common value #define MAX_FILEPATH_LENGTH 512 // Use common value
#endif #endif
#if defined(PLATFORM_ANDROID) #if defined(PLATFORM_ANDROID)
@ -1676,37 +1675,26 @@ const char *GetFileName(const char *filePath)
// Get filename string without extension (memory should be freed) // Get filename string without extension (memory should be freed)
const char *GetFileNameWithoutExt(const char *filePath) const char *GetFileNameWithoutExt(const char *filePath)
{ {
char *result, *lastDot, *lastSep; #define MAX_FILENAMEWITHOUTEXT_LENGTH 64
char nameDot = '.'; // Default filename to extension separator character static char fileName[MAX_FILENAMEWITHOUTEXT_LENGTH];
char pathSep = '/'; // Default filepath separator character memset(fileName, 0, MAX_FILENAMEWITHOUTEXT_LENGTH);
// Error checks and allocate string strcpy(fileName, GetFileName(filePath)); // Get filename with extension
if (filePath == NULL) return NULL;
int len = strlen(fileName);
// Try to allocate new string, same size as original
// NOTE: By default strlen() does not count the '\0' character for (int i = 0; (i < len) && (i < MAX_FILENAMEWITHOUTEXT_LENGTH); i++)
if ((result = (char *)malloc(strlen(filePath) + 1)) == NULL) return NULL;
strcpy(result, filePath); // Make a copy of the string
// NOTE: strrchr() returns a pointer to the last occurrence of character
lastDot = strrchr(result, nameDot);
lastSep = (pathSep == 0)? NULL : strrchr(result, pathSep);
if (lastDot != NULL) // Check if it has an extension separator...
{ {
if (lastSep != NULL) // ...and it's before the extenstion separator... if (fileName[i] == '.')
{ {
if (lastSep < lastDot) // NOTE: We break on first '.' found
{ fileName[i] = '\0';
*lastDot = '\0'; // ...then remove it break;
}
} }
else *lastDot = '\0'; // Has extension separator with no path separator
} }
return result; // Return the modified string return fileName;
} }
// Get directory for a given fileName (with path) // Get directory for a given fileName (with path)