2013-07-19 25 views
0

我想通過Mac上的終端解壓文件,而不是使用ZipArchive或SSZipArchive。如何通過Objective-c中的終端解壓文件

在終端中,我嘗試了「解壓縮」命令,它工作的很好,但我不知道如何通過目標c代碼來表達。

我試過這種方式(鏈接:Unzip without prompt)它的工作原理,但只解壓縮我的一半文件,而不是所有的文件。

謝謝!

+0

@TBlue我在這裏開了新的話題。謝謝 ! –

回答

4

您是否試過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問題的解決方案,但如果您的項目不需要錯誤處理,則應該沒問題。

+0

沒有NSTask你可以做到嗎?這很簡單。你得到我的投票。 –

+0

謝謝!它效果很好。爲什麼NSTaks不起作用? –

+0

@YUFENG我不確定NSTask爲什麼不起作用,或許'unzip'工具有錯誤,無法在半途中繼續?我很高興這個解決方案爲你工作:) –

3

請參閱以下內容。我修改了一下。

- (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路徑。而且,根據解壓縮Man頁面,該命令行工具需要一個開關(-d)來指定解壓壓縮文件的目錄。 sourcePath是要解壓縮的源zip文件。 exportPath是目標文件夾。如果出現錯誤,請插入NSLog(@「%@」,命令);在第10行之前,讓我看看命令說的是什麼。

+0

感謝您的回答!它也很棒! –

+0

如果您爲我的努力投下贊成票,這將是很好的。謝謝。 –