-
-
Save AdriDevelopsThings/242c612b2992c7b54b0bb186c02684be to your computer and use it in GitHub Desktop.
My du implementation
This file contains 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> | |
off_t* count_filesize_of_directory(char *path) { | |
DIR *dir = opendir(path); | |
if (dir == NULL) { | |
perror("error while reading directory"); | |
return NULL; | |
} | |
struct dirent *dir_entry; | |
off_t *size = malloc(sizeof(off_t)); | |
if (size == NULL) { | |
perror("out of memory"); | |
return NULL; | |
} | |
while ((dir_entry = readdir(dir)) != NULL) { | |
if (strcmp(dir_entry->d_name, ".") == 0 || strcmp(dir_entry->d_name, "..") == 0) { | |
continue; | |
} | |
size_t complete_path_length = strlen(path) + strlen(dir_entry->d_name) + 2; | |
char* complete_path = malloc(sizeof(char) * complete_path_length); | |
if (complete_path == NULL) { | |
perror("out of memory"); | |
return NULL; | |
} | |
snprintf(complete_path, complete_path_length, "%s/%s", path, dir_entry->d_name); | |
if (dir_entry->d_type != DT_DIR) { | |
struct stat stat_buf; | |
if (stat(complete_path, &stat_buf) != 0) { | |
perror("error while getting stat from file"); | |
return NULL; | |
} | |
*size += stat_buf.st_size; | |
} else if (dir_entry->d_type == DT_DIR) { | |
off_t *d_size = count_filesize_of_directory(complete_path); | |
if (d_size == NULL) { | |
return NULL; | |
} | |
printf("%lld\t%s\n", *d_size, complete_path); | |
*size += *d_size; | |
free(d_size); | |
} | |
free(complete_path); | |
} | |
closedir(dir); | |
return size; | |
} | |
int main(int argc, char* argv[]) { | |
char* directory = "."; | |
if (argc > 1) { | |
directory = argv[1]; | |
} | |
off_t* filesize = count_filesize_of_directory(directory); | |
if (filesize == NULL) { | |
return 1; | |
} | |
printf("%lld\n", *filesize); | |
free(filesize); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment