C ++:如何使我的程序打开一个带有可选参数的.exe文件

我在程序上遇到了一些麻烦。 我的目标是让它打开几个传递可选参数的.exe文件。 例如,如果我想打开一个pdf,我可以input下面的string到cmd窗口。

// If used in a cmd window it will open up my PDF reader and load MyPDF.pdf file "c:\Test space\SumatraPDF.exe" "c:\Test space\Sub\MyPDF.pdf" 

这里有两个我使用的尝试。 第一个打开PDF,但当然不会加载文件。 第二个根本不起作用。

 // Opens the PDF in my program system("\"C:\\Test space\\SumatraPDF.exe\""); // Error I get inside of a cmd window is the comment below // 'C:\Test' is not recognized as an internal or external command, operable program or batch file. //system("\"C:\\Test space\\SumatraPDF.exe\" \"C:\\Test space\\Sub\\MyPDF.pdf\""); 

我不确定第二个不工作的原因。 这可能是我误解系统的一些东西,或者我没有正确使用分隔符。

我觉得有一个为此devise的库,而不是创build一个使用这么多分隔符的长string。

谢谢你的帮助。

欢迎来到堆栈溢出!

系统方法通过将参数传递给cmd / c来工作。 所以你需要一些附加的引号。 查看由sled发布的相关问题 。

作为系统的替代方法,请查看ShellExecute或ShellExecuteEx Win32 API函数。 它有更多的功能,虽然它不是便携式。

 // ShellExecute needs COM to be initialized CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); SHELLEXECUTEINFO sei = {0}; sei.cbSize = sizeof(sei); sei.lpFile = prog; // program like c:\Windows\System32\notepad.exe sei.lpParameters = args; // program arguments like c:\temp\foo.txt sei.nShow = SW_NORMAL; // app should be visible and not maximized or minimized ShellExecuteEx(&sei); // launch program CoUninitialize(); 

更多信息在这里 。