REDESIGNED: GetFileNameWithoutExt()
Removed possible memory leak when using this function
This commit is contained in:
parent
b6dd31c653
commit
5e8427a8b5
48
src/core.c
48
src/core.c
@ -180,15 +180,14 @@
|
||||
|
||||
//#define GLFW_EXPOSE_NATIVE_COCOA // WARNING: Fails due to type redefinition
|
||||
#include <GLFW/glfw3native.h> // Required for: glfwGetCocoaWindow()
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(__linux__)
|
||||
#include <linux/limits.h> // for NAME_MAX and PATH_MAX defines
|
||||
#define MAX_FILEPATH_LENGTH PATH_MAX // Use Linux define (4096)
|
||||
#include <linux/limits.h> // for NAME_MAX and PATH_MAX defines
|
||||
#define MAX_FILEPATH_LENGTH PATH_MAX // Use Linux define (4096)
|
||||
#else
|
||||
#define MAX_FILEPATH_LENGTH 256 // Use common value
|
||||
#define MAX_FILEPATH_LENGTH 512 // Use common value
|
||||
#endif
|
||||
|
||||
#if defined(PLATFORM_ANDROID)
|
||||
@ -1676,37 +1675,26 @@ const char *GetFileName(const char *filePath)
|
||||
// Get filename string without extension (memory should be freed)
|
||||
const char *GetFileNameWithoutExt(const char *filePath)
|
||||
{
|
||||
char *result, *lastDot, *lastSep;
|
||||
|
||||
char nameDot = '.'; // Default filename to extension separator character
|
||||
char pathSep = '/'; // Default filepath separator character
|
||||
|
||||
// Error checks and allocate string
|
||||
if (filePath == NULL) return NULL;
|
||||
|
||||
// Try to allocate new string, same size as original
|
||||
// NOTE: By default strlen() does not count the '\0' character
|
||||
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...
|
||||
#define MAX_FILENAMEWITHOUTEXT_LENGTH 64
|
||||
|
||||
static char fileName[MAX_FILENAMEWITHOUTEXT_LENGTH];
|
||||
memset(fileName, 0, MAX_FILENAMEWITHOUTEXT_LENGTH);
|
||||
|
||||
strcpy(fileName, GetFileName(filePath)); // Get filename with extension
|
||||
|
||||
int len = strlen(fileName);
|
||||
|
||||
for (int i = 0; (i < len) && (i < MAX_FILENAMEWITHOUTEXT_LENGTH); i++)
|
||||
{
|
||||
if (lastSep != NULL) // ...and it's before the extenstion separator...
|
||||
if (fileName[i] == '.')
|
||||
{
|
||||
if (lastSep < lastDot)
|
||||
{
|
||||
*lastDot = '\0'; // ...then remove it
|
||||
}
|
||||
// NOTE: We break on first '.' found
|
||||
fileName[i] = '\0';
|
||||
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)
|
||||
|
Loading…
Reference in New Issue
Block a user