C input line argc and argv

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;
}



Published by

G3n1k

just to remember what i had known :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s