使用Windows API启动外部程序

时间:2014-04-12 07:54:36

标签: c++ winapi createprocess

我是Windows API的新手,我在使用dot程序(使用graphviz创建图形)从我的程序运行时遇到了很多麻烦。

我想要运行的命令,在cmd中运行的是:

dot -Kfdp -n -Tpng -o "D:\Programming\VS\Visual Studio 2013\Projects\Graphs\Graphs\Input\topsort.png" "D:\Programming\VS\Visual Studio 2013\Projects\Graphs\Graphs\Input\topsort.dot"

但是我一直收到错误2,The system cannot find the file specified

这是我的(简化)代码。请注意,处理结束时ca的值是正确的字符串,所以这不是问题。

//From earlier in the file
//#include <Windows.h>
//std::string filepath = "D:\\Programming\\VS\\Visual Studio 2013\\Projects\\Graphs\\Graphs\\Input\\topsort";

//Create structs
PROCESS_INFORMATION ProcessInfo; 
STARTUPINFO StartupInfo; 
ZeroMemory(&StartupInfo, sizeof(StartupInfo));
StartupInfo.cb = sizeof StartupInfo;

//Create a string and copy to a char*
string procArg = "dot -Kfdp -n -Tpng -o \"" + filepath + ".png\" \"" + filepath + ".dot\"";
char* ca = new char[procArg.size() + 1];
int size = (procArg.size() + 1) * sizeof(*ca);
int count = procArg.length();
procArg._Copy_s(ca, size, count);
ca[procArg.size()] = '\0';

//At the end of this, size = 182, count = 181,
//and ca = dot -Kfdp -n -Tpng -o "D:\Programming\VS\Visual Studio 2013\Projects\Graphs\Graphs\Input\topsort.png" "D:\Programming\VS\Visual Studio 2013\Projects\Graphs\Graphs\Input\topsort.dot"

//Attempt to create process
CreateProcess(NULL,
    ca,
    NULL,
    NULL,
    FALSE,
    0,
    NULL,
    NULL,
    &StartupInfo,
    &ProcessInfo);

谢谢!

2 个答案:

答案 0 :(得分:3)

看起来系统找不到程序的PATH。我建议您尝试将 dot 程序的绝对路径作为 procArg 的一部分。这也可以通过执行CMD来验证,然后尝试在那里执行相同的命令。

答案 1 :(得分:1)

CreateProcess有许多不同的选择。你挑选的那个可能不是最好的。选择是:

  1. 将应用程序的完整路径作为CreateProcess的第一个参数传递。在这种情况下,您的命令行可能会被正确解释。这是我的偏好。
  2. 将应用程序包含为命令行的第一个标记。在这种情况下,您通常必须包含两次,一次用于Windows,一次用于被调用程序的argv [0]。如果DOT不在Windows PATH上,则必须是完整路径。如果路径有任何空格,则需要引用它们。我发现这很痛苦,所以我避免这种方式。
  3. 通过CMD调用程序。将CMD作为CreateProcess的第一个参数传递并让它完成工作。您仍然需要DOT(或完整路径)作为第一个命令参数,但只需要一次。如果您正在执行命令行重定向或运行BAT文件,请使用此方法。
相关问题