I have a c program compiled as say demo.exe which will be run using a batch file or a python script. The C program will return an error code which I need to catch in the batch file or a python script.
Below is a sample program for C on windows
#include <stdio.h>
#include <stdlib.h>
int func()
{
return(44);
}
void fun(void)
{
func();
}
int main(int argc, char *argv[])
{
int c = atexit(fun);
printf("c = %dn", c);
return(74);
}
Next I wrote a windows batch file to run the program: I tried 3 scripts to run the exe but I am not getting return value from the C program. Instead the exe name is getting returned. This is the batch file:
@ECHO OFF
ECHO ==================================== FIRST BATCH TEST SCRIPT ====================================
call demo.exe
echo %ERRORLEVEL%
echo demo.exe returns "%ERRORLEVEL%"
IF %ERRORLEVEL% NEQ 0 (
echo FAILED
)
echo ==================================== SECOND BATCH TEST SCRIPT ====================================
for /f %%a in ('demo.exe') do set "demo=%%a"
echo %ERRORLEVEL%
echo ==================================== THIRD BATCH TEST SCRIPT ====================================
cd %~dp0
call demo.exe
if "%ERRORLEVEL%" == "54" goto NO_ERROR
:NO_ERROR
echo No Error. Error code = %ERRORLEVEL%
PAUSE
goto end
:ERROR
echo ERROR. Error code = %ERRORLEVEL%
PAUSE
:end
Output is as follows:
C:\Users\USER4\Downloads>demo.bat
==================================== FIRST BATCH TEST SCRIPT ====================================
c = 0ndemo.exe
demo.exe returns "demo.exe"
FAILED
==================================== SECOND BATCH TEST SCRIPT ====================================
demo.exe
==================================== THIRD BATCH TEST SCRIPT ====================================
c = 0nNo Error. Error code = demo.exe
Press any key to continue . . .
ERRORLEVEL is always coming as the name of the exe. How to get the return value of the C program in the batch file?