system(“c:\\sample\\startAll.bat”) cannot run because of working directory?

╄→尐↘猪︶ㄣ 提交于 2019-12-11 08:31:29

问题


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?


回答1:


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)




回答2:


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.




回答3:


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




回答4:


Try with double slashes


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


来源:https://stackoverflow.com/questions/1372916/systemc-sample-startall-bat-cannot-run-because-of-working-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!