如何从Objective-C应用程序执行终端命令(如grep)?

推荐答案

你可以用100.下面是一个运行"/usr/bin/grep foo bar.txt"的示例.

int pid = [[NSProcessInfo processInfo] processIdentifier];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;

NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/grep";
task.arguments = @[@"foo", @"bar.txt"];
task.standardOutput = pipe;

[task launch];

NSData *data = [file readDataToEndOfFile];
[file closeFile];

NSString *grepOutput = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"grep returned:\n%@", grepOutput);

NSPipeNSFileHandle用于重定向任务的标准输出.

有关在Objective-C应用程序中与操作系统交互的更多详细信息,请参阅苹果开发中心的以下文档:Interacting with the Operating System.

编辑:包括NSLog问题的修复

如果您正在使用NSTask通过bash运行命令行实用程序,那么您需要包含以下魔行以保持NSLog正常工作:

//The magic line that keeps your log where it belongs
task.standardOutput = pipe;

这里有一个解释:https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask

Objective-c相关问答推荐

目标 C:什么是(id)发件人?

如何使 UIView 动画序列重复和自动反转

iPhone:将日期字符串转换为相对时间戳

我需要在 ARC 中使用 dealloc 方法吗?

在子类中覆盖init

如何使用 NSString drawInRect 使文本居中?

无法加载从笔尖引用的图像

进入编辑模式时动画自定义绘制的 UITableViewCell

当服务器上的图像文件更改时,我的应用程序中的 SDWebImage 缓存图像会发生什么情况?

iPhone - 时区便利方法之间的差异

当用户点击文本字段外的其他区域时如何关闭键盘?

UIWebView didFinishLoading 多次触发

在 32 位和 64 位架构上格式化 NS(U)Integer 时类型转换的替代方法?

从 iPhone 设备查找当前国家

将 UIColor 保存到 NSUserDefaults 并从中加载

在 Objective-C 中_和touch之间的区别

IOS 中的圆形进度条

为什么我们不能在当前队列上使用 dispatch_sync?

使用正则表达式查找/替换 NSString 中的子字符串

UIPageViewController,如何在不打乱数据源指定顺序的情况下正确跳转到特定页面?