diff --git a/fs.c b/fs.c new file mode 100644 index 0000000..03b998e --- /dev/null +++ b/fs.c @@ -0,0 +1,40 @@ +/* + * fs.c + * + * Created on: 20.10.2017 + * Author: julian + */ + +#include "fs.h" + +#include +#include + + +void path_join(struct path *p1, struct path *p2) { + size_t other = p2->len; + + while(other) { + p1->entries = realloc(p1->entries, sizeof(const char*) * (p1->len+1)); + if (p1->entries == NULL) { + // OUT OF MEM, oper incomplete + return; + } + + p1->entries[p1->len] = strdup(p2->entries[p2->len - other]); + + other--; + p1->len++; + } +} + +void free_path(struct path * p) { + while(p->len) { + free(p->entries[p->len-1]); + p->len--; + } + + // free the old array + free(p->entries); +} + diff --git a/fs.h b/fs.h new file mode 100644 index 0000000..11423ba --- /dev/null +++ b/fs.h @@ -0,0 +1,30 @@ +/* + * fs.h + * + * Created on: 20.10.2017 + * Author: julian + */ + +#ifndef FS_H_ +#define FS_H_ + +#include // size_t + +struct path { + char ** entries; + size_t len; + int absolute:1; +}; + + +extern void path_join(struct path *p1, struct path *p2); +extern void free_path(struct path *p); +extern void create_path(struct path * p, const char * fsPath); + + +#include + +// behaves like fopen, but uses the path struct as path +extern FILE * path_fopen(struct path * p, const char * flags); + +#endif /* FS_H_ */ diff --git a/test_path.c b/test_path.c new file mode 100644 index 0000000..64fe793 --- /dev/null +++ b/test_path.c @@ -0,0 +1,74 @@ +/* + * test_path.c + * + * Created on: 20.10.2017 + * Author: julian + */ + + +#include "tests.h" +#include "fs.h" + +#include +#include + +const char * reason_invalid_entry = "invalid entry"; + +void test1() { + init("a/b/c"); + + struct path p = {}; + create_path(&p, "a/b/c"); + if (p.len < 3) { + fail("%d, not enough path splits", p.len); + } + if (p.absolute) { + fail("path should be relative"); + } + if (strcmp(p.entries[0], "a") != 0) { + fail(reason_invalid_entry); + } + if (strcmp(p.entries[1], "b") != 0) { + fail(reason_invalid_entry); + } + if (strcmp(p.entries[2], "c") != 0) { + fail(reason_invalid_entry); + } + + free_path(&p); + pass(); +} + +void test2() { + init("/a/b/c"); + + struct path p = {}; + create_path(&p, "/a/b/c"); + if (p.len != 3) { + fail("%d, not enough path splits", p.len); + } + if (!p.absolute) { + fail("path should be absolute"); + } + + if (strcmp(p.entries[0], "a") != 0) { + fail(reason_invalid_entry); + } + if (strcmp(p.entries[1], "b") != 0) { + fail(reason_invalid_entry); + } + if (strcmp(p.entries[2], "c") != 0) { + fail(reason_invalid_entry); + } + + free_path(&p); + pass(); +} + +int main() { + init("test_path"); + test1(); + test2(); + pass(); +} +