How do i get readdir ignore directories in C/C++?
I am reading the content of the current library with readdir
, but I would like to treat only files and not directories. How do I know that I am poi开发者_开发知识库nting to a directory and not to a file?
You can use lstat, and the S_ISDIR macro.
E.g. without error-checking:
struct stat buffer;
int status;
char path[PATH_MAX];
DIR *dir = opendir(dir_name);
...
struct dirent *de = readdir(dir);
sprintf(path, "%s/%s", dir_name, de->d_name);
status = lstat(path, &buffer);
if(S_ISDIR(buffer.st_mode))
{
...
}
EDIT: Fixed to include directory in lstat path (per el.pescado). As noted by R Samuel Klatchko, you may want to take a whitelist approach (S_ISREG) instead of blacklisting types as they come up.
`void DirectryNFileCount(const char * FileDir)
{
DIR *dir;
int filecount;
int dircount;
struct dirent *direntry;
if ((dir = opendir (FileDir)) == NULL)
{
/*Error code*/
}
while((direntry = readdir (dir)) != NULL)
{
if(direntry->d_type==DT_DIR)
dircount++;
/*do something with directries */
}
else
{
filecount++;
std::cout<<"Files Names"<<direntry->d_name<<std::endl;
}
}
std::cout<<"THIS Directory has "<<filecount<<" FILES and "<<dircount<< " DIRECTORIES";
}
精彩评论