2

I got bored earlier and wondered if you could execute terminal commands on the iOS platform. Surely enough, just like OSX you can. This is really awesome, but how do I output what the terminal outputs to a text area or something similar? It's nothing serious, just a fun project.
I am using system("") to do it.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
James Heald
  • 841
  • 1
  • 12
  • 33

1 Answers1

1

This, my friend is one of the downsides to using system. I also hope you understand that system is unavailable on a non-jailbroken iDevice, so unless you are installing it as instructed on the #1 answer on iPhone App Minus App Store, then you can't use it.

Now, moving forward, you have a few options.

  1. Pipe the output of the command to a file, and read that file in your application. Your code should look something like this:

    system("myCommand -f \"/path/to/my/file\" > output.txt")
    
    NSString *results = [NSString stringWithContentsOfFile:@"output.txt" usedEncoding:nil error:nil];
    NSLog(@"%@", results);
    
  2. Create the process with the popen function, and then pipe the output directly into your application:

    NSFileHandle *openProcessRead(const char *command)
    {
        FILE *fPtr = popen(command, "r");
    
        NSFileHandle *fileHandle = [[NSFileHandle alloc] initWithFileDescriptor:fileno(fPtr) closeOnDealloc:YES];
    
        return fileHandle;
    }
    

    You can now use the NSFileHandle docs to do what you need.

Community
  • 1
  • 1
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • Shame about its jailbroken exclusivity. But I just need something simple for me to use. Great answer! Thanks for the helpful advice! :) – James Heald Jun 18 '12 at 12:50