Archive for the ‘ C/C++ ’ Category

Creating Custom printf() Wrappers

Sitting at my desk hacking away at a project in C, I began to think back to the good ol’ days of last summer when I was knee-deep in Flex work. Now don’t get me wrong, I like lower-level C code as much as the next guy… who… well, likes lower-level C code. But there were certain niceties about ActionScript 3 that I just miss in times like these.  One of those, of course, was trace().

Sure, printf() works fine for quickly spitting out some debugging information.  But golly, it sure would be nice to add a custom prefix to those messages, maybe even have them print to stderr while I’m at it. My desire for my buddy trace() got the best of me, and after some brief searching, I found a way to create my own custom printf() wrapper functions.

The technique is rather simple.  Declare a function that accepts a format string and a varying number of further arguments.  Pass said string and arguments to fprintf.  Do anything else desired before and after.

Here’s how to do it in C/C++:

#include <stdio.h>
#include <stdarg.h>

void trace( const char* format, ... ) {
    va_list args;
    fprintf( stderr, "[Debug] " );
    va_start( args, format );
    vfprintf( stderr, format, args );
    va_end( args );
    fprintf( stderr, "\n" );
}

And here’s the PHP equivalent:

function trace() {
    $args = func_get_args();
    $format = array_shift( $args );
    printf( '[Debug] ' );
    vprintf( $format, $args );
    printf( "\n" );
}

Not too shabby.  I ended up creating three different functions for this particular project: info(), error(), and trace().  The nice part is that I can now conditionally control whether or not these functions actually output anything via command line arguments. All that’s left is to add macros to automatically add the filename and line numbers to the output.

I whipped up a couple of tutorials over at Ozzu coving this in more detail. The C and PHP versions of the tutorial can be found below, respectively.
Writing a Custom printf() Wrapper Function in C
Writing a Custom printf() Wrapper Function in PHP

Update:
It turns out I wanted the filename and line numbers afterall, so I went ahead an added a macro (in C) to get the job done. Change the name of the function to _trace() and add two more arguments, so that your function now looks like this:

#define trace(...) _trace(__FILE__, __LINE__, __VA_ARGS__)

void _trace( char* filename, int line, const char* format, ... ) {
    va_list args;
    fprintf( stderr, "[%s:%d] " );
    va_start( args, format );
    vfprintf( stderr, format, args );
    va_end( args );
    fprintf( stderr, "\n" );
}

Every call to trace() will now print out the filename and line number of the trace call, followed by the formatted message.

nf – A Simple Number Format Utility

One of the projects I’m working on requires me to switch between decimal and hexadecimal formats for values that I’m dealing with.  I found myself using Google quite a bit to convert between number formats, but after a day or two of constantly opening my web browser to do this, it was getting to be a pain.

I decided to write a quick utility that I could use from the command line to view a number in all three formats.  Hence, I present you with nf, short for ‘number format’:

int main( int argc, char* argv[] ) {
    if( argc != 2 ) {
        printf( "usage: %s <number>\n", argv[0] );
        exit( 0 );
    }
    long int num = strtol( argv[1], 0x0, 0 );
    printf( "DEC: %ld\nOCT: %lo\nHEX: %lX\n", num, num, num );
}

Just compile it with your favorite C compiler, toss it in /usr/local/bin (or any other directory of your choice in your PATH), and you’re good to go. It generates output like the following:

$ nf 42
DEC: 42
OCT: 52
HEX: 2A

The argument passed to nf can be in decimal, octal, or hex format; strtol() automatically determines which format you’re using. Decimal numbers begin with any digit 1-9, octal numbers begin with a 0, and hex numbers begin with 0x. Thus, the utility can be used to convert between all three formats.

Three New C++ Tutorials

I write some introductory tutorials covering various programming topics for Ozzu.com from time to time.  At the moment I have written three C++ tutorials, which can be found below.

Defining and Overloading Operators in C++
C++ Exceptions
C++ Classes, Part 1

I always welcome feedback on these, either here or on the forums.