如何通过cstdlib系统传递带空格的参数

发布于 2024-09-05 11:57:18 字数 499 浏览 2 评论 0原文

我有这个 Windows 控制台应用程序,它接受一个文件,进行一些计算,然后将输出写入指定的文件。输入以“ap​​p.exe -input fullfilename”格式指定。我需要从我的 C++ 程序调用此应用程序,但文件路径中存在空格问题。当我通过键入直接从 cmd.exe 调用应用程序(为了清楚起见,没有指定输出文件)时,

"c:\first path\app.exe" -input "c:\second path\input.file"

一切都按预期工作。但是,当我尝试使用 cstdlib std::system() 函数时,即

std::system(" \"c:\\first path\\app.exe\" -input \"c:\\second path\\input.file\" ");

控制台打印出 c:\first 不是任何有效命令。这可能是常见的错误,并且有简单的解决方案,但我一直找不到任何解决方案。感谢您的帮助。

I have this windows console app which takes a file, do some calculations, and then writes the output to a specified file. The input is specified in "app.exe -input fullfilename" format. I need to call this application from my C++ program, but I have a problem with spaces in paths to files. When I call the app directly from cmd.exe by typing (without specifying output file for clarity)

"c:\first path\app.exe" -input "c:\second path\input.file"

everything works as expected. But, when I try using cstdlib std::system() function, i.e.

std::system(" \"c:\\first path\\app.exe\" -input \"c:\\second path\\input.file\" ");

the console prints out that c:\first is not any valid command. It's probably common mistake and has simple solution, but I have been unable to find any. Thx for any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笙痞 2024-09-12 11:57:18

您应该使用 Windows API 中的 _wspawnv 函数,而不是 std::system()。如果您想在 PATH 中搜索程序,而不是指定它的完整路径,请使用 _wspawnvp。

#include <stdio.h>
#include <wchar.h>
...
const WCHAR *app = L"C:\\path to\\first app.exe";
const WCHAR *argv[] = {app, L"-input", L"c:\\second path\\input file.txt"};
_wpspawnv(_P_WAIT, app, argv);

如果您 100% 确定您的输入文件名永远不会包含 ASCII 以外的任何内容,您也可以使用 _spawnv / _spawnvp。

Instead of std::system(), you should use the _wspawnv function from the Windows API. Use _wspawnvp if you want to search for the program in PATH, rather than specifying a full path to it.

#include <stdio.h>
#include <wchar.h>
...
const WCHAR *app = L"C:\\path to\\first app.exe";
const WCHAR *argv[] = {app, L"-input", L"c:\\second path\\input file.txt"};
_wpspawnv(_P_WAIT, app, argv);

You could also use _spawnv / _spawnvp if you are 100% sure that your input filename will never, ever contain anything else than ASCII.

北斗星光 2024-09-12 11:57:18

不要尝试在 std::system() 调用中添加引号。请尝试以下操作:

std::system("c:\\first\\ path\\app.exe -input c:\\second\\ path\\input.file");

Don't try to put the quotes in the std::system() call. Try the following:

std::system("c:\\first\\ path\\app.exe -input c:\\second\\ path\\input.file");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文