Created
July 24, 2022 16:29
-
-
Save okyanusoz/e67acf5afe13875e428a253f030a9365 to your computer and use it in GitHub Desktop.
C code to print the size of file(s) in a human friendly format
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 <ftw.h> | |
#include <sys/stat.h> | |
#include <sys/dir.h> | |
#include <dirent.h> | |
void printbytes(char *filename, long l) | |
{ | |
printf("%s: ", filename); | |
if (l < 1000) | |
{ | |
printf("%ld bytes\n", l); | |
return; | |
} | |
if (l < 1000000) | |
{ | |
printf("%f KB\n", l / 1000.0); | |
return; | |
} | |
if (l < 1000000000) | |
{ | |
printf("%f MB\n", l / 1000000.0); | |
return; | |
} | |
if (l < 1000000000000) | |
{ | |
printf("%f GB", l / 1000000000.0); | |
return; | |
} | |
if (l < 1000000000000000) | |
{ | |
printf("%f TB", l / 1000000000000.0); | |
return; | |
} | |
printf("%f PB", l / 1000000000000000.0); | |
printf("\n"); | |
} | |
long getfilesize(char *path) | |
{ | |
FILE *fp = fopen(path, "r"); | |
if (!fp) | |
{ | |
return -1; | |
} | |
fseek(fp, 0, SEEK_END); | |
long s = ftell(fp); | |
fclose(fp); | |
return s; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
long total = 0; | |
if (argc == 1) | |
{ | |
printf("Usage: %s [file1] [file2] [file3] ...\n", argv[0]); | |
return 1; | |
} | |
for (int i = 1; i < argc; i++) | |
{ | |
char *path = argv[i]; | |
struct stat st; | |
if (stat(path, &st) != 0) | |
{ | |
fprintf(stderr, "Could not open %s, skipping...\n", path); | |
continue; | |
} | |
if (S_ISDIR(st.st_mode)) | |
{ | |
fprintf(stderr, "%s is a directory.\nTo get the size of a directory, please use wildcards.\n", path); | |
continue; | |
} | |
long size = getfilesize(path); | |
if (size == -1) | |
{ | |
fprintf(stderr, "Could not open %s, skipping...\n", path); | |
continue; | |
} | |
printbytes(path, size); | |
total += size; | |
} | |
if(argc > 2) { | |
printbytes("\033[0;34mTotal", total); | |
printf("\033[0m"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment