Skip to content

Instantly share code, notes, and snippets.

@mrothNET
Created July 14, 2018 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrothNET/c98482fc59c288f15f0d6332669e1eb6 to your computer and use it in GitHub Desktop.
Save mrothNET/c98482fc59c288f15f0d6332669e1eb6 to your computer and use it in GitHub Desktop.
dirnamedup() - Simpler interface to dirname()
/*
Simpler interface to dirname() because dirname() has drawbacks:
- may modify the argument
- may return a pointer to static memory which gets
overwritten in subsequent calls
This function never modifies the argument and returns a pointer
to freshly allocated memory.
The caller is responsibly to free() the result,
*/
#define _POSIX_SOURCE
#define _BSD_SOURCE
#include <libgen.h>
#include <stdlib.h>
#include <string.h>
extern char *dirnamedup(const char *path)
{
char *dircopy = NULL;
if (!path || !*path)
return strdup(".");
char *pathcopy = strdup(path);
if (!pathcopy)
goto exit;
char *dir = dirname(pathcopy);
if (!dir)
goto exit;
dircopy = strdup(dir);
exit:
free(pathcopy);
return dircopy;
}
#ifndef DIRNAMEDUP_H
#define DIRNAMEDUP_H
extern char *dirnamedup(const char *path);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment