I’m doing simple tests on all files in directory.
But from some reason, sometimes, they behave wrongly?
What’s bad with my code?
using namespace std;
int main() {
string s = "/home/";
struct dirent *file;
DIR *dir = opendir(s.c_str());
while ((file = readdir(dir)) != NULL){
struct stat * file_info = new (struct stat);
stat(file->d_name,file_info);
if ((file_info->st_mode & S_IFMT) == S_IFDIR)
cout << "dir" << endl;
else
cout << "other" << endl;
}
closedir(dir);
}
You made some mistakes, the most important being to call
stat()without checking its return value. I modified your program to this:When I ran it, I got this output:
Now I saw that
statwas called with a filename ofroland, which doesn’t exist in my current working directory. You have to prefix the filenames with the directory name.Your second bug was to allocate a new
struct stateverytime but not freeing the memory after use. By default, C++ doesn’t have garbage collection, so your program would run out of memory soon.