Question

I have an application and executables. I want my application to run my executables.

The executable files are in a folder, lets say in "c:\sample".

In this directory there is a batch file that calls my exe's. like:

start a1.exe
start a2.exe
start a3.exe

let's name it as startAll.bat

and suppose every exe has a data like a1.dat a2.dat ... and these data files are near this exe's.

I want to call this batch file by my application.

system("c:\\\\sample\\\\startAll.bat");

when I call it like that, command cannot find these exe's.

if I add directory names to batch files, it can not find the data that time. I think it is because of working directory.

start c:\sample\a3.exe

how can I change the working directory before I call this batch file?

or do you suggest anything else?

Was it helpful?

Solution

Call chdir("C:\\sample") before calling system(...)

Or put a cd command in your batch file

EDIT

Since you're not on C: the first lines of the batch script should be

C:
cd \sample

EDIT2

Using the suggestions made by Johannes and MattH a much better version of the BAT file would start with something like this

setlocal
set BATDIR=%~dp0
cd /d %BATDIR%

Now the bat file will work regardless of the directory it's in as there are no hard coded paths. SETLOCAL is used to avoid side effects from running the script (like changing directory or setting environment variables)

OTHER TIPS

The system function can take multiple commands like this:

system("C: && cd \\sample && startAll.bat");

That's neater than changing the current working directory of your calling process, because that can have its own unwanted side-effects.

Depending on how you set up these files, it might be neater than hard-coding a cd command into the batch file.

Edit: I tested this with a C program like this:

#include "stdafx.h"
#include <stdlib.h>

int _tmain(int argc, _TCHAR* argv[])
{
    system("C: && cd \\temp && test.bat");
    return 0;
}

and a batch file called C:\temp\test.bat like this:

echo "Hello world" > pog

and when I run that C program (in a different directory from c:\temp), sure enough a file called pog appears in C:\temp.

I often prefer to make my batch files ignore the working directory of the caller, if I only intend to work with paths relative to the batch file. You can do this with the following at the start of the file:

SET BATDIR=%~dp0
CD %BATDIR%

Or you can %BATDIR% when calling your external files.

To understand how the above works, take a look here

Try with double slashes


system("c:\\sample\\startAll.bat");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top