如何从C ++中的其他目录运行命令行工具

时间:2016-06-15 15:00:56

标签: c++ windows

我正在尝试构建一个C ++应用程序,它使用system()函数在Windows命令提示符下进行大量命令行调用。 C ++在下面的目录 BSP 中运行。 BSP 包含子文件夹 BSP / XST / Files 。应用程序执行的命令之一需要调用需要在 Files 目录中运行的命令行工具(Xilinx综合工具)。

BSP
|---XST
|---|---Files

在命令提示符下手动执行我会做类似的事情:

>>cd XST
>>cd Files
>>xst -h

有没有办法从 BSP 目录中调用子目录中的工具? 我看了这个问题here,但它不起作用。我猜是因为他们正在讨论存储在子目录中的可执行文件,而我正在调用命令行工具(即使用环境变量)。

简化:是否有命令/选项在Windows命令提示符下的子文件夹中运行命令行工具?我可以通过我的C ++模拟语句。

1 个答案:

答案 0 :(得分:1)

正如@CodyGray在评论中所建议的,我的想法是使用SetCurrentDirectory。如果您的程序位于 BST 目录中,并且您希望在相对于它的子文件夹 XST \ Files 中运行 xst ,那么它有意义的是也使用GetModuleFileName。使用此功能检索程序的路径,然后用子文件夹替换文件名。最后将目录更改为修改后的路径:

#include <string>
using namespace std;

int main()
{
    // Get the path to your program.
    char moduleFilePath[MAX_PATH];
    GetModuleFileName(NULL, moduleFilePath, MAX_PATH);

    // Find the backslash in front of the name of your program.
    string::size_type pos = string(moduleFilePath).rfind("\\");

    // Replace the program name by your sub-folder.
    string subFolderPath = string(moduleFilePath).substr(0, pos) + "\\XST\\Files";

    // Change into the sub-folder relative to your program.
    SetCurrentDirectory(subFolderPath.c_str());

    // Execute some program in your sub-folder.
    system("type test.txt");

    return 0;
}

由于我没有 xst ,我将文本文件 test.txt 放入子文件夹以进行测试。该文件只包含Test test test,因此上面的程序打印出以下内容:

  

测试测试

但正如@MikeVine所建议的那样,CreateProcess可能是一个更智能的解决方案。

相关问题