Image of Modern Operating Systems (3rd Edition)
Image of Android Wireless Application Development
Image of Linux Kernel Development (3rd Edition)
Image of Advanced Programming in the UNIX Environment, Second Edition (Addison-Wesley Professional Computing Series)

Sprintf Portability and Leading Zeros

On some platforms, code such as the following can be used to output a string with leading zeros left padded to a length of 4.

sprintf(*str, "%04s", *pstr);

This works on AIX for example. However if the same code is compiled on Linux using gcc, it outputs leading spaces, padded to a length of 4, instead of leading zeros.

There is no simple way to fix this behavior. This particular usage of leading zero padding with the string format is explicitly undefined in the various C standards. What is outputted depends on a platform’s libraries rather than the compiler. As a result, this code is inherently non-portable.

One workaround is to do something like the following:

int width = 4;
sprintf(str, "%.*d%s", width-strlen(pstr), 0, pstr);

There are many other possible workarounds.

Comments are closed.