#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
bool ExecDosCmd(char* strcmd)
{
SECURITY_ATTRIBUTES sa;
HANDLE hRead = NULL, hWrite = NULL;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hRead, &hWrite, &sa, 0))
{
return false;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError = hWrite; //把創建進程的標準錯誤輸出重定向到管道輸入
si.hStdOutput = hWrite; //把創建進程的標準輸出重定向到管道輸入
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
//關鍵步驟,CreateProcess函數參數意義請查閱MSDN
if (!::CreateProcess(NULL, strcmd, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi))
{
CloseHandle(hWrite);
CloseHandle(hRead);
::CloseHandle(pi.hThread);
::CloseHandle(pi.hProcess);
return false;
}
CloseHandle(hWrite);
char buffer[4096] = { 0 }; //用4K的空間來存儲輸出的內容,只要不是顯示文件內容,一般情況下是夠用了。
DWORD bytesRead;
while (true)
{
if (ReadFile(hRead, buffer, 4095, &bytesRead, NULL) == NULL)
break;
//buffer中就是執行的結果,可以保存到文本,也可以直接輸出
//printf(buffer); //這裏是彈出對話框顯示
if (strstr(buffer, "文件損壞或密碼錯誤") || strstr(buffer, "發現文件頭毀損"))
{
CloseHandle(hRead);
::CloseHandle(pi.hThread);
::CloseHandle(pi.hProcess);
return false;
}
}
CloseHandle(hRead);
::CloseHandle(pi.hThread);
::CloseHandle(pi.hProcess);
return true;
}
int main(int argc, char* argv[])
{
//char szCommandLine[] = "Rar.exe a -r -hp123456 \"g:/360Downloads.rar\" \"f:/360Downloads\"";
char szCommandLine[512] = {} ;
for (int i = 100000; i < 999999; i++)
{
sprintf_s(szCommandLine, 512, "Rar.exe x -hp%u \"g:/360Downloads.rar\" \"F:/test/\"", i);
if (ExecDosCmd(szCommandLine))
{
printf("密碼是:%u\r\n",i);
break;
}
}
system("pause");
}