-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2a_cd.cpp
More file actions
55 lines (52 loc) · 1.51 KB
/
2a_cd.cpp
File metadata and controls
55 lines (52 loc) · 1.51 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
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
int change_directory(const char *path) {
if (path == nullptr || path[0] == '\0') {
// No argument provided, change to the home directory
const char *home_dir = getenv("HOME");
if (home_dir != nullptr) {
if (chdir(home_dir) != 0) {
perror("cd");
}
}
} else if (strcmp(path, "-") == 0) {
// Change to the previous directory
const char *previous_dir = getenv("OLDPWD");
if (previous_dir != nullptr) {
if (chdir(previous_dir) != 0) {
perror("cd");
}
}
} else if (strcmp(path, ".") == 0) {
// Do nothing (current directory)
} else if (strcmp(path, "..") == 0) {
// Move to the parent directory
if (chdir("..") != 0) {
perror("cd");
}
} else if (strcmp(path, "~") == 0) {
// Change to the home directory
const char *home_dir = getenv("HOME");
if (home_dir != nullptr) {
if (chdir(home_dir) != 0) {
perror("cd");
}
}
} else {
// Change to the specified directory
if (chdir(path) != 0) {
perror("cd");
}
}
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <directory>" << std::endl;
return 1;
}
const char *path = argv[1];
return change_directory(path);
}