Depends on where you want to implement it you need different approach.

If it's for automatic build system then Lykrug's idea is better.

But if it's for you to change the build number as you progress between commits to vcs, then you'll need to go with my suggestion (or something similar).

As to the failed builds - I wouldn't bother with that, as long as every build has a different number it shouldn't be a problem if it fails or not.