Saturday, June 2, 2007

Interacting with the command line in Objective-C


Before, I thought that you could interact with the command line only through Apple Script. I found a different way of doing it. If you have a script file for command line, you can access it and utilize it by using one of the following methods in Objective-C (Note, These are C functions)
  • int result = system("Your Command Here");
If you want to get the output from this call, you will have to pipe the output to a file and read it in using Objective-C. You can pipe the output like this:
  • int result = system("Your Command Here > File.txt");
I'm going to try and get a demo up for this to better understand this sometime this weekend.

The result contains from my understanding a 1 if it completed without error or a 0 if it had an error, I could be wrong. All I know is if you handle the result like this.
  • if (!result) {}
Your code will fall through to this method if it had an error.

Now, if you have a script that can run in the background, you can use the following C command
  • FILE *fileObject = popen("Your Command Here");
As shown above, this will return a FILE Object. This is a C object. This contains all the information being sent to and returned from the console, so if you need to get back information, you will have to use some C functions to print it out.

1 comment:

ThE uSeFuL said...

How can I print a FILE type object in Objective C?