Browse Source

Add the get_file_basename function

Add a helper function to extract the basename of a filepath.
master
Damien Goutte-Gattat 5 years ago
parent
commit
2ec78811b3
  1. 31
      src/util.c
  2. 3
      src/util.h

31
src/util.c

@ -22,6 +22,7 @@
#include "util.h"
#include <string.h>
#include <errno.h>
#include <sys/types.h>
@ -149,3 +150,33 @@ write_file(const char *filename, const unsigned char *contents, size_t len)
return rc;
}
/**
* Gets the basename part of a path.
*
* @param path The path to extract the basename from.
*
* @return A newly allocated buffer containing the basename,
* or NULL if an error occured (check errno for details).
*/
char *
get_file_basename(const char *path)
{
char *last_slash, *last_dot;
unsigned n;
if ( ! path ) {
errno = EINVAL;
return NULL;
}
if ( (last_slash = strrchr(path, '/')) )
path = last_slash + 1;
if ( (last_dot = strrchr(path, '.')) )
n = last_dot - path;
else
n = strlen(path);
return strndup(path, n);
}

3
src/util.h

@ -38,6 +38,9 @@ read_file(const char *, size_t *, size_t);
int
write_file(const char *, const unsigned char *, size_t);
char *
get_file_basename(const char *);
#ifdef __cplusplus
}
#endif

Loading…
Cancel
Save