lstat() creates an infinite loop

#include <string>
#include <iostream>
#include <list>
#include <sys/stat.h>
#include <errno.h>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
#define each(I)\
for(typeof((I).begin()) it = (I).begin(); it != (I).end(); ++it )

int walk(string root)
{
//Create a list of names of files
DIR * dirp; //open DIR

if( ! ( dirp = opendir( root.c_str()))) {
cerr << "Cannot open directory " << root << ".\n";

return -1;
}
list <string> files; //read names into st ring list, "files"
while( dirent * dp = readdir(dirp)) {
cout << dp->d_name << endl;
files.push_back(dp->d_name);
}
closedir(dirp); //close DIR asap

cout << root << ":" << endl; //emit header
cout <<"total " << (sizeof(files) / 1024)<< endl; //output the size of the file.

//lstat and report on each file, creating list of subdirectories
list <string> hardSubdirectories ;
files.sort();
each(files) {
string filename = root + "/" + *it;
struct stat st;

if (lstat(filename.c_str() ,&st)) continue;


//my program goes into
// an infinite loop after this command ****
// it looks like ././././././././././././././././././././


cout << st.st_mode << endl;
cout << st.st_atime << endl;
cout << st.st_dev << endl;
cout << st.st_uid << endl;

//if this file is a hard-linked subdirectories, add it to list
if( S_ISDIR ( st.st_mode) && ! S_ISLNK( st.st_mode) ){
hardSubdirectories.push_back(filename);
}
}

//Recurse through the hard_linked subdirectories.
each(hardSubdirectories) {
cout << endl;
walk(*it);
}

return 0; //return success
}

int main(int argc , char* argv [])
{
return walk(argc > 1 ? argv [1] : ".");
}
Topic archived. No new replies allowed.