@@ -20,7 +20,10 @@ File::File(const char* path)
20
20
rewind (f);
21
21
22
22
this ->data = std::unique_ptr<char []> (new char [size], std::default_delete<char []> ());
23
- fread (this ->data .get (), this ->size , 1 , f);
23
+ size_t actual = fread (this ->data .get (), this ->size , 1 , f);
24
+ if (actual != 1 ) {
25
+ throw std::runtime_error (" diskbuilder: Could not read from file " + std::string (path));
26
+ }
24
27
fclose (f);
25
28
}
26
29
Dir::Dir (const char * path)
@@ -80,34 +83,62 @@ void FileSys::add_dir(Dir& dvec)
80
83
strcat (cwd_buffer, dvec.name .c_str ());
81
84
82
85
// printf("*** Entering %s...\n", cwd_buffer);
83
- chdir (cwd_buffer);
86
+ int res = chdir (cwd_buffer);
87
+ // throw immediately when unable to read directory
88
+ if (res < 0 ) {
89
+ fprintf (stderr, " Unable to enter directory %s\n " , cwd_buffer);
90
+ throw std::runtime_error (" Unable to enter directory " + std::string (cwd_buffer));
91
+ }
84
92
85
93
auto * dir = opendir (cwd_buffer);
86
- if (dir == nullptr )
87
- {
88
- printf ( " Could not open directory: \n -> %s\n " , cwd_buffer);
89
- return ;
94
+ // throw immediately when unable to open directory
95
+ if (dir == nullptr ) {
96
+ fprintf (stderr, " Unable to open directory %s\n " , cwd_buffer);
97
+ throw std::runtime_error ( " Unable to open directory " + std::string (cwd_buffer)) ;
90
98
}
99
+
100
+ std::vector<std::string> sub_dirs;
101
+ std::vector<std::string> sub_files;
102
+
91
103
struct dirent * ent;
92
104
while ((ent = readdir (dir)) != nullptr )
93
105
{
94
106
std::string name (ent->d_name );
95
107
if (name == " .." || name == " ." ) continue ;
96
108
97
109
if (ent->d_type == DT_DIR) {
98
- auto & d = dvec.add_dir (ent->d_name );
99
- add_dir (d);
110
+ sub_dirs.push_back (std::move (name));
100
111
}
101
112
else {
102
- try {
103
- dvec.add_file (ent->d_name );
104
- } catch (std::exception & e) {
105
- fprintf (stderr, " %s\n " , e.what ());
106
- }
113
+ sub_files.push_back (std::move (name));
107
114
}
108
115
}
116
+ // close directory before adding more folders and files
117
+ res = closedir (dir);
118
+ if (res < 0 ) {
119
+ throw std::runtime_error (" diskbuilder: Failed to close directory" );
120
+ }
121
+
122
+ // add sub directories
123
+ for (const auto & dirname : sub_dirs) {
124
+ auto & d = dvec.add_dir (dirname.c_str ());
125
+ add_dir (d);
126
+ }
127
+ // add files in current directory
128
+ for (const auto & filename : sub_files)
129
+ {
130
+ try {
131
+ dvec.add_file (filename.c_str ());
132
+ } catch (std::exception & e) {
133
+ fprintf (stderr, " %s\n " , e.what ());
134
+ }
135
+ }
136
+
109
137
// pop work dir
110
- chdir (pwd_buffer);
138
+ res = chdir (pwd_buffer);
139
+ if (res < 0 ) {
140
+ throw std::runtime_error (" diskbuilder: Failed to return back to parent directory" );
141
+ }
111
142
}
112
143
113
144
void FileSys::gather (const char * path)
0 commit comments