Skip to content

Instantly share code, notes, and snippets.

@krisk0
Created July 1, 2026 05:35
Show Gist options
  • Select an option

  • Save krisk0/8539f80dcbc475a7670a44baa4aa21a9 to your computer and use it in GitHub Desktop.

Select an option

Save krisk0/8539f80dcbc475a7670a44baa4aa21a9 to your computer and use it in GitHub Desktop.
Calculate sum of files sizes, ingoring symbolic links
#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static uint64_t total_size = 0;
static uint64_t file_count = 0;
static int calc_size(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) {
// We are only interested in regular files (ignore directories, symlinks, etc.)
if (tflag == FTW_F) {
total_size += sb->st_size;
file_count++;
}
return 0;
}
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: %s <directory>\n", argv[0]);
exit(EXIT_FAILURE);
}
// 20 concurrent file descriptors is a safe and standard limit
if (nftw(argv[1], calc_size, 20, FTW_PHYS) == -1) {
perror("nftw");
exit(EXIT_FAILURE);
}
printf("Total files: %llu\n", (unsigned long long)file_count);
printf("Total real size: %llu = %1.2e bytes\n", (unsigned long long)total_size, (double)total_size);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment