11

In Xcode Organizer, Console - I can read the NSLog output, but not printf(). Is this possible to read printf() result on the real device, the same like in simulator?

Cœur
  • 37,241
  • 25
  • 195
  • 267
theWalker
  • 2,022
  • 2
  • 18
  • 27
  • It might help if you explain why you want to do this? Why do you need to use printf instead of NSLog()? Is it because you are using a library that contains printf() statements? – Nick Lockwood Jan 19 '12 at 11:03
  • 2
    Because the biggest part of my code it's C code. The universal one, runs under windoz, droid, symbian, iOS etc. And printf() work under iOS simulator, in XCode. – theWalker Jan 19 '12 at 11:07

4 Answers4

18

Easiest solution would be to overload printf function globally in your project and replace it with NSLog output

int printf(const char * __restrict format, ...)
{ 
    va_list args;
    va_start(args,format);    
    NSLogv([NSString stringWithUTF8String:format], args) ;    
    va_end(args);
    return 1;
}
Sohaib
  • 10,941
  • 9
  • 32
  • 34
  • Sohaib, big thanks. This solution work perfectly, and I can leave all of the C code without any changes:) – theWalker Jan 19 '12 at 12:36
10

As Nick Lockwood said in one of the comments above, printf prints to stdout but NSLog prints to stderr. You can use fprintf to print to stderr (the Xcode console) instead of using printf, like this:

fprintf(stderr, "This prints to the Xcode debug console");
Swindler
  • 802
  • 10
  • 9
  • @Sergei works for me now, on XCode 9.2. Notice that NSLog adds some extra info to the output as a prefix. However fprintf logs only what you pass as a parameter. Also fprintf doesn't print a \n by itself. – Rudolf Real Feb 07 '18 at 22:07
4

You can run the following command to print only to device's console:

syslog(LOG_WARNING, "log string");

You will also need to #include <sys/syslog.h> for syslog and LOG_WARNING to be explicitly declared

Elviss Strazdins
  • 1,404
  • 14
  • 30
-1

Skippy,printf() is the output statement for c not for Objective C,SO in real device also printf() is not work.

user1157838
  • 131
  • 1
  • 1
  • 7
  • Objective-C is a strict superset of C, so printf() very much works as documented. But NSLog() behind the scenes does more than printf(), which might be why Skippy is having trouble. – Conrad Shultz Jan 19 '12 at 11:06
  • I believe the problem is actually that printf prints to stdout, whereas NSLog prints to stderr. – Nick Lockwood Jan 19 '12 at 12:35
  • 3
    Nick, fprintf(stderr, format, args); not work under XCode Organizer's Console. – theWalker Jan 19 '12 at 13:10