如何让 readdir 忽略 C/C++ 中的目录?

发布于 2024-08-29 12:55:42 字数 62 浏览 10 评论 0原文

我正在使用 readdir 读取当前库的内容,但我只想处理文件而不是目录。我如何知道我指向的是目录而不是文件?

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 pointing to a directory and not to a file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

始于初秋 2024-09-05 12:55:42

您可以使用 lstatS_ISDIR 宏。

例如,没有错误检查:

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),而不是在出现类型时将其列入黑名单。

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.

撩人痒 2024-09-05 12:55:42
`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";
}
`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";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文