codescracker


c

C Command Line Arguments



« Previous Tutorial CodesCracker Home »


Sometimes it is useful to pass the information into a program when you run it. In other words, sometimes you need to pass the information into a program at the time of running the program.

In general, you pass the information into the function main() via the 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 instance, when you compile a program, you might type something like this on the command prompt:

cc program_name

Here program_name is a command line argument which specifies the name of the program that you wish to compile.

argc and argv

To special built-in arguments 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.

C Command Line Arguments Example

Here is an example program that uses a command line argument. It simply prints Hello and your name on the screen, if you specify your name as a command line argument. Just concentrate on this program:

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
	if(argc != 2)
	{
		printf("You have forgot to type your name..!!\n");
		exit(1);
	}
	printf("Hello %s", argv[1]);
	
	return 0;
}

If you saved this program with name myprogram and your name is Ritesh, you would type myprogram Ritesh to run the program. And then the output of the program will be Hello Ritesh

Let's take a look at one more example 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 have to 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);
		}
	}
	
	printf("Done..!!");
	
	return 0;
}

« Previous Tutorial CodesCracker Home »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test