从另一个exe运行exe
我试图编写一个程序,运行其他可执行文件与一些参数在同一个文件夹中,这个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;
}
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方法工作,虽然我给的解释是错误的,如下面pmg的comment指出。
你的工作目录可能错了,你可以把它从cd
命令不会改变。由于你使用的是windows,我建议你使用CreateProcess来执行pdftotext.exe
,如果你想设置工作目录,你可以检查CreateProcess
的lpCurrentDirectory
参数。
可能想要createprocess而不是系统 –
@EdHeal,谢谢,我试过'createProcess()'但没有运气,我不太明白什么意思是该函数的参数,特别是最后两个,任何示例都是受欢迎的。 – wallek876
网上有很多例子,比如https://msdn.microsoft.com/en-us/library/windows/desktop/ms682512(v=vs.85).aspx –