2

stat() を使用して、フォルダーに含まれるすべてのファイルを一覧表示しようとしています。ただし、フォルダーには他のフォルダーも含まれており、その内容も表示したい. stat() はフォルダーとファイルを区別できないため、再帰は無限になります。実際、すべてのファイルはフォルダーとしてリストされます。何かアドバイス?

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;
}
4

2 に答える 2

2

あなたのエラーは別のものだと思います。各ディレクトリのリストには、「.」である 2 つの「疑似ディレクトリ」(正式な用語は不明) が含まれています。現在のディレクトリと「..」親ディレクトリ。

コードはこれらのディレクトリに従うため、無限ループが発生します。これらの擬似ディレクトリを除外するには、コードを次のように変更する必要があります。

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;
    }
}
于 2013-05-01T06:55:02.040 に答える