This repository has been archived by the owner on Dec 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sfs.c
111 lines (90 loc) · 2.42 KB
/
sfs.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
100
101
102
103
104
105
106
107
108
109
110
111
#include "sfs.h"
#include <string.h>
#include <malloc.h>
struct sfs_entry* sfs_get(struct sfs_entry* root, const char* path)
{
if (!strcmp("/", path)) {
return root;
} else {
char* copy = strdup(path);
char* p = strtok(copy, "/");
struct sfs_entry* entry = root->children;
while (entry) {
if (!strcmp(entry->name, p)) {
/* component found */
p = strtok(NULL, "/");
if (!p) {
/* no more subdirs */
free(copy);
return entry;
} else {
entry = entry->children;
}
} else {
entry = entry->next;
}
}
free(copy);
return NULL;
}
}
struct sfs_entry* sfs_add_child(struct sfs_entry* root, const char* name, int type)
{
struct sfs_entry* entry = malloc(sizeof(struct sfs_entry));
entry->next = NULL;
entry->name = strdup(name);
entry->size = 0;
entry->type = type;
entry->children = NULL;
return sfs_add_child_entry(root, entry);
}
struct sfs_entry* sfs_add_child_entry(struct sfs_entry* root, struct sfs_entry* entry)
{
entry->next = NULL;
if (root->children) {
struct sfs_entry *current = root->children;
while (current->next) {
current = current->next;
}
current->next = entry;
} else {
root->children = entry;
}
return entry;
}
struct sfs_entry* sfs_add_subdirectory(struct sfs_entry* root, const char* name)
{
struct sfs_entry* entry = malloc(sizeof(struct sfs_entry));
entry->next = NULL;
entry->type = sfs_directory;
entry->name = strdup(name);
entry->size = 0;
entry->children = NULL;
return sfs_add_child_entry(root, entry);
}
struct sfs_entry* sfs_get_child_by_name(struct sfs_entry* root, const char* name)
{
struct sfs_entry* entry = root->children;
while (entry) {
if (!strcmp(entry->name, name)) {
return entry;
} else {
entry = entry->next;
}
}
return NULL;
}
struct sfs_entry* sfs_get_child_by_index(struct sfs_entry* root, int index)
{
struct sfs_entry* entry = root->children;
int i = 0;
while (entry) {
if (i == index) {
return entry;
} else {
entry = entry->next;
i++;
}
}
return NULL;
}