vrfileman

view src/fs.cc @ 1:9e3d77dad51b

moving on...
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 31 Jan 2015 20:01:35 +0200
parents
children 282da6123fd4
line source
1 #include <stdio.h>
2 #include <string.h>
3 #include <ctype.h>
4 #include <errno.h>
5 #include <alloca.h>
6 #include <unistd.h>
7 #include <dirent.h>
8 #include "fs.h"
10 static char *clean_path(char *path);
11 static char *filename(char *path);
13 FSNode::FSNode()
14 {
15 init();
16 }
18 FSNode::~FSNode()
19 {
20 destroy();
21 }
23 void FSNode::init()
24 {
25 path = name = 0;
26 parent = 0;
27 expanded = false;
28 uid = gid = mode = 0;
29 }
31 void FSNode::destroy()
32 {
33 delete [] path;
34 children.clear();
35 init();
36 }
38 void FSNode::destroy_tree()
39 {
40 for(size_t i=0; i<children.size(); i++) {
41 children[i]->destroy_tree();
42 delete children[i];
43 }
44 destroy();
45 }
47 void FSNode::set_path(const char *path)
48 {
49 delete [] this->path;
51 char *buf = new char[strlen(path) + 1];
52 strcpy(buf, path);
54 char *tmp = clean_path(buf);
55 if(tmp == buf) {
56 this->path = tmp;
57 } else {
58 this->path = new char[strlen(tmp) + 1];
59 strcpy(this->path, tmp);
60 delete [] buf;
61 }
63 name = filename(this->path);
64 }
66 void FSNode::set_name(const char *name)
67 {
68 delete [] path;
70 if(parent) {
71 char *path = new char[strlen(name) + strlen(parent->path) + 2];
72 sprintf(path, "%s/%s", parent->path, name);
73 set_path(path);
74 } else {
75 path = this->name = new char[strlen(name) + 1];
76 strcpy(path, name);
77 }
78 }
80 #if 0
81 FSDir *create_fsdir(const char *path)
82 {
83 char *pathbuf;
85 FSDir *node = new FSDir;
86 node->name = std::string(filename(path));
88 DIR *dir = opendir(path);
89 if(!dir) {
90 fprintf(stderr, "failed to open dir: %s: %s\n", path, strerror(errno));
91 return 0;
92 }
94 pathbuf = (char*)alloca(strlen(path) + NAME_MAX + 2);
96 struct dirent *ent;
97 while((ent = readdir(dir))) {
98 sprintf(pathbuf, "%s/%s", path, ent->d_ent);
100 struct stat st;
101 if(stat(pathbuf, &st) == -1) {
102 fprintf(stderr, "failed to stat: %s: %s\n", pathbuf, strerror(errno));
103 continue;
104 }
106 if(S_ISDIR(st.st_type)) {
107 FSDir *subdir = new FSDir;
108 subdir->name = std::string(ent->d_ent);
109 add_subdir(node, subdir);
110 } else {
111 FSFile *file = new FSFile;
112 file->name = std::string(ent->d_ent);
113 file->parent = node;
114 }
115 }
116 }
117 #endif
119 static char *clean_path(char *path)
120 {
121 while(*path && isspace(*path)) {
122 path++;
123 }
125 char *end = path + strlen(path) - 1;
126 while(end >= path && isspace(*end)) {
127 *end-- = 0;
128 }
130 char *ptr = path - 1;
131 while(*++ptr) {
132 if(*ptr == '\\') {
133 *ptr = '/';
134 }
135 }
136 return path;
137 }
139 static char *filename(char *path)
140 {
141 char *ptr = strrchr(path, '/');
142 if(ptr) {
143 return ptr + 1;
144 }
145 return path;
146 }