-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprompt.c
99 lines (77 loc) · 1.79 KB
/
prompt.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include "headers.h"
int prompt()
{
char *login_name = (char *)malloc(BUFFER_SIZE);
if (login_name == NULL)
{
fprintf(stderr, "Error allocating memory");
return EXIT_FAILURE;
}
char *host_name = (char *)malloc(BUFFER_SIZE);
if (host_name == NULL)
{
fprintf(stderr, "Error allocating memory");
free(login_name);
return EXIT_FAILURE;
}
if (getlogin() == NULL)
{
login_name = "anonymous_user";
}
else
{
strcpy(login_name, getlogin());
}
int result = gethostname(host_name, BUFFER_SIZE);
if (result == -1)
{
perror("Error getting hostname");
}
char *path = (char *)malloc(BUFFER_SIZE);
if (path == NULL)
{
fprintf(stderr, "Error allocating memory");
return EXIT_FAILURE;
}
if (getcwd(path, BUFFER_SIZE) != NULL)
{
char *homedir = getenv("HOME");
int len = strlen(homedir);
for (int i = len; i <= strlen(path); ++i)
{
path[i - len] = path[i];
}
}
else
{
perror("getcwd() error");
free(path);
free(login_name);
free(host_name);
return EXIT_FAILURE;
}
printf("\033[0;35m<%s@%s:\033[0;32m%s\033[0;35m~>\033[0;37m", host_name, login_name, path);
free(login_name);
free(host_name);
free(path);
return EXIT_SUCCESS;
}
char *readline()
{
char *command = (char *)malloc(BUFFER_SIZE);
if (command == NULL)
{
fprintf(stderr, "Error allocating memory");
return command;
}
size_t sz = BUFFER_SIZE;
if (getline(&command, &sz, stdin) == -1)
{
perror("getline()");
}
if (strlen(command) > 0)
{
command[strlen(command) - 1] = '\0';
}
return command;
}