summaryrefslogtreecommitdiff
path: root/libs/pbd3/dirname.cc
blob: 6b97ac7e3a4083f04b3c0ff8035fb1d5468d612b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <cstdio>
#include <cstdlib>
#include <string>
#include <pbd/dirname.h>


char *
PBD::dirname (const char *path)

{
	char *slash;
	size_t len;
	char *ret;
	
	if ((slash = strrchr (path, '/')) == 0) {
		return strdup (path);
	}
	
	if (*(slash+1) == '\0') {
		return strdup ("");
	}

	len = (size_t) (slash - path);
	ret = (char *) malloc (sizeof (char) * (len + 1));

	snprintf (ret, len, "%*s", (int)len, path);
	return ret;
}

std::string 
PBD::dirname (const std::string str)
{
	std::string::size_type slash = str.find_last_of ('/');
	std::string dir;

	if (slash == std::string::npos) {
		return str;
	}

	/* remove trailing multiple slashes (legal under POSIX) */

	dir = str.substr (0, slash);
	slash = dir.length();

	while (slash > 1 && dir[slash-1] == '/') {
		slash--;
		dir = dir.substr (0, slash);
	}

	return dir;
}