【问题标题】:Geting numbers of files in specific directory in Linux获取Linux中特定目录中的文件数
【发布时间】:2013-05-31 14:12:50
【问题描述】:

是否有没有迭代 readdir(3) 的特定目录中的文件总数?

我的意思只是特定目录的直接成员。

似乎获取文件数量的唯一方法是重复调用 readdir(3) 直到它返回零。

还有其他方法可以得到 O(1) 中的数字吗?我需要一个适用于 Linux 的解决方案。

谢谢。

【问题讨论】:

  • 为什么O(1)如此重要?
  • 其实我只是想知道 O(1) 是否可行。我想知道有没有更好的方法来获取计数,比较普通的 opendir/readdir*/closedir。

标签: linux file readdir


【解决方案1】:

scandir() 示例,需要dirent.h:

struct dirent **namelist;
int n=scandir(".", &namelist, 0, alphasort);   //  "."  == current directory.
if (n < 0)
{
    perror("scandir");
    exit(1);
}
printf("files found = %d\n", n);
free(namelist);

【讨论】:

  • scandir(3) 手册页包含 “scandir() 函数扫描目录 dirp,在每个目录条目上调用 filter()。” 所以不,这将是 O(n) 而不是 O(1)。我不认为有这样做的 O(1) 方法。
【解决方案2】:

我认为在 O(1) 中是不可能的。 想想inode结构。没有任何线索。

但如果可以获取文件系统中的文件数量, 你可以使用 statvfs(2)。

#include <sys/vfs.h>    /* or <sys/statfs.h> */
int statfs(const char *path, struct statfs *buf);


struct statfs {
               __SWORD_TYPE f_type;    /* type of file system (see below) */
               __SWORD_TYPE f_bsize;   /* optimal transfer block size */
               fsblkcnt_t   f_blocks;  /* total data blocks in file system */
               fsblkcnt_t   f_bfree;   /* free blocks in fs */
               fsblkcnt_t   f_bavail;  /* free blocks available to
                                          unprivileged user */
               fsfilcnt_t   f_files;   /* total file nodes in file system */
               fsfilcnt_t   f_ffree;   /* free file nodes in fs */
               fsid_t       f_fsid;    /* file system id */
               __SWORD_TYPE f_namelen; /* maximum length of filenames */
               __SWORD_TYPE f_frsize;  /* fragment size (since Linux 2.6) */
               __SWORD_TYPE f_spare[5];
};

您可以通过 f_files - f_ffree 轻松获取文件数量。

顺便说一句,这是一个非常有趣的问题。所以我投了赞成票。

【讨论】:

    【解决方案3】:

    在 shell 脚本中非常简单

    ll directory_path | wc -l 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-12
      • 2023-03-28
      • 2014-12-29
      • 2012-07-28
      • 1970-01-01
      • 2013-01-16
      • 2018-07-23
      • 2010-11-04
      相关资源
      最近更新 更多