开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜