I have been working on a project and am wondering how it is possible to send a terminal command in xcode and display results in a popup. I dont want to use the system(); method because it opens terminal. I know NSTasks can be used, i just dont know how to use it. Thank you everyone! (BTW this is for macosx not ios)
Asked
Active
Viewed 2,946 times
1 Answers
1
To get the output of a shell command, you need to open a pipe and read the data from it. Here's what I use for this task:
static NSString *outputForShellCommand(NSString *command) {
FILE *fp;
char data[1024];
NSMutableString *finalRet = [[NSMutableString alloc] init];
fp = popen([command UTF8String], "r");
if (fp == NULL) {
[finalRet release];
return nil;
}
while (fgets(data, 1024, fp) != NULL) {
[finalRet appendString:[NSString stringWithUTF8String:data]];
}
if (pclose(fp) != 0) {
[finalRet release];
return nil;
}
return [NSString stringWithString:finalRet];
}
Also, note that this question has been asked many times before.