#include <windows.h>
#include <iostream> // wcerr
int wmain(int argc, wchar_t* argv[]) {
// Path to the file (must be a wide string)
// You can use an absolute path or a relative path
LPCWSTR filePath = L"C:\\Windows\\System32\\notepad.exe";
LPCWSTR fileArguments = L"C:\\temp\\file.txt";
// Check if the file exists before trying to open it
DWORD fileAttr = GetFileAttributesW(filePath);
if (fileAttr == INVALID_FILE_ATTRIBUTES || (fileAttr & FILE_ATTRIBUTE_DIRECTORY)) {
std::wcerr << L"Error: File not found: " << filePath << std::endl;
return 1;
}
// Open the file with the default associated application
HINSTANCE result = ShellExecuteW(
nullptr, // No parent window
L"open", // Operation: "open", "print", etc.
filePath, // File to open
fileArguments, // Arguments
nullptr, // Default directory
SW_SHOWNORMAL // Show window normally
);
// ShellExecuteW returns a value > 32 if successful
if ((INT_PTR)result <= 32) {
std::wcerr << L"Failed to open file. Error code: " << (INT_PTR)result << std::endl;
return 1;
}
}
/*
run:
*/