Program & Design Tips, tricks, tutorials, and tools on programming & web design

18Mar/092

Human-readable file size in C

I did a quick search on Google and couldn't find any code that did this in C/C++, so here's my contribution for the day. Just remember the allocate enough space in the buffer -- about 10 chars should be enough.

char* readable_fs(double size/*in bytes*/, char *buf) {
    int i = 0;
    const char* units[] = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
    while (size > 1024) {
        size /= 1024;
        i++;
    }
    sprintf(buf, "%.*f %s", i, size, units[i]);
    return buf;
}

// usage
struct stat info;
char buf[10];
lstat("somefile.txt", &info);
printf("File size: %s\n", readable_fs(info.st_size, buf));
Filed under: C++ 2 Comments
9Mar/091

Extract (almost) any archive type

After getting tired of trying to remember "tar xvzf", I wrote a little script for extracting almost any file type via the linux command-line. You can copy and paste this script into a text editor like gedit and save it to "/usr/local/bin" for convenience. I called mine "untar" since it doesn't seem to be taken. Remember to `chmod +x ` so that you can execute it. You may need to `sudo apt-get install unrar` if you don't already have it. I'm sure you can see how to add other file types from this example.

#!/bin/sh
me=`basename $0`
if [ $# -eq 0 ]; then
    echo "usage: $me <files...>"
fi
for file in $@; do
    bn=`basename $file`
    case $file in
        *.tar)
            tar xvf $file;;
        *.tar.gz|*.tgz|*.tar.Z|*.tar.z)
            tar xvzf $file;;
        *.tar.bz2)
            tar xvjf $file;;
        *.zip)
            unzip $file;;
        *.rar)
            unrar x $file;;
        *)
            echo "$me: $bn: unkown filetype";;
    esac
done
Tagged as: 1 Comment