I wanted a low-level C project that touches memory management, recursive filesystem traversal, and platform-specific APIs — so I built a terminal disk usage analyzer from scratch. No external libraries, just the C standard library and OS system calls. What it does Recursively scans a directory using nftw() Reports total / used / available disk space (cross-platform) Lists every file sorted by size (ascending) with a proportional ASCII bar chart === Disk Usage Report === Total: 512.0 GB Used: 210.3 GB Available: 301.7 GB [ ] 2.0 B ./notes.txt [########################################] 50.0 MB ./video.mp4 Enter fullscreen mode Exit fullscreen mode The interesting bugs Bug 1 — realloc without sizeof total_size = total_size * 2; files = realloc(files, total_size); // ❌ bytes, not entries! Enter fullscreen mode Exit fullscreen mode Should be total_size * sizeof(FileEntry). Without it, the buffer shrinks to almost nothing and every write past the original bound corrupts the heap — a great reminder that realloc takes bytes, always. Bug 2 — mixing directories into the file list nftw() calls your callback for every entry — files, directories, symlinks. I had to explicitly filter: if (typeflag != FTW_F) return 0; Enter fullscreen mode Exit fullscreen mode Bug 3 — no cross-platform disk stats statvfs() works great on Linux/macOS but doesn't exist on Windows. Solved with an #ifdef _WIN32 split: GetDiskFreeSpaceExA on Windows, statvfs everywhere else, unified behind one function signature. Bar chart scaling Once all files are captured, I scale each bar relative to the largest file found: int filled = (int)((double) size / (double) max * BAR_WIDTH); Enter fullscreen mode Exit fullscreen mode Then qsort with a custom comparator sorts everything ascending by size before printing. Repo Single C file + CMakeLists, builds on Linux and Windows (MinGW tested): [https://github.com/SecByShresth/Disk-Usage-CLI.git] Would love feedback on the traversal/performance side — currently it walks the entire tree with no depth limit or exclusion list (.git, node_modules, etc.), which is next on my list to fix.
Building a Cross-Platform Disk Usage Analyzer in C
Full Article
Original Source
Read the full article at Dev →KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.