如果我input错误的dos命令,shellexecute会给出正确的结果

我执行dos命令,并给我预期的结果。

//executing dos command hInst = ShellExecute(0, "open", "cmd.exe", "/C dir > out.txt", 0, SW_HIDE); if(int(hInst)>32) { cout<<"\n Command executed."; } else { cout<<"\n Command not executed."; } 

如果我执行一个错误的命令相同的代码..

 hInst = ShellExecute(0, "open", "cmd.exe", "/C abc > out.txt", 0, SW_HIDE); if(int(hInst)>32) { cout<<"\n Command executed."; } else { cout<<"\n Command not executed."; } 

仍然显示执行的命令不是预期的。 我能做些什么来检查命令(abc)是否有效并成功执行

可能最简单的事情是:

 #include <cstdlib> // ... int ret1 = std::system("dir > out.txt"); // ret1 == 0 int ret2 = std::system("abc > out.txt"); // ret2 != 0 

但它会显示控制台黑色窗口。

使用ShellExecuteEx :

 SHELLEXECUTEINFO ei = {0}; ei.cbSize = sizeof(SHELLEXECUTEINFO); ei.fMask = SEE_MASK_NOCLOSEPROCESS; ei.hwnd = NULL; ei.lpVerb = NULL; ei.lpFile = "cmd"; ei.lpParameters = "/c dir > out.txt"; ei.lpDirectory = NULL; ei.nShow = SW_HIDE; ei.hInstApp = NULL; ShellExecuteEx(&ei); WaitForSingleObject(ei.hProcess, INFINITE); unsigned long ret; GetExitCodeProcess(ei.hProcess, &ret); // ret==0 ==> success ret!=0 ==> failure 

使用CreateProcess :

 STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); unsigned long ret; char cmd[255] = "cmd /c dir > out.txt"; if (CreateProcess(0, cmd, // this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string) 0, 0, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) { WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, &ret); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } // ret==0 ==> success ret!=0 ==> failure 

请考虑这些只是一个例子,让你知道你能做什么。 实际的代码在精神上是相似的,但稍微复杂一些。