从另一个exe运行exe

时间:2015-07-12 10:13:16

标签: c windows cmd cygwin system

我正在尝试使用一些参数编写一个在同一文件夹中运行其他可执行文件的程序,这个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;
}

2 个答案:

答案 0 :(得分:2)

cd是&#34; shell&#34;命令,而不是可以执行的程序。

<击>

所以要应用它,在Windows下运行一个shell(cmd.exe)并传递你想要执行的命令。

这样做使winCommand的内容看起来像这样:

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

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

<强>更新

仔细查看错误消息,我们会注意到&#34; sh: ... &#34;。这清楚地表明system()没有调用cmd.exe,因为它最有可能不会为此类错误消息添加前缀。

从这个事实我敢于得出结论显示的代码被调用并在Cygwin下运行。

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

然而,Cygwin使用的shell可以调用cmd.exe我的orignally提供方法,虽然我给出的解释是错误的,正如 pmg &#39所指出的那样;下面是comment

答案 1 :(得分:1)

您的工作目录可能有误,您无法从cd命令更改它。由于您使用的是Windows,我建议您使用CreateProcess来执行pdftotext.exe,如果您想设置工作目录,可以查看CreateProcess的{​​{1}}参数。