time_t and printf

The bane of my existence is work where I use c++ primarily with MFC.

Now today I have come up to one or the most strange occurrence while debugging the database code in our product. I was formatting a string with sprintf and all of my time values were being formatted as “(null)“.

I know we should really be using parameterized queries but this is legacy code created by PC software guys, and I really don’t know if ODBC supports it in a database agnostic way.

Now we have been using Visual Studio 2005 for years but this code has not been working for years, the problem showed up around the database purging code.

When looking in the debugger at the formed SQL I noticed “(null)” showing up instead the numbers I was expecting.

It turns out we were using time_t as the type being fed into sprintf which under this version of Visual C++ is actually a 64-bit integer, or unsinged long long.

So the solution to this rather strange error in formatting is also quite strange, as in how do you format a unsinged long long into sprintf. Well it’s rather simple just add another formatter charter so if you have a signed long long use %lld or if you have a unsinged long long use %llu.

I hope you don’t get tripped up like I did. And if you were wondering why there was “(null)” in the string it’s because the next token was a string, %s, and intel architeture is little endian making the upper 4 bytes all zero, ie null.

Leave a Reply