Friday, October 23, 2009

sizeof/bsizeof

I thought it was about time that I make a few convenient changes to the old sizeof utility. The primary change here is adding support of printing either bytes (as bsizeof, which is useful for piping to sort -k1nr) or size in larger units as appropriate (as sizeof).

sizeof.c

#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <libgen.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>

off_t getsize(const char * path) {
off_t ret = 0;
struct stat info;
struct dirent * file;
DIR * dirinfo;
char d_name[PATH_MAX];
size_t pathlen = strlen(path);
char * app = d_name + pathlen + 1;
if(pathlen < PATH_MAX) {
strcpy(d_name, path);
strcat(d_name, "/");
if(!stat(path, &info)) {
if(S_ISREG(info.st_mode))
ret = info.st_size;
else if(S_ISDIR(info.st_mode)) {
dirinfo = opendir(path);
while((file = readdir(dirinfo)) != NULL) {
if(strcmp(".", file->d_name) && strcmp("..", file->d_name) && pathlen + file->d_reclen + 1 < PATH_MAX) {
strcpy(app, file->d_name);
ret += getsize(d_name);
}
}
closedir(dirinfo);
}
}
}
return ret;
}
int compute_size_string(char * str, off_t size) {
if(size > (1 << 30))
sprintf(str, "%.2lf GiB", ((double) size) / ((double)(1 << 30)));
else if(size > (1 << 20))
sprintf(str, "%.2lf MiB", ((double) size) / ((double)(1 << 20)));
else if(size > (1 << 10))
sprintf(str, "%.2lf kiB", ((double) size) / ((double)(1 << 10)));
else
sprintf(str, "%lu B", size);
return 0;
}
void print_size_computed(off_t size, const char * name) {
char size_string[1024];
compute_size_string(size_string, size);
printf("%-10s %s\n", size_string, name);
}
void print_size(off_t size, const char * name) {
printf("%-40lu %s\n", size, name);
}

int main(int argc, char ** argv) {
int i;
off_t size;
char * bname = basename(argv[0]);
void (* handler)(off_t, const char *) = strcmp(bname, "bsizeof") ? &print_size_computed : &print_size;
for(i = 1; i < argc; i++) {
size = getsize(argv[i]);
if(size)
handler(size, argv[i]);
}
return 0;
}
Post a Comment