Created
December 2, 2025 20:48
-
-
Save neeraj9/785ae7cafedff7cbc1fbd1afddb055a1 to your computer and use it in GitHub Desktop.
C code to list list directories and files with size on Linux simpler version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <dirent.h> | |
| #include <sys/stat.h> | |
| #include <limits.h> | |
| typedef struct { | |
| off_t total; | |
| int depth; | |
| } DirStats; | |
| void list_directory(const char *basepath, DirStats *stats) { | |
| DIR *dir = opendir(basepath); | |
| if (!dir) { | |
| perror("opendir"); | |
| return; | |
| } | |
| struct dirent *entry; | |
| struct stat statbuf; | |
| char fullpath[PATH_MAX]; | |
| while ((entry = readdir(dir)) != NULL) { | |
| // Skip . and .. | |
| if (strcmp(entry->d_name, ".") == 0 || | |
| strcmp(entry->d_name, "..") == 0) { | |
| continue; | |
| } | |
| // Construct full path | |
| snprintf(fullpath, sizeof(fullpath), "%s/%s", basepath, entry->d_name); | |
| // Get file info | |
| if (lstat(fullpath, &statbuf) == -1) { | |
| perror("lstat"); | |
| continue; | |
| } | |
| // Print with indentation based on depth | |
| int indent = stats->depth * 2; | |
| if (S_ISDIR(statbuf.st_mode)) { | |
| printf("%*s๐ %s/\n", indent, "", entry->d_name); | |
| // Recurse into subdirectory | |
| DirStats substats = {0, stats->depth + 1}; | |
| list_directory(fullpath, &substats); | |
| stats->total += substats.total; | |
| } else if (S_ISREG(statbuf.st_mode)) { | |
| printf("%*sโโ %s (%lld bytes)\n", indent, "", | |
| entry->d_name, (long long)statbuf.st_size); | |
| stats->total += statbuf.st_size; | |
| } else if (S_ISLNK(statbuf.st_mode)) { | |
| printf("%*s๐ %s -> (symlink)\n", indent, "", entry->d_name); | |
| } | |
| } | |
| closedir(dir); | |
| } | |
| int main(int argc, char *argv[]) { | |
| if (argc != 2) { | |
| fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]); | |
| exit(EXIT_FAILURE); | |
| } | |
| printf("Scanning: %s\n\n", argv[1]); | |
| DirStats stats = {0, 0}; | |
| list_directory(argv[1], &stats); | |
| printf("\n๐ Total size: %lld bytes (%.2f MB)\n", | |
| (long long)stats.total, stats.total / (1024.0 * 1024.0)); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment