2015-07-12 144 views
1

我试图编写一个程序,运行其他可执行文件与一些参数在同一个文件夹中,这个exe是pdftotext.exe来自poppler-utils,它会生成一个文本文件。从另一个exe运行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; 
} 
+1

可能想要createprocess而不是系统 –

+0

@EdHeal,谢谢,我试过'createProcess()'但没有运气,我不太明白什么意思是该函数的参数,特别是最后两个,任何示例都是受欢迎的。 – wallek876

+1

网上有很多例子,比如https://msdn.microsoft.com/en-us/library/windows/desktop/ms682512(v=vs.85).aspx –

回答

2

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

所以申请它运行一个shell(cmd.exe在windows下)并传递你想要执行的命令。

做,以SO 3 M 使​​看起来像这样的内容:

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不知道windows特定选项/D到shell命令cd,因此出现该错误。

然而,如通过Cygwin的使用的炮弹可以叫我cmd.exe提供orignally方法工作,虽然我给的解释是错误的,如下面pmgcomment指出。

+0

不是'system()'应该已经这样做了吗?见[7.22.4.8](http://port70.net/~nsz/c/c11/n1570.html#7.22.4.8):*“...系统函数将字符串指向的字符串传递给该命令处理器以执行应该记录的方式执行......“* – pmg

+0

@pmg嗯......确实如此。但是,为什么这个'cd/D:没有这样的文件或目录'错误呢? – alk

+0

@pmg:请看我更新的答案。 – alk

1

你的工作目录可能错了,你可以把它从cd命令不会改变。由于你使用的是windows,我建议你使用CreateProcess来执行pdftotext.exe,如果你想设置工作目录,你可以检查CreateProcesslpCurrentDirectory参数。

+0

谢谢,我试过,但不太了解其他论点,特别是最后两个,任何例子都是值得欢迎的。 – wallek876

+0

@ wallek876这里是[示例](https://msdn.microsoft.com/en-us/library/windows/desktop/ms682512(v = vs.85).aspx) – Freeznet