Search code examples
ccommand-promptsystem-callserrorlevel

Getting errorlevel from system command


I have a C project and at some point I call the system command below:

ret_val = system("@ECHO OFF\nFC /A /L /N C:\\tmp\\test.out C:\\bin\\win\\output.txt");

FC command basically compares the two files and supposed to return an error level.

If I call this command on command prompt, I can view the error simply by echoing the errorlevel variable. I have no problem here.

My question is I would like to have this error level in an int variable in my code. I don't want it to be seen on my terminal but at the same time I want this variable in order to analyze my comparison result. This ret_val variable is always 0, it's not the functionality that I need.

How can I get errorlevel value in my code?


Solution

  • The system command only executes the first line of your string, so it executes @echo off, which doesn't change default return code, and you always get 0.

    Of course, you could

    • paste the text in a .bat file and execute this .bat file
    • use commands chaining: @echo off && FC /A /L /N C:\\tmp\\test.out C:\\bin\\win\\output.txt

    but in your case, since you have only one command to call, just call it without the @echo off

    ret_val = system("FC /A /L /N C:\\tmp\\test.out C:\\bin\\win\\output.txt")
    

    system doesn't need echo to be turned off. Only batch file execution defaults to verbose. System calls are silent (they don't print the issued commands).