【问题标题】:Run exe from another exe从另一个exe运行exe
【发布时间】:2015-09-30 17:33:19
【问题描述】:

我正在尝试编写一个程序,该程序使用一些参数在同一文件夹中运行其他可执行文件,这个 exe 是来自 poppler-utils 的 pdftotext.exe,它会生成一个文本文件。

我准备一个字符串作为system()的参数传递,结果字符串是:

cd/D N:\folder0\folder1\folder2\foldern && pdftotext.exe data.pdf -layout -nopgbrk

先进入文件所在目录,然后运行可执行文件。

当我运行它时,我总是得到

sh: cd/D: No such file or directory

但如果我直接从命令提示符运行该命令,则该命令有效。

我认为这并不重要,但这是我目前所写的:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <string.h>

// Function to get the base filename
char *GetFileName(char *path);

int main (void)
{
    // Get path of the acutal file
    char currentPath[MAX_PATH];

    int pathBytes = GetModuleFileName(NULL, currentPath, MAX_PATH);
    if(pathBytes == 0)
    {
        printf("Couldn't determine current path\n");
        return 1;
    }

    // Get the current file name
    char* currentFileName = GetFileName(currentPath);

    // prepare string to executable + arguments
    char* pdftotextArg = " && pdftotext.exe data.pdf -layout -nopgbrk";

    // Erase the current filename from the path
    currentPath[strlen(currentPath) - strlen(currentFileName) - 1] = '\0';


    // Prepare the windows command
    char winCommand[500] = "cd/D ";
    strcat(winCommand, currentPath);
    strcat(winCommand, pdftotextArg);

    // Run the command
    system(winCommand);

    // Do stuff with the generated file text

    return 0;
}

【问题讨论】:

  • 可能想要创建进程而不是系统
  • @EdHeal,谢谢,我试过createProcess(),但没有运气,我不太明白那个函数的参数是什么意思,特别是最后两个,欢迎任何例子。跨度>
  • 您使用的是哪个编译器/环境?赛格温?

标签: c windows cmd cygwin system


【解决方案1】:

cd 是“shell”命令,不是可以执行的程序。

因此,要应用它,请运行一个 shell(Windows 下的cmd.exe)并传递您要执行的命令。

Do to so m 使winCommand 的内容看起来像这样:

cmd.exe /C "cd/D N:\folder0\folder1\folder2\foldern && pdftotext.exe data.pdf -layout -nopgbrk"

请注意,更改驱动器和目录仅适用于cmd.exe 使用的环境。程序的驱动器和目录保持在调用system() 之前的状态。


更新:

仔细查看错误消息会发现“sh: ...”。这清楚地表明system() 不会调用cmd.exe,因为它很可能不会在这样的错误消息前面加上前缀。

从这个事实我敢断定显示的代码被调用并在Cygwin 下运行。

Cygwin 提供和使用的 shell 不知道 shell 命令 cd 的 windows 特定选项 /D,因此出现错误。

尽管 Cygwin 使用的 shell 可以调用 cmd.exe 我最初提供的方法有效,但我给出的解释是错误的,正如下面 pmgcomment 所指出的那样。

【讨论】:

  • system() 不应该已经自己做到了吗?参见7.22.4.8: "...系统函数将字符串指向的字符串传递给该命令处理器,以便以实现应记录的方式执行..."
  • @pmg Hm ... - 确实正确。但是,为什么会出现这个cd/D: No such file or directory 错误呢?
  • Cygwin ...真棒洞察力:)
  • 首先感谢您的回答,是的,我在cygwin中使用clang来编译程序,我应该提到
【解决方案2】:

您的工作目录可能有误,您无法通过cd 命令更改它。由于您使用的是windows,建议您使用CreateProcess执行pdftotext.exe,如果您想设置工作目录,可以查看CreateProcesslpCurrentDirectory参数。

【讨论】:

  • 谢谢,我试过了,但不太理解其他论点,特别是最后两个,欢迎任何例子。
  • @wallek876 这里是example
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-18
  • 1970-01-01
  • 2023-03-16
  • 2013-03-04
  • 2013-08-26
相关资源
最近更新 更多