-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcd.c
More file actions
78 lines (72 loc) · 1.66 KB
/
Copy pathcd.c
File metadata and controls
78 lines (72 loc) · 1.66 KB
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
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <stdbool.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/utsname.h>
void changeDirectory(char *input, char *home_dir, char *prev_dir, char *curr_dir)
{
input += 2; // Skip the "cd" part
while (*input == ' ' || *input == '\t')
input++; // Skip any leading spaces
char *arg = strtok(input, " \t");
// Remove the newline at the end of the argument if it exists
if (arg != NULL && arg[strlen(arg) - 1] == '\n')
{
arg[strlen(arg) - 1] = '\0';
}
char *extra_arg = strtok(NULL, " \t"); // Check if there's more than one argument
if (arg == NULL)
{
// No arguments, go to the home directory
if (chdir(home_dir) != 0)
{
perror("cd error");
}
}
else if (extra_arg != NULL)
{
printf("cd: too many arguments\n");
}
else if (strcmp(arg, "..") == 0)
{
if (chdir("..") != 0)
{
perror("cd error");
}
}
else if (strcmp(arg, "-") == 0)
{
if (prev_dir[0] == '\0')
{
printf("cd: OLDPWD not set\n");
}
else
{
printf("%s\n", prev_dir);
if (chdir(prev_dir) != 0)
{
perror("cd error");
}
}
}
else if (strcmp(arg, "~") == 0)
{
if (chdir(home_dir) != 0)
{
perror("cd error");
}
}
else
{
if (chdir(arg) != 0)
{
perror("cd error");
}
}
// Store the previous directory
strcpy(prev_dir, curr_dir);
}