我正在使用readdir
阅读当前库的内容,但我想只处理文件而不是目录。我怎么知道我指的是目录而不是文件?
谢谢
答案 0 :(得分:1)
E.g。没有错误检查:
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))
{
...
}
编辑:修复了在lstat路径中包含目录(每个el.pescado)。正如R Samuel Klatchko所指出的,您可能希望采用白名单方法(S_ISREG),而不是将类型列入黑名单。
答案 1 :(得分:0)
`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";
}