gpt4 book ai didi

c++ - 如何从 C++ 中的不同目录运行命令行工具

转载 作者:行者123 更新时间:2023-11-30 05:26:20 25 4
gpt4 key购买 nike

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

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

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

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

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

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

最佳答案

正如@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,因此上面的程序打印出以下内容:

Test test test

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

关于c++ - 如何从 C++ 中的不同目录运行命令行工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37839065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com