Created
October 17, 2016 03:02
-
-
Save binand/d33446f7317c9e79331ffd9da62b8446 to your computer and use it in GitHub Desktop.
Locates the largest file (files) in a directory and its subdirectories passed as argument.
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 <ftw.h> | |
| struct currentry { | |
| char **path; | |
| int cnt; | |
| size_t size; | |
| }; | |
| struct currentry ce; | |
| int record_largest(const char *, const struct stat *, int); | |
| int main(int ac, char **av) { | |
| int i = 0; | |
| if (ac < 1) { | |
| fprintf(stderr, "Usage: largest <directory>\n"); | |
| exit(1); | |
| } | |
| ce.cnt = 0; | |
| ce.size = 0; | |
| ce.path = NULL; | |
| ftw(av[1], record_largest, 100); | |
| if (ce.cnt == 0) { | |
| printf("No files found?\n"); | |
| exit(1); | |
| } | |
| printf("\nLargest file size: %lu\n\n", ce.size); | |
| for (i = 0; i < ce.cnt; i++) { | |
| printf("\tFile[%d]: %s\n", i + 1, ce.path[i]); | |
| } | |
| putchar('\n'); | |
| exit(0); | |
| } | |
| int record_largest(const char *fpath, const struct stat *sb, int typeflag) { | |
| int i; | |
| if (typeflag != FTW_F) { | |
| return 0; | |
| } | |
| if (ce.path == NULL) { | |
| ce.size = sb->st_size; | |
| ce.cnt = 1; | |
| ce.path = malloc(sizeof *(ce.path)); | |
| ce.path[0] = malloc(strlen(fpath) + 1); | |
| strcpy(ce.path[0], fpath); | |
| return 0; | |
| } | |
| if (sb->st_size > ce.size) { | |
| for (i = 0; i < ce.cnt; i++) { | |
| free(ce.path[i]); | |
| } | |
| free(ce.path); | |
| ce.size = sb->st_size; | |
| ce.cnt = 1; | |
| ce.path = malloc(sizeof *(ce.path)); | |
| ce.path[0] = malloc(strlen(fpath) + 1); | |
| strcpy(ce.path[0], fpath); | |
| } else if (sb->st_size == ce.size) { | |
| ce.path[ce.cnt] = malloc(strlen(fpath) + 1); | |
| strcpy(ce.path[ce.cnt], fpath); | |
| ce.cnt++; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment