1/*
2 * Copyright 2005, Ingo Weinhold, bonefish@users.sf.net.
3 * Distributed under the terms of the MIT License.
4 */
5
6#include "compat.h"
7
8#include <stdlib.h>
9#include <string.h>
10
11#include "path_util.h"
12
13status_t
14get_last_path_component(const char *path, char *buffer, int bufferLen)
15{
16	int len = strlen(path);
17	if (len == 0)
18		return FS_EINVAL;
19
20	// eat trailing '/'
21	while (len > 0 && path[len - 1] == '/')
22		len--;
23
24	if (len == 0) {
25		// path is `/'
26		len = 1;
27	} else {
28		// find previous '/'
29		int pos = len - 1;
30		while (pos > 0 && path[pos] != '/')
31			pos--;
32		if (path[pos] == '/')
33			pos++;
34
35		path += pos;
36		len -= pos;
37	}
38
39	if (len >= bufferLen)
40		return FS_NAME_TOO_LONG;
41
42	memcpy(buffer, path, len);
43	buffer[len] = '\0';
44	return FS_OK;
45}
46
47char *
48make_path(const char *dir, const char *entry)
49{
50	// get the len
51	int dirLen = strlen(dir);
52	int entryLen = strlen(entry);
53	bool insertSeparator = (dir[dirLen - 1] != '/');
54	int pathLen = dirLen + entryLen + (insertSeparator ? 1 : 0) + 1;
55
56	// allocate the path
57	char *path = (char*)malloc(pathLen);
58	if (!path)
59		return NULL;
60
61	// compose the path
62	strcpy(path, dir);
63	if (insertSeparator)
64		strcat(path + dirLen, "/");
65	strcat(path + dirLen, entry);
66
67	return path;
68}
69
70
71