Created
July 14, 2018 15:51
-
-
Save mrothNET/c98482fc59c288f15f0d6332669e1eb6 to your computer and use it in GitHub Desktop.
dirnamedup() - Simpler interface to dirname()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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