-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrealpath-posix.c
52 lines (48 loc) · 1.31 KB
/
realpath-posix.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
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <libgen.h> /* for basename(3) in error messages */
#include <string.h> /* for str(n)dup(3) - to copy strings so basename()
doesn't tamper with things */
void errmsg(char *message);
char *invoke_name;
int main(int argc, char **argv)
{
invoke_name = argv[0];
if(argc == 2)
{
char *to_resolve = argv[1];
/* char *restrict full_path[PATH_MAX + 1]; */
/* POSIX says that if the resolved_name arg is null pointer, it will allocate
for us. */
char *restrict full_path = realpath(to_resolve, NULL);
if(full_path == NULL)
{
char *e_fmt = "Cannot find file %s";
size_t str_size = snprintf(NULL, 0, e_fmt, to_resolve);
char *e_msg = malloc(str_size + 1);
sprintf(e_msg, e_fmt, to_resolve);
errmsg(e_msg);
free(e_msg);
return 2;
}
else
{
printf("%s\n",full_path);
free(full_path);
}
return 0;
}
else /* argc != 2 */
{
errmsg("Please pass exactly one argument (a path to resolve).");
return 1;
}
}
void errmsg(char *message)
{
char *progname = strdup(invoke_name);
char *basename_out = basename(progname);
fprintf(stderr, "E: %s: %s\n", basename_out, message);
free(progname); /* posix basename() does not do a malloc */
}