我正在使用 NSTask 从我的应用程序中执行 zip 命令。它作为参数传递一些指向要压缩的文件/文件夹的路径。
问题是,如果没有 -j 选项,最终的 zip 最终会在 zip 内出现荒谬的文件路径(例如“/private/var/folders/A5/A5CusLQaEo4mop-reb-SYE+++TI/-Tmp-/9101A216-5A6A-4CD6-A477-E4B86E007476-51228-00014BCB9514323F/myfile.rtf”)。但是,如果我添加 -j 选项,那么如果嵌套文件夹深处的任何文件有
我尝试在执行 NSTask 之前设置路径:
[[NSFileManager defaultManager] changeCurrentDirectoryPath:path];
希望 zip 的文档说的是实话:
By default, zip will store the full path (relative to the current directory)
但这并没有按预期工作。调整 -j 和 -p 和 -r 的设置只会在不同的组合中产生上述问题。
问题:
我如何获取一组目录,例如
- /some/long/path/sub1/file1.txt
- /some/long/path/sub2/file1.txt
并将它们压缩成一个 zip,其内容为
- /sub1/file1.txt
- /sub2/file1.txt
感谢您对 zip 的微妙之处提出的任何建议。
-----编辑
我忘记添加的另一件事是传递的原始目录是“path”,因此在我看来,期望的结果也是预期的结果。
最佳答案
而不是
[[NSFileManager defaultManager] changeCurrentDirectoryPath:path];
在启动任务之前使用-[NSTask setCurrentDirectoryPath:]
。例如:
NSString *targetZipPath = @"/tmp/foo.zip";
NSArray *args = [NSArray arrayWithObjects:@"-r", targetZipPath,
@"sub1", @"sub2", nil];
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/zip"];
[task setArguments:args];
// set path to be the parent directory of sub1, sub2
[task setCurrentDirectoryPath:path];
…
关于cocoa - 从命令行 Zip - 如何修剪路径元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6352866/