【问题标题】:How to unzip file via terminal in Objective-c如何在Objective-c中通过终端解压缩文件
【发布时间】:2013-07-19 01:47:00
【问题描述】:

我想通过 Mac 上的终端解压缩文件,而不是使用 ZipArchive 或 SSZipArchive。

在终端中,我尝试了“解压缩”命令,效果很好,但我不知道如何通过目标 c 代码表达。

我已经尝试过这种方式(链接:Unzip without prompt)它可以工作,但只解压缩了我的一半文件而不是所有文件。

谢谢!!

【问题讨论】:

  • @TBlue 我在这里打开了新话题。谢谢!

标签: objective-c macos terminal unzip nstask


【解决方案1】:

你试过system()函数吗?

system("unzip -u -d [destination full path] [zip file full path]");

您需要使用您的完整命令(包括文件路径)构造一个NSString,并将其转换为系统命令的 C 字符串,如下所示:

NSString *myCommandString = 
[NSString stringWithFormat:@"unzip -u -d %@ %@", destinationPath, zipPath];
system([myCommandString UTF8String]);

这不会返回任何命令的输出,因此如果您想了解有关操作如何进行的详细信息,但如果您的项目不需要错误,则最好使用Unzip without prompt 问题中的解决方案 -处理这个应该没问题。

【讨论】:

  • 不用NSTask也可以吗?那更简单。你得到我的投票。
  • @YUFENG 我不知道为什么 NSTask 不起作用,也许unzip 实用程序出错并且无法中途继续?我很高兴这个解决方案对你有用:)
【解决方案2】:

请参阅以下内容。我稍微修改了一下。

- (void)unzipme {
    NSTask *task = [[NSTask alloc] init];
    NSMutableString *command = [[NSMutableString alloc] initWithString:@""];
    NSArray *args;
    [task setLaunchPath:@"/bin/sh"];
    [command appendString:@"unzip "];
    [command appendString:[self convertShell:sourcePath];
    [command appendString:@" "];
    [command appendString:-d ];
    [command appendString:[self convertShell:[self exportPath]]];
    args = [NSArray arrayWithObjects:@"-c",command,nil]; // Line 10
    [task setArguments:args];
    NSPipe *pipe1;
    pipe1 = [NSPipe pipe];
    [task setStandardOutput: pipe1];
    [task launch];
    [task waitUntilExit];
}

- (NSString *)convertShell: (NSString *)path {
    static NSString *chr92 = @"\\";
    NSMutableString *replace = [[NSMutableString alloc]initWithString:chr92];
    [replace appendString:@" "];
    NSString *sPath = [self Replace:path :@" " :replace];
    return sPath;
}

convertShell 将 Objective-C 路径转换为 ​​Shell 路径。此外,根据 unzip 手册页,此命令行工具需要一个开关 (-d) 来指定解压缩档案的目录。 sourcePath 是要解压缩的源 zip 文件。 exportPath 是目标文件夹。如果出现错误,请插入 NSLog(@"%@",command);在第 10 行之前,告诉我命令的内容。

【讨论】:

  • 如果你为我的努力投上一票就好了。谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-12-29
  • 2012-06-30
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多