c - 我如何获得C中目录的大小?

标签 c size posix directory

是否有一个 POSIX 函数可以给出目录(包括所有子文件夹)的大小,大致相当于“du -s somepath”?

最佳答案

$ man nftw

NAME

ftw, nftw - file tree walk

DESCRIPTION

ftw() walks through the directory tree that is located under the directory dirpath, and calls fn() once for each entry in the tree. By default, directories are handled before the files and subdirectories they contain (pre-order traversal).

CONFORMING TO

POSIX.1-2001, SVr4, SUSv1.

简单例子

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

static unsigned int total = 0;

int sum(const char *fpath, const struct stat *sb, int typeflag) {
    total += sb->st_size;
    return 0;
}

int main(int argc, char **argv) {
    if (!argv[1] || access(argv[1], R_OK)) {
        return 1;
    }
    if (ftw(argv[1], &sum, 1)) {
        perror("ftw");
        return 2;
    }
    printf("%s: %u\n", argv[1], total);
    return 0;
}

关于c - 我如何获得C中目录的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/472697/

相关文章:

lua - 使用 Corona SDK 的不同屏幕尺寸

android - 移植 Windows 线程以在 Android 操作系统上运行

Posix 共享内存与映射文件

在没有数组的情况下将字符串转换为十进制

google-chrome - 谷歌浏览器中的最大磁盘缓存大小

c - 根据子元素的内容使用 XPath 过滤 XML

android - 如何修复位图大小超出 VM 预算的错误

c++ - 使用 g++ 在 AIX 上编译 pthread.h 东西

c - C 中的 UNIX 域套接字编程,打印问题

C 程序取整数(无论它是素数还是非素数)