You made some mistakes, the most important being to call stat()
without checking its return value. I modified your program to this:
#include <cstdio>
#include <dirent.h>
#include <iostream>
#include <string>
#include <sys/stat.h>
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;
if (stat(file->d_name, &file_info) == -1) {
perror("stat");
return 1;
}
if (S_ISDIR(file_info.st_mode))
cout << "dir " << file->d_name << endl;
else
cout << "other " << file->d_name << endl;
}
closedir(dir);
}
When I ran it, I got this output:
$ ./a.exe
dir .
dir ..
stat: No such file or directory
Now I saw that stat
was called with a filename of roland
, 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 stat
everytime but not freeing the memory after use. By default, C++ doesn't have garbage collection, so your program would run out of memory soon.