3

I have an issue and I don't know my program is correct or not. Please let me know your ideas?

Issue: Create a process file program in command line and the return of program is the number of processed file.

My program: in main() function I return the number of processed file.

Is it correct? If correct, how can I get this value from another program?

Please help me?

Ankata
  • 141
  • 2
  • 3
  • 4
  • Note that returning count of things processed as an exit status is dangerous, since the [largest value you can return in an exist status is 255](http://stackoverflow.com/questions/808541/any-benefit-in-using-wexitstatus-macro-in-c-over-division-by-256-on-exit-status). – sarnold Mar 12 '11 at 08:10

3 Answers3

5

You can simply use return. A common return value for Success is 0, and anything else is considered some sort of error.

int main()
{
 ...

return 0;
}

To get the value to another program, you can either use a System call, http://en.wikipedia.org/wiki/System_(C_standard_library)

or use a bash script like:

Edited, thanks Evan Teran:

  myProgram; 
    V=$?; 
    program1 $V
William Melani
  • 4,270
  • 1
  • 21
  • 44
  • That's not how you get the return value of a program that will assign the output (as in `stdout` to `$v`). To get the return value you should do this: `myProgram; V=$?; program1 $V` – Evan Teran Mar 12 '11 at 18:59
3

main() can return "exit code" to OS by using exit(code) function

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
    cout<<"Program will exit";
    exit(1); // Returns 1 to the operating system

    cout<<"This line is never executed";
}

Then in caller program, you can check returned exit code, for example (caller is a batch file):

@echo off
call yourapp.exe
echo Exit Code = %ERRORLEVEL%
ngduc
  • 1,415
  • 12
  • 17
0

That's correct. The result code of the program is the return value of the main function.

Oswald
  • 31,254
  • 3
  • 43
  • 68