I have built a c++ program that depends on "cmd.exe" to execute some of the tasks. For now I and for test purposes the path to that file is "c:\windows\system32\cmd.exe". My question is there any c++ API that returns the path of that file knowing that my program must work on win32 and on win64.
GetSystemDirectory is one option. For a 32-bit app, it will return the 32-bit system directory. For an x64 app, it will return the 64-bit native system directory.
You can also use CreateProcess or ShellExecuteEx with cmd.exe and it should find it without the path unless you are specifically concerned about someone manipulating the search path and getting the wrong cmd.exe.
If you are launching a .cmd file, then you can just do it with ShellExecuteEx with the open verb. Generally for a Windows desktop app, use of ShellExecuteEx is recommended for launching other programs. For example, here's some code that will launch the command prompt running the test.cmd script and wait for the result:
#include <windows.h>
#include <stdio.h>
#pragma comment(lib,"shell32.lib")
void main()
{
SHELLEXECUTEINFOW info = {};
info.cbSize = sizeof( info );
info.lpVerb = L"open";
info.fMask = SEE_MASK_FLAG_NO_UI | SEE_MASK_NOASYNC | SEE_MASK_NOCLOSEPROCESS;
info.lpFile = L"test.cmd";
info.lpParameters = nullptr; // Command-line parameters
info.lpDirectory = nullptr; // Working directory to set
info.nShow = SW_SHOW;
if( !ShellExecuteExW( &info ) )
{
printf("ERROR\n");
}
else
{
// Wait for process to finish.
WaitForSingleObject( info.hProcess, INFINITE );
// Return exit code from process
DWORD exitcode;
GetExitCodeProcess( info.hProcess, &exitcode );
CloseHandle( info.hProcess );
printf("Finished with exit code %u\n", exitcode);
}
}
You can also use:
info.lpFile = L"cmd.exe";
info.lpParameters = L"/c test.cmd";
The primary reason to use
ShellExecuteExinstead ofCreateProcessis thatShellExecuteExcan handle admin elevation requests for exes with the proper manifest elements.CreateProcesswould fail if the target EXE requires higher privileges than your current process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With