mirror of
https://gitlab.com/80486DX2-66/gists
synced 2024-11-08 18:02:23 +05:30
47 lines
812 B
C
47 lines
812 B
C
/*
|
|
* portable_basename.c
|
|
*
|
|
* Author: Intel A80486DX2-66
|
|
* License: Unlicense
|
|
*/
|
|
|
|
#include "portable_basename.h"
|
|
|
|
static char* correct_slashes(const char* path) {
|
|
char* new_path = strdup(path);
|
|
if (new_path == NULL)
|
|
return NULL;
|
|
|
|
char* ptr = new_path;
|
|
while (*ptr != '\0') {
|
|
if (*ptr == '\\')
|
|
*ptr = '/';
|
|
ptr++;
|
|
}
|
|
|
|
return new_path;
|
|
}
|
|
|
|
char* portable_basename(const char* raw_path) {
|
|
char* path = correct_slashes(raw_path);
|
|
if (path == NULL)
|
|
return NULL;
|
|
|
|
char* base = malloc(FILENAME_MAX * sizeof(char));
|
|
if (base == NULL) {
|
|
free(path);
|
|
return NULL;
|
|
}
|
|
|
|
size_t fname_len = strlen(path);
|
|
|
|
const char* last_slash = strrchr(path, '/');
|
|
if (last_slash != NULL)
|
|
fname_len = strlen(last_slash + 1);
|
|
|
|
memcpy(base, last_slash + 1, fname_len);
|
|
base[fname_len] = '\0';
|
|
|
|
return base;
|
|
}
|