aboutsummaryrefslogtreecommitdiff
path: root/src/path.c
blob: 5502a7b6df06ac048c795842cc7dce95a49ce425 (plain) (blame)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* SPDX-License-Identifier: copyleft-next-0.3.1 */
/* Copyright 2023 Kim Kuparinen < kimi.h.kuparinen@gmail.com > */

/**
 * @file path.c
 *
 * Path handling helper implementations.
 */

#include <stddef.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>

#include <fwd/path.h>
#include <fwd/debug.h>
#include <fwd/tracker.h>
#include <fwd/coverage.h>

char *fwd_basename(const char *file)
{
	size_t l = strlen(file);
	size_t n = l - 1;
	while (--n) {
		if (file[n] == '/')
			break;
	}

	char *s = NULL;
	if (n == 0)
		s = strdupc(file);
	else
		s = strndupc(file + n + 1, l - n);

	if (!s) {
		internal_error("failed allocating basename");
		return NULL;
	}

	track_ptr(s);
	return s;
}

char *fwd_dirname(const char *file)
{
	size_t l = strlen(file);
	size_t n = l - 1;
	while (--n) {
		if (file[n] == '/')
			break;
	}

	char *s = strndupc(file, n);
	if (!s) {
		internal_error("failed allocating dirname");
		return NULL;
	}

	track_ptr(s);
	return s;
}

char *fwd_cwdname()
{
	size_t size;
	long path_max = pathconf(".", _PC_PATH_MAX);
	if (path_max == -1)
		size = 1024;
	else
		size = (size_t)path_max;

	char *buf = mallocc(size);
	if (!buf) {
		internal_error("failed allocating cwd buf");
		return NULL;
	}

	track_ptr(buf);
	if (!getcwd(buf, size)) {
		error("%s\n", strerror(errno));
		return NULL;
	}

	return buf;
}