Shell command in .m file?
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
NSTask is an alternative. Check out the NSTask Class Reference
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.
精彩评论