Showing posts with label Command line arguments. Show all posts
Showing posts with label Command line arguments. Show all posts

Command Line Arguments in C programming

It is possible to pass arguments to C programs when they are executed. The brackets which follow main are used for this purpose. argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument which is passed to mainA simple example follows, which checks to see if a single argument is supplied on the command line when the program is invoked.
#include <stdio.>h
main( int argc, char *argv[] )  
{
   if( argc == 2 )
      printf("The argument supplied is %s\n", argv[1]);
   else if( argc > 2 )
      printf("Too many arguments supplied.\n");
   else
      printf("One argument expected.\n");
}
Note that *argv[0] is the name of the program invoked, which means that *argv[1] is a pointer to the first argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one. Thus for n arguments, argc will be equal to n + 1. The program is called by the command line:
$myprog  argument1
More clearly, Suppose a program is compiled to an executable program myecho and that the program is executed with the following command.
$myeprog aaa bbb ccc
When this command is executed, the command interpreter calls the main() function of the myprog program with 4 passed as the argc argument and an array of 4 strings as the argv argument.
argv[0]         -  "myprog"
argv[1]  -  "aaa"
argv[2]  -  "bbb"
argv[3]  -  "ccc"
 www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

Ksh Tutorials :Command Line Arguments in kshell

Ksh Tutorials :Command Line Arguments in kshell
It is also called "positional parameters"
The number of command line arguments is stored in $# so one can check
for arguments with:
if [[ $# -eq 0 ]];then
print "No Arguments"
exit
fi
The single Arguments are stored in $1, ....$n and all are in $* as one string. The arguments cannot
directly be modified but one can reset the hole commandline for another part of the program.
If we need a first argument $first for the rest of the program we do:
if [[ $1 != $first ]];then
set $first $*
fi
One can iterate over the command line arguments with the help of the shift command. Shift indirectly removes the first argument.
until [[ $# -qe 0 ]];do
# commands ....
shift
done
One can also iterate with the for loop, the default with for is $*:
for arg;do
print $arg
done
The program name is stored in $0 but it contains the path also!