Search code examples
cwindowscmdcygwinsystem

Run exe from another exe


I am trying to write a program that runs an other executable in the same folder with some arguments, this exe is pdftotext.exefrom poppler-utils and it generates a text file.

I prepare a string to pass it as argument for system(), the result string is:

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

First go to the directory of the file and then run the executable.

When I run it I always get

sh: cd/D: No such file or directory

but the command works if I run it directly in from the Command Prompt.

I don't think it matters, but this is what I have written so far:

#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;
}

Solution

  • cd is a "shell" command, not a program that can be executed.

    So to apply it run a shell (cmd.exe under windows) and pass the command(s) you want to execute.

    Do to so m Make the content of winCommand look like this:

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

    Please note that changing the drive and directory only applies to the environment used by cmd.exe. The program's drive and directory stay as they were before the call to system().


    Update:

    Looking more closely at the error message one notices the "sh: ...". This clearly indicates system() does not call cmd.exe, because it most likley would not prefix an error message like this.

    From this fact I dare to conclude the code shown is called in and runs under Cygwin.

    The shell(s) provided and used by Cygwin do not know the windows specific option /D to the shell command cd, thus the error.

    As however the shells used by Cygwin can call cmd.exe my orignally provide approach works, although the explaination I gave is wrong, as pointed out by pmg's comment below.