Memention Blog

That old thing

Sometimes I stumble over a piece of code that makes me smile.

When we became a three person company in 2004 the need for some time tracking tool increased. Before we used an excel sheet for this. I had already a small server at home which I had a static ip adress for. So, said and done, I wrote a small tool in C that feed out minimal html pages and that could receive and handle form posts. I just lay the time entries in a simple file with fixed records sizes.

I am pretty lazy so all this was written in a very short way. But I also wanted a way to sort the entries, but without writing to much code. So instead of writing anything I thought about doing this thing also in a very short way. The idea wasn’t apparent at first so I needed to think about it first. I felt there should be an easy way to do just that, sort a simple file with fixed record sizes. But then I got the idea and it was so simple and it made me smile. In short it can be described as; access the file with mmap(..) and sort the entries with qsort(..) and you are done. For those who don’t know what mmap(..) does I might add that it will give you access to a file though a pointer in memory. You don’t need to read the file, the virtual memory handling takes care of loading the file, you just access it as it was memory. So, then to sort the file is just as easy as calling the function qsort(..). You don’t even need to save the file, the virtual memory handling will take care of that for you. Me smile. The verbatim code from my time tracker is below.

void sort_time_track_db(time_track_db *db) {
  void *mptr;
  struct stat sb;
  if (fstat(fileno((FILE*)db->userdata), &sb))
  mptr = mmap(NULL, /* hint */
              PROT_READ | PROT_WRITE,
              0);   /* offset */
  qsort(mptr + sizeof(time_track_db) - sizeof(time_track_entry),
  munmap(mptr, sb.st_size);

Today, six years later I happened to show some new collegues the time tracking tool. They are Ruby developers so when I tried to explain this thing I saw they didn’t get it. But I thought I could share this little gem for you all. I still smile when I see that snippet.

By Edward Patel, 04 May 2011

Show comments


Throwing pebbles12 Jul 2013
Provision this!30 Aug 2012
Break what?18 Aug 2011
That old thing04 May 2011
Removing a Step15 May 2010
Make It Work22 Feb 2010
KISS server31 Jan 2010
tig on Mac12 Dec 2009
The XML Runner31 Oct 2009
Get some software from Memention
Powered by Jekyll and Disqus.
Copyright © 2010-2013 Memention AB