-
Notifications
You must be signed in to change notification settings - Fork 0
/
path.c
79 lines (65 loc) · 2.54 KB
/
path.c
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
/* path.c - path functions for Plunge
*
* Copyright (c) 2016-21 Jeffrey Paul Bourdier
*
* Licensed under the MIT License. This file may be used only in compliance with this License.
* Software distributed under this License is provided "AS IS", WITHOUT WARRANTY OF ANY KIND.
* For more information, see the accompanying License file or the following URL:
*
* https://opensource.org/licenses/MIT
*/
/*****************
* Include Files *
*****************/
#include <string.h> /* memcpy, strlen */
#include <stdio.h> /* printf */
#include "jb.h" /* JB_PATH_SEPARATOR, JB_PATH_MAX_LENGTH */
#include "path.h" /* MAX_LINE_LENGTH */
/*************
* Functions *
*************/
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Build an absolute pathname from a directory pathname and a relative pathname.
* abs: receives absolute pathname
* dir: directory pathname
* rel: relative pathname
*/
void path_build(char * abs, const char * dir, const char * rel)
{
size_t i = strlen(dir), n = strlen(rel) + 1;
char s[JB_PATH_MAX_LENGTH];
memcpy(s, dir, i);
if (s[i - 1] != JB_PATH_SEPARATOR) s[i++] = JB_PATH_SEPARATOR;
memcpy(s + i, rel, n);
memcpy(abs, s, i + n);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Output a relative pathname within a given field width (shortened as necessary),
* left-justified, with a trailing newline or right-padded with double-spaced dots.
* path: relative pathname
* width: field width
*/
void path_output(const char * path, int width)
{
static const int v = 3, w = 6;
int n, m, i, j, k;
char s[MAX_LINE_LENGTH];
/* If the width is less than the maximum line length, output with padding (instead of a trailing newline). */
m = (width < MAX_LINE_LENGTH) ? width - v : width;
/* If necessary, shorten the pathname to fit within the field. */
if ((n = strlen(path)) > m)
{
for (i = n - 1; i > w && path[i] != JB_PATH_SEPARATOR; --i);
while ((k = m - (j = n - i)) < w) ++i;
memcpy(s, path, n = k - v);
while (n < k) s[n++] = '.';
memcpy(s + n, path + i, j);
n = m;
}
else memcpy(s, path, n);
/* If appropriate, right-pad the field with double-spaced dots. (Otherwise, append a newline.) */
if (m < width) while (n < width) { s[n] = ((width - n) % 2) ? ' ' : '.'; ++n; }
else s[n++] = '\n';
/* Finally, null-terminate and output the string buffer. */
s[n] = '\0'; printf("%s", s);
}