C input line argc and argv
16 Dec 2011 Leave a Comment
Sometimes it is useful to pass information into a program when you run it.
Generally, you pass information into the main( ) function via command line arguments.
A command line argument is the information that follows the program’s name on the command line of the operating system.
For example, when you compile a program, you might type something like the following after the command prompt:
at windows
> program_name
at linux
./program_name
where program_name is a command line argument that specifies the name of the program you wish to compile.
There are two special built-in arguments, argv and argc, that are used to receive command line arguments.
The argc parameter holds the number of arguments on the command line and is an integer. It is always at least 1 because the name of the program qualifies as the first argument.
The argv parameter is a pointer to an array of character pointers. Each element in this array points to a command line argument. All command line arguments are strings
any numbers will have to be converted by the program into the proper internal format.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if(argc!=2) {
printf("You forgot to type your name.\n");
exit(1);
}
printf("Hello %s\n", argv[1]);
return 0;
}
next code, write countdown
/* Countdown program. */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main(int argc, char *argv[])
{
int disp, count;
if(argc<2) {
printf("You must enter the length of the count\n");
printf("on the command line. Try again.\n");
exit(1);
}
if(argc==3 && !strcmp(argv[2], "display")) disp = 1;
else disp = 0;
for(count=atoi(argv[1]); count; --count){
if(disp) printf("%d\n", count);
putchar('\a'); /* this will ring the bell */
}
printf("Done\n");
return 0;
}
