立即查询 HFS 或 APFS 卷上的文件和文件夹总数

Query total number of files and folders on a HFS or APFS volume instantly

macOS 32 位 API 提供了一种查询本地卷上文件和文件夹数量的方法立即,因为此信息直接记录在 HFS 中卷 header,以及 APFS、FAT 和 NTFS 卷,显然。

我喜欢使用 64 位 API 阅读这些相同的书籍,例如如果可能,使用 POSIX 或 BSD 调用,如 fsstatfsctl。不过我找不到。

我曾希望 statfs() 会在其 f_files 结构字段中给我这个值:

 long    f_files;    /* total file nodes in file system */

但是,该值始终是固定的 (0xffffffef),因此无用。

我知道这些值可能不完全准确,但这不是必需的。我只需要扫描全卷时提前大致预测总搜索时间的值即可。

我没有 mac,但在进行快速测试后,它似乎可以在 Linux 上与 hfsplus 一起使用:

[root@tuxpad tmp]# dd if=/dev/zero of=filesystem.img bs=1024 count=102400
102400+0 records in
102400+0 records out
104857600 bytes (105 MB, 100 MiB) copied, 0.130317 s, 805 MB/s
[root@tuxpad tmp]#
[root@tuxpad tmp]# mkfs.hfsplus filesystem.img
Initialized filesystem.img as a 100 MB HFS Plus volume
[root@tuxpad tmp]#
[root@tuxpad tmp]# mount -o loop filesystem.img /mnt/
[root@tuxpad tmp]#
[root@tuxpad tmp]# ./a.out /mnt
f_type=18475
(Total inodes (f_files) = 4294967295
Free inodes (f_ffree) =4294967278
Total no. of files = (f_files - f_ffree) =17
[root@tuxpad tmp]#
[root@tuxpad tmp]# touch /mnt/file{1..100}
[root@tuxpad tmp]#
[root@tuxpad tmp]# ./a.out /mnt
f_type=18475
(Total inodes (f_files) = 4294967295
Free inodes (f_ffree) =4294967178
Total no. of files = (f_files - f_ffree) =117

代码片段:

#include <stdio.h>
#include <stdlib.h>
#include <sys/vfs.h>    /* or <sys/statfs.h> */

int main (int argc, char**argv)
{
        struct statfs buf = {0};
        int ret = 0;

        ret = statfs(argv[1], &buf);
        if (ret) {
                perror("statfs");
                return -1;
        }

        printf("f_type=%llu\n", buf.f_type);
        printf("(Total inodes (f_files) = %llu\n", buf.f_files);
        printf("Free inodes (f_ffree) =%llu\n", buf.f_ffree);
        printf("Total no. of files = (f_files - f_ffree) =%llu\n", buf.f_files -buf.f_ffree);

        return 0;
}

也可以使用FSGetVolumeInfo获取信息。虽然它已被标记为已弃用,但无论如何它仍然适用于 macOS 10.15。可以在头文件 (Files.h) 中找到文档。