Reputation: 512
CONTEXT :
-Windows 10
-C++
-Batch file
-I want to call a .bat
file in a .cpp
file and get an int
as return value
-The batch file counts and renames .jpg
files in a given folder passed as parameter
-Batch file code:
::%1 is the path to the base folder
::%2 is the name of the folder of the images
setlocal enabledelayedexpansion
@echo off
CD /D %1
set cnt=0
for %%f in (%2\*) do (
set newName=000!cnt!
set newName=!newname:~-4!
ren %%f !newName!.jpg
set /a cnt+=1
)
@echo %cnt% files renamed in order
exit /b %cnt%
QUESTION :
I think I already know how to pass parameters... You need put spaces after the .bat file you call and enter the wanted parameters.
ex:
To run my script in the L:/baseFolder/water
folder, I would use :
system(file.bat L:\\baseFolder water)
How do I get the cnt
value returned with exit /b %cnt%
as a variable in my cpp file?
Am I supposed to use exit
to get this integer?
Bonus: What if I want to return multiple values?
Upvotes: 2
Views: 1461
Reputation: 20141
MSDN describes the usage of system()
. I cite the part about return value:
If
command
isNULL
and the command interpreter is found, returns a nonzero value. If the command interpreter is not found, returns0
and setserrno
toENOENT
. Ifcommand
is notNULL
, system returns the value that is returned by the command interpreter. It returns the value0
only if the command interpreter returns the value0
.
Somehow, I assumed that return code of batch file is the return code of command interpreter but I was not fully sure nor I found an appropriate doc. concerning this.
Thus, I made a little sample and tried it locally.
testExitBat.cc
:
#include <Windows.h>
#include <iostream>
int main()
{
int ret = system("testExitBat.bat Hello");
std::cout << "testExitBat.bat returned " << ret << '\n';
return 0;
}
testExitBat.bat
:
::%1 an argument
echo "$1: '"%1%"'"
exit /b 123
I compiled and ran it on VS2013 (Windows 10):
C:\Users\Scheff>echo "$1: '"Hello"'"
"$1: '"Hello"'"
C:\Users\Scheff>exit /b 123
testExitBat.bat returned 123
Upvotes: 2
Reputation: 711
Both g++ and vs have the filesystem header under experimental, which may be a better solution. If you prefer the environmental variable solution then std::getenv will do that.
It's been a long time since I've done any batch file programming, but I seem to remember that you can set environmental variables in there.
Upvotes: 0