1

I tried using system() to run a shell command in a .m file, but to no avail. How is it possible to run a shell command from a .m file in Xcode?

#import "AppController.h"


@implementation AppController
- (void)awakeFromNib
{
    [output setStringValue:@"Awaiting orders, sir."];
}

- (IBAction)convertFile:(id)sender
{
    NSString *string = [input stringValue];
    NSString *string2 = @"tar czvf ProjectFiles.tar.gz ";



    NSString *stringCmd = [NSString stringWithFormat:@"%@ %@", string2, string];

    system(stringCmd);
}
@end
Mike
  • 55
  • 1
  • 1
  • 8

2 Answers2

1

NSTask is an alternative. Check out the NSTask Class Reference

JimDusseau
  • 729
  • 6
  • 6
  • So - (void)setLaunchPath:(NSString *)path? – Mike May 20 '11 at 16:46
  • NSTask is a good alternative to system indeed. For usage examples, you can search NSTask on stackoverflow, e.g. http://stackoverflow.com/questions/5211737/nstask-question – diciu May 20 '11 at 19:28
0

Your code failed because system expects a C string (char *) and your stringCmd is a NSString *.

Try using:

system([stringCmd cStringUsingEncoding:NSASCIIStringEncoding]);

Also note that system runs the command in a shell so be aware for potential security problems. If your input string is @"tt.txt; echo \"aa\"" your code will run

tar czvf ProjectFiles.tar.gz tt.txt; echo "aa"

This may or not be what you intend.

diciu
  • 29,133
  • 4
  • 51
  • 68
  • echo "aa" is just an example. It could just as well be "rm -rf /" or some other destructive command. – diciu May 21 '11 at 20:06