我正在阅读当前库的内容readdir
,但我只想处理文件而不是目录。我怎么知道我指向的是目录而不是文件?
问问题
5158 次
2 回答
2
例如没有错误检查:
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),而不是在出现类型时将其列入黑名单。
于 2010-04-16T22:16:52.933 回答
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";
}
于 2016-11-18T20:48:49.303 回答