-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcd.cpp
More file actions
63 lines (55 loc) · 1.17 KB
/
cd.cpp
File metadata and controls
63 lines (55 loc) · 1.17 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
#include "allFunctions.h"
static string prevDir;
// Changes the current working directory with support for ~, -, and relative/absolute paths
void printCd(const vector<string> &args, string &homeDir)
{
if (prevDir.empty())
{
char buf[4096];
if (getcwd(buf, sizeof(buf)))
prevDir = string(buf);
}
if (args.size() > 2)
{
cerr << "cd: Invalid arguments\n";
return;
}
string target;
if (args.size() == 1)
{
target = homeDir;
}
else if (args[1] == "-")
{
if (prevDir.empty())
{
cerr << "cd: OLDPWD not set\n";
return;
}
target = prevDir;
}
else if (args[1] == "~")
{
target = homeDir;
}
else
{
target = args[1];
}
char oldBuf[4096];
string oldDir;
if (getcwd(oldBuf, sizeof(oldBuf)))
oldDir = string(oldBuf);
if (chdir(target.c_str()) != 0)
{
perror("cd");
return;
}
if (args.size() > 1 && args[1] == "-")
{
char newBuf[4096];
if (getcwd(newBuf, sizeof(newBuf)))
cout << newBuf << endl;
}
prevDir = oldDir;
}