X-Git-Url: http://erislabs.net/gitweb/?a=blobdiff_plain;f=lib%2Fdirname.c;h=3487015343dc0c890294470a7dbf4faccde2663f;hb=559ac9667adc2becf7a2a956f00024b79056469d;hp=e01fa42ac558a0da42965380d0cdf3ae33529ff7;hpb=4d2ba1df0fd6135c58ce1dc16e8e28ba510e700e;p=gnulib.git diff --git a/lib/dirname.c b/lib/dirname.c index e01fa42ac..348701534 100644 --- a/lib/dirname.c +++ b/lib/dirname.c @@ -49,17 +49,15 @@ void *memrchr (); #define BACKSLASH_IS_PATH_SEPARATOR ISSLASH ('\\') -/* Return the leading directories part of PATH, - allocated with malloc. If out of memory, return 0. +/* Return the length of `dirname (PATH)' and set *RESULT + to point to PATH or to `"."', as appropriate. Works properly even if there are trailing slashes (by effectively ignoring them). */ - -char * -dir_name (const char *path) +size_t +dir_name_r (const char *path, const char **result) { - char *newpath; char *slash; - int length; /* Length of result, not including NUL. */ + size_t length; /* Length of result, not including NUL. */ slash = strrchr (path, '/'); if (BACKSLASH_IS_PATH_SEPARATOR) @@ -118,10 +116,24 @@ dir_name (const char *path) length = slash - path + 1; } - newpath = (char *) malloc (length + 1); + *result = path; + return length; +} + +/* Return the leading directories part of PATH, + allocated with malloc. If out of memory, return 0. + Works properly even if there are trailing slashes + (by effectively ignoring them). */ + +char * +dir_name (const char *path) +{ + const char *result; + size_t length = dir_name_r (path, &result); + char *newpath = (char *) malloc (length + 1); if (newpath == 0) return 0; - strncpy (newpath, path, length); + strncpy (newpath, result, length); newpath[length] = 0; return newpath; }