1

我的目标是计算目录中的文件数。在四处搜索之后,我发现了一段代码,它遍历目录中的每个文件。但问题是它循环了额外的时间,更准确地说是额外循环了 2 次。

因此对于

int main(void)
{   
  DIR           *d;
  struct dirent *dir;  
  char *ary[10000];
  char fullpath[256];  
  d = opendir("D:\\frames\\");
  if (d)
  {    
   int count = 1;
    while ((dir = readdir(d)) != NULL)
    {  
       snprintf(fullpath, sizeof(fullpath), "%s%d%s", "D:\\frames\\", count, ".jpg");
       int fs = fsize(fullpath);
       printf("%s\t%d\n", fullpath, fs); // using this line just for output purposes
      count++;      
    }      
    closedir(d);
  }
  getchar();
  return(0);
}

我的文件夹包含 500 个文件,但输出显示到 502在此处输入图像描述

更新

我将代码修改为

struct stat buf;
if ( S_ISREG(buf.st_mode) ) // <-- I'm assuming this says "if it is a file"
{
  snprintf(fullpath, sizeof(fullpath), "%s%d%s", "D:\\frames\\", count, ".jpg");
  int fs = fsize(fullpath);
  printf("%s\t%d\n", fullpath, fs);
}

但我得到了storage size of "buf" isn't known。我也尝试过struct stat buf[100],但这也无济于事。

4

2 回答 2

1

正如评论中所指出的,您还将获得两个名为.and的目录..,这会影响您的计数。

在 Linux 中,您可以使用 的d_type字段将struct dirent它们过滤掉,但文档说:

POSIX.1 规定的唯一结构中的唯一字段是:d_name[],未指定大小,在NAME_MAX终止空字节之前最多有字符;和(作为 XSI 扩展)d_ino。其他字段未标准化,并非在所有系统上都存在;有关更多详细信息,请参见下面的注释。

因此,假设您在 Windows 上,您可能没有d_type. 然后您可以改用其他调用,例如stat(). 当然,您也可以根据名称进行过滤,但如果您想跳过目录,这是一个更强大和更通用的解决方案。

于 2013-02-20T08:45:43.177 回答
0

您需要在要获取信息的文件名上调用_stat()/ stat()

#include <sys/types.h>
#include <sys/stat.h>

#ifdef WINDOWS
#  define STAT _stat
#else
#  define STAT stat
#endif

...

char * filename = ... /* let it point to some file's name */

struct STAT buffer = {0};
if (STAT(filename, &buffer)
  ... /* error */
else
{
  if (S_ISREG(buffer.st_mode))
  {
    ... /* getting here, means `filename` referrs to a ordinary file */
  }
}
于 2013-02-20T09:02:10.463 回答