-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectory.cpp
More file actions
104 lines (84 loc) · 2.54 KB
/
Directory.cpp
File metadata and controls
104 lines (84 loc) · 2.54 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "Directory.hpp"
using std::string;
Directory::Directory(Directory* parent, DirectoryItem* current, DirectoryItem* subdir, DirectoryItem* file)
: parent(parent), current(current), subdir(subdir), file(file) {}
Directory* Directory::getParent() const {
return parent;
}
Directory::~Directory() {
// Helper lambda to delete all items in a linked list
auto deleteAllItems = [](DirectoryItem* item) {
while (item != nullptr) {
DirectoryItem* nextItem = item->getNext();
delete item; // Delete the current item
item = nextItem;
}
};
// Delete all files
deleteAllItems(file);
// Delete all subdirectories
deleteAllItems(subdir);
}
void Directory::setParent(Directory* newParent) {
parent = newParent;
}
DirectoryItem* Directory::getCurrent() const {
return current;
}
void Directory::setCurrent(DirectoryItem* newCurrent) {
current = newCurrent;
}
DirectoryItem*& Directory::getSubdir() {
return subdir;
}
void Directory::setSubdir(DirectoryItem* newSubdir) {
subdir = newSubdir;
}
DirectoryItem*& Directory::getFile() {
return file;
}
void Directory::setFile(DirectoryItem* newFile) {
file = newFile;
}
void Directory::addSubdirectory(DirectoryItem* item) {
if (subdir == nullptr) {
subdir = item;
} else {
DirectoryItem* current = subdir;
while (current->getNext() != nullptr) {
current = current->getNext(); // Go to the last item
}
current->setNext(item); // Add the new item to the end of the list
}
}
void Directory::addFile(DirectoryItem* item) {
if (file == nullptr) {
file = item;
} else {
DirectoryItem* current = file;
while (current->getNext() != nullptr) {
current = current->getNext(); // Go to the last item
}
current->setNext(item); // Add the new item to the end of the list
}
}
DirectoryItem* Directory::deleteFileFromDirectory(const string& fileName) {
// Search for the file in the directory
DirectoryItem* item = file;
DirectoryItem** prevItem = &file;
bool fileFound = false;
while (item != nullptr) {
if (item->getItemName() == fileName) {
fileFound = true;
break;
}
prevItem = &(item->getNextRef()); // Get the reference to the next item
item = item->getNext(); // Go to the next item
}
if (!fileFound) {
return nullptr;
}
// Remove the item from the list
*prevItem = item->getNext();
return item;
}