Search code examples
objective-ccprintfnslog

Help with C printf function


I am trying to duplicate NSLog but without all of the unnecessary dates at the beginning. I have tried the following c function (I made myself), but it wont log any other values that are not NSStrings. Please could you tell me how I could do it so that it would log any value?

static void echo(NSString *fmt, ...) {
    printf("<<<<<<<%s>>>>>>>", [fmt UTF8String]);
}

Solution

  • To use variadic argument lists in C you need to use a few macros that are defined in the stdarg.h header file that comes with your compiler.

    here is a detailed explanation of how to write your own printf

    If you just want to pass the arguments to the real printf without further manipulation you can use the vfprintf variant of printf instead but you need to extend the fmt parameter separately:

    static void echo(NSString *fmt, ...)
    {
        va_list args;
        NSString *logfmt = [NSString stringWithFormat: @"<<<<<<<%s>>>>>>>", [fmt UTF8String]];
        va_start (args, fmt);
        vfprintf( stdout, [logfmt UTF8String], args );
        va_end (args);
        [logfmt release];
    }