@@ -20,7 +20,10 @@ File::File(const char* path)
2020 rewind (f);
2121
2222 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+ }
2427 fclose (f);
2528}
2629Dir::Dir (const char * path)
@@ -80,34 +83,62 @@ void FileSys::add_dir(Dir& dvec)
8083 strcat (cwd_buffer, dvec.name .c_str ());
8184
8285 // 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+ }
8492
8593 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)) ;
9098 }
99+
100+ std::vector<std::string> sub_dirs;
101+ std::vector<std::string> sub_files;
102+
91103 struct dirent * ent;
92104 while ((ent = readdir (dir)) != nullptr )
93105 {
94106 std::string name (ent->d_name );
95107 if (name == " .." || name == " ." ) continue ;
96108
97109 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));
100111 }
101112 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));
107114 }
108115 }
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+
109137 // 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+ }
111142}
112143
113144void FileSys::gather (const char * path)
0 commit comments