Linux Fu: Customizing Printf

Linux Fu: Customizing Printf

When it comes to programming in C and, sometimes, C++, the printf function is a jack-of-all-trades. It does a nice job of quickly writing output, but it can also do surprisingly intricate formatting. For debugging, it is a quick way to dump some data. But what if you have data that printf can’t format? Sure, you can just write a function to pick things apart into things printf knows about. But if you are using the GNU C library, you can also extend printf to use custom specifications. It isn’t that hard, and it makes using custom data types easier.


An Example


Suppose you are writing a program that studies coin flips. Even numbers are considered tails, and odd numbers are heads. Of course, you could just print out the number or even mask off the least significant bit and print that. But what fun is that?


Here’s a very simple example of using our new printf specifier “%H”:



printf("%H %H %H %H
",1,2,3,4);
printf("%1H %1H
",0,1);

When you have a width specification of 1 (like you do in the second line) the output will be H or T. If you have anything else, the output will be HEADS or TAILS.



Easy!


But first, we need to add the %H specifier, and it’s easy. It would be even more straightforward, but the system is very flexible, so there are a few hurdles. The key lies in the printf.h header. This defines several functions that allow you to bend printf to your will.


You have to provide two functions. The first takes an output stream, a structure of information, and a void * to the current printf argument list. The function’s job is to gr ..

Support the originator by clicking the read the rest link below.