In a program I am designing, I am using opendir() to test whether entries under a certain directory are sub-directories or not. This method works fine for the directory itself (.) and the parent directory (..), however it does not work for any sub-directories I manually create.
i.e. it does not work for current_directory/my_sub_directory
One trap I always keep falling into is forgetting to glue back the entry from a readdir to the directory I read it from, i.e. using a relative file name in the wrong (e.g. grandparent) directory.
Ive discovered a better way to test for the presence of sub-directories within folders, however it does not involve the use of opendir()
What I did instead was the following
/*Check if it is current or parent directory*/
if( (strcmp(subfolder_name,".") != 0) && (strcmp(subfolder_name,"..") != 0)
{
/*Check to see if it is a directory by using strrchr()*/
ptr = strrchr(subfolder_name,'.');
/*If strrchr() returns NULL, the current entry
is indeed a sub-folder*/
if(ptr == NULL)
{
/*Do necessary stuff here*/
}
}
opendir() returns a pointer to a dir stream. readdir() is invoked in a loop afterwards to read the contents of the opened dir stream. Each dir entry is passed from readdir() to stat() which stores information in a stat structure. The S_ISDIR() macro can be used to test whether the stat structure is a dir or not. Look at the manpages of opendir() readdir() and stat().