1
0
mirror of https://gitlab.com/80486DX2-66/gists synced 2024-12-27 05:40:17 +05:30
gists/c-programming/strings/portable_basename.c

47 lines
812 B
C
Raw Normal View History

2024-06-26 01:05:10 +05:30
/*
* 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;
}