-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_cmd_name.c
51 lines (42 loc) · 1.08 KB
/
base_cmd_name.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
// base_cmd_name.c print the executable name with and without full path
//
// Uses:
// basename()
// malloc()
// realpath()
// printing to stderr
//
// $ gcc -o base_cmd_name base_cmd_name
// $ ./base_cmd_name
//
///////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <libgen.h>
#include <linux/limits.h>
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
char *path = NULL;
char *fullpath = NULL;
path = malloc(sizeof(argv[0]+1));
fullpath = malloc(PATH_MAX+1);
if (path == NULL || fullpath == NULL) {
exit(1);
fprintf(stderr, "%s: memory error\n", argv[0]);
}
// basename() works on copy of path
strcpy(path, argv[0]);
realpath(path, fullpath);
if (fullpath == NULL) {
exit(1);
fprintf(stderr, "%s: realpath error\n", argv[0]);
}
printf("argv[0]: %s\n", argv[0]);
printf("basename(path): %s\n", basename(path));
printf("realpath(path): %s\n", fullpath);
return EXIT_SUCCESS;
}