///////////////////////////////////////////////////////////////////////////// // // directories.cpp // Jeff Ondich 5/19/04 // // Simple demonstration of the use of opendir, readdir, closedir, and // lstat to examine the contents of a directory. // ///////////////////////////////////////////////////////////////////////////// #include #include #include #include #include using namespace std; int main( int argc, char *argv[] ) { DIR *directory; struct dirent *entry; struct stat st; if( argc != 2 ) { cerr << "Usage: " << argv[0] << " directoryname" << endl; exit( 1 ); } // Open the directory. if( (directory = opendir( argv[1] )) == NULL ) { cerr << "Can't open directory '" << argv[1] << "'." << endl; exit( 1 ); } // Iterate through the directory's contents. while( (entry = readdir( directory )) != NULL ) { if( lstat( entry->d_name, &st ) != 0 ) { cerr << "Can't collect information about " << entry->d_name << endl; break; } // Print out the directory entry's name, with a type marker // (D=directory, L=link, R=regular, ?=other). if( S_ISDIR( st.st_mode ) ) cerr << "D "; else if( S_ISLNK( st.st_mode ) ) cerr << "L "; else if( S_ISREG( st.st_mode ) ) cerr << "R "; else cerr << "? "; cerr << entry->d_name << endl; } closedir( directory ); return 0; }