Search code examples
c++stat

cannot distinguish directory from file with stat()


I am trying to list all the files contained in a folder using stat(). However, the folder also contains other folders, whose content I want to be displayed too. My recursion becomes infinite because stat() cannot distinguish a folder from a file. In fact, all files are listed as folders. Any advice?

using namespace std;

bool analysis(const char dirn[],ofstream& outfile)
{
cout<<"New analysis;"<<endl;
struct stat s;
struct dirent *drnt = NULL;
DIR *dir=NULL;

dir=opendir(dirn);
while(drnt = readdir(dir)){
    stat(drnt->d_name,&s);
    if(s.st_mode&S_IFDIR){
        if(analysis(drnt->d_name,outfile))
        {
            cout<<"Entered directory;"<<endl;
        }
    }
    if(s.st_mode&S_IFREG){
        cout<<"Entered file;"<<endl;
    }

}
return 1;
}

int main()
{
    ofstream outfile("text.txt");
    cout<<"Process started;"<<endl;
    if(analysis("UROP",outfile))
        cout<<"Process terminated;"<<endl;
    return 0;
}

Solution

  • I think your error is something else. Each directory listing contains two 'pseudo-directories' (don't know what the official term is) which are '.' the current directory and '..' the parent directory.

    Your code follows those directories so you are getting an infinite loop. You need to change your code to something like this to exclude these pseudo-directories.

    if (s.st_mode&S_IFDIR && 
        strcmp(drnt->d_name, ".") != 0 && 
        strcmp(drnt->d_name, "..") != 0)
    {
        if (analysis(drnt->d_name,outfile))
        {
            cout<<"Entered directory;"<<endl;
        }
    }