Quickest Way to Shell - Use system() instead of NSTask

/ Published in: Objective C
Save to your folder(s)

Cocoa provides NSTask to run subprocesses. It can be used to run shell scripts, but all this manual pipe and file handling is a bit cumbersome. Fortunately, for a simple script, we can use the trusty old system and redirect its result to a file.

Copy this code and paste it in your HTML
  1. // We'll save the result in a temp file
  2. NSString* tempFilePath = [NSString stringWithFormat:@"%@/MyApplicationLastCrash.txt", NSTemporaryDirectory()];
  4. // Run the shell script
  5. NSString* script = [NSString stringWithFormat: @"ls -1t /Users/mini/Library/Logs/CrashReporter/* | grep /MyApplication | head -1 | tr -d '\n' >%@", tempFilePath];
  6. system([script UTF8String]);
  8. // Returns path to last crash report or empty string ( [lastCrash length == 0] )
  9. NSString* lastCrash = [NSString stringWithContentsOfFile:tempFilePath encoding:NSUTF8StringEncoding error:nil];

URL: http://parmanoir.com/Quickest_Way_to_Shell

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.