Snippet of code #1 – Gathering Disk Information in C

One of the people I work with (an excellent fellow, I might add) was grumbling about how he could gather information about the mounted disks on a computer.  He was mucking around with ‘df’ in the command line, and giving serious thought to the business of parsing the result into his program.

I was concerned that this might be rather slow – especially since his program was written in C, and he’d already demonstrated his mettle with a marvellously efficient ring buffer. So this isn’t mere incompetence here – it’s just unfamiliarity with the language and all the wonderful modules that are available.  I offered him the following snippet of code and, since others might encounter the same problem, I offer it here as well.

Firstly, you’ll need to include the necessary module:

#include <sys/statvfs.h>

Then you’ll need to define the structure to store the disk information:

typedef struct _diskInfo
{
   unsigned long size;
   unsigned long used;
   unsigned long free;
   unsigned long blockSize;
   unsigned long blocks;
} diskInfo;

And finally, you’ll need the function to gather this wonderful information for you:

diskInfo diskUsage(char * path,unsigned int function)
{
   struct statvfs buf;
   diskInfo disk;
   unsigned long freeblks;
   int ret;

   ret = statvfs(path,&buf);
   disk.blockSize = buf.f_frsize;
   disk.blocks = buf.f_blocks;
   freeblks = buf.f_bfree;
   disk.size = disk.blockSize * disk.blocks;
   disk.free = disk.blockSize * freeblks;
   disk.used = disk.size - disk.free;

   return disk;
}

I’ll keep publishing snippets until I loose interest.  So this might be part one of an occasional series, or it might be the only one I ever write.

CategoriesUncategorised

One Reply to “Snippet of code #1 – Gathering Disk Information in C”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.