天天看點

【MFC】VC調用WinRar解壓檔案(如:.gz)

void UnpackFile(const CString & strFilePath)
{
    CString winRarInstallPath = "C:\\Program Files\\WinRAR\\WinRAR.exe"; 
    CString strDestPath; //目标解壓位置
    int pos  = strFilePath.ReverseFind('.');
    strDestPath = strFilePath.Left(pos);
    //删除同名檔案
    if(::PathFileExists(strDestPath));
    {
      DeleteFile(strDestPath);
    }
    // 清空檔案
    DeleteDirectories(strDestPath); //上篇文章中的函數
    
    if (FALSE == ::CreateDirectory(strDestPath,NULL))
    {
        AfxMessageBox("建立解壓路徑失敗");
        return;
    }
    
    //x解壓  -ibck背景執行 -o+如存在,則覆寫 -inul不彈出錯誤提示  
    //使用 -ibck,縮小到了系統托盤區域
    CString strCmd= "\"" + winRarInstallPath + "\" x -ibck -o+ -inul \"" + strFilePath + "\" \"" + strDestPath+"\""; 
    STARTUPINFO si={sizeof(si)};
    PROCESS_INFORMATION pi; 

    BOOL bRet=CreateProcess(NULL,strCmd.GetBuffer(MAX_PATH),NULL,NULL,FALSE,0,NULL,NULL,&si,&pi);  
    DWORD dwExit=0;  
    if(bRet)  
    {  
        //這個地方将導緻該函數為阻塞狀态  
        WaitForSingleObject(pi.hProcess,INFINITE);        
        ::GetExitCodeProcess(pi.hProcess,&dwExit);  
        CloseHandle(pi.hThread);  
        CloseHandle(pi.hProcess);  
    }    
    return;
}
           

需注意問題:

1.網上有說目标檔案路徑需要加一個“\“,可能調系統的函數的話是對的,但如果你是拷貝的winrar.exe的話,就不能加"\",不然是無法解壓的。

2.調用winrar.exe 而不是rar.exe的原因,這樣winrar可以托盤到通知區域,而rar.exe會出現黑視窗,使用者體驗不好