Thursday, July 26, 2012

External Arguments in ANSI C

The easiest way to send data to your program is to use external arguments. An external argument is a string that can be processed by your program.

Let us suppose that we have a console program called ArgPrinter. To execute the program and send external arguments you will need to open a console\terminal and type something like this:
ArgPrinter arg1 arg2 arg3 arg4
Arguments can also be sent by using other methods, but those are system specific (Example: When you create a shortcut in windows you can go to the shortcut's properties and put the arguments there).

If you want to access the arguments who were sent, your main function should have this prototype:
int main(int argc, char**argv)
argc is a integer value who represents the number of arguments who were sent.
argv is a array of strings containing each of the sent arguments plus the path to your executable file.

TIPYes, this means that if you send 4 arguments argc will be equal to 5 because of the path argument.

Now let's take an example implementation of the ArgPrinter program:

int main(int argc, char** argv)
   int i;
   int returnValue = 0;
      printf("Number of arguments: %d\n", argc);
      for(i = 0; i<argc; i++)
      returnValue = -1;
   return returnValue;
Number of arguments: 5
/home/dystopiancode/Ubuntu One/Eclipse/ArgPrinter/ArgPrinter
The program above will print the number of arguments and after that it will print the value of each argument.

The value that your program returns can signify the execution status of the program. Usually programs return 0 if they were executed successfully. This feature is useful if you call a C program from a shell script or something similar.

Question: Is your C program called directly from console using the external arguments or it is called by another program?


No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger