views:

338

answers:

4

Hi all,

Is it possible to make system call in Objective-C?

I have the following code:

if (!system("ls -l")) {
    NSLog(@"Successfully executed"); 
} else {
      NSLog(@"Error while executing the command"); 
}

How to get the output?

Thanks

+6  A: 

You should use NSTask. If you just need the results of ls, there are more appropriate filesystem wrappers in Cocoa.

refulgentis
+7  A: 

This is a perfect candidate for using -[NSFileManager contentsOfDirectoryAtPath:error:] instead of wrapping a built-in shell function and parsing the output. For general-purpose commands where you need the output — and where there is no equivalent functionality "for free" in Cocoa (it just takes time to learn the available APIs) — NSTask is generally a far better alternative than system().

Quinn Taylor
+4  A: 

If you like to do it the C way you can use popen. This can be used to read the output also. But the answers about using Objective-C solutions are probably the better ones.

Friedrich
A: 

Objective-C does not prevent a program to invoque system() or any of its equivalents.

CocoaTouch does.

mouviciel