Skip to content

Instantly share code, notes, and snippets.

@neeraj9
Last active December 2, 2025 20:23
Show Gist options
  • Select an option

  • Save neeraj9/0e6bed06b246c88e05b3aa3b06b69510 to your computer and use it in GitHub Desktop.

Select an option

Save neeraj9/0e6bed06b246c88e05b3aa3b06b69510 to your computer and use it in GitHub Desktop.
List files and folders with sizes on Linux
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ftw.h>
#include <sys/stat.h>
static off_t total_size = 0;
static off_t total_symbolic_links = 0;
static off_t total_directories_visited = 0;
// Callback function for nftw()
static int process_entry(const char *fpath, const struct stat *sb,
int typeflag, struct FTW *ftwbuf) {
if (typeflag == FTW_F) {
// Regular file
printf("%*s├─ %s (%lld bytes)\n", ftwbuf->level * 2, "",
fpath + ftwbuf->base, (long long)sb->st_size);
total_size += sb->st_size;
} else if (typeflag == FTW_D) {
// Directory (preorder - before contents)
if (ftwbuf->level > 0) {
printf("%*s📁 %s/\n", ftwbuf->level * 2, "",
fpath + ftwbuf->base);
}
} else if (typeflag == FTW_DNR) {
// Directory cannot be read
fprintf(stderr, "Error: Cannot read %s\n", fpath);
} else if (typeflag == FTW_SL) {
// Symbolic link.
++total_symbolic_links;
} else if (typeflag == FTW_DP) {
// Directory, all subdirs have been visited.
++total_directories_visited;
} else {
fprintf(stderr, "Unknown: typeflag = %d\n", typeflag);
}
return 0; // Continue walking
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
exit(EXIT_FAILURE);
}
const char *dirpath = argv[1];
total_size = 0;
printf("Scanning: %s\n\n", dirpath);
// nftw flags:
// FTW_PHYS: Don't follow symlinks
// FTW_DEPTH: Visit files before directories (postorder)
// 10: Max open file descriptors
if (nftw(dirpath, process_entry, 10, FTW_PHYS | FTW_DEPTH) == -1) {
perror("nftw");
exit(EXIT_FAILURE);
}
printf("\n📊 Total size: %lld bytes (%.2f MB)\n",
(long long)total_size, total_size / (1024.0 * 1024.0));
printf("\nTotal symbolic links %lld", (long long)total_symbolic_links);
printf("\nTotal directories visited %lld", (long long)total_directories_visited);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment