Coupon Accepted Successfully!


Command-Line Arguments

An executable program that performs a specific task for the operating system is called a command. The commands are issued from the command prompt of the operating system. Some arguments are associated with the commands; hence these arguments are called command-line arguments. These associated arguments are passed to programs.
Similar to C, in C++, every program starts with a main() function, and this function marks the beginning of the program. We have not provided any arguments so far in the main() function. Here, we can make arguments in the main function as in other functions. The main()function can receive two arguments, and they are (1) argc (argument counter) and (2) argv (argument vector). The first argument contains the number of arguments, and the second argument is an array of char pointers. The *argv points to the command-line arguments. The size of the array is equal to the value counted by the argc. The information contained in the command line is passed on to the program through these arguments when the main() is called up by the system.
  1. Argument argc: The argument argc counts the total number of arguments passed from command prompt. It returns a value that is equal to the total number of arguments passed through the main().
  2. Argument argv: It is a pointer to an array of character strings that contains names of arguments. Each word is an argument.

Syntax - main ( int argc, char * argv[]);

Example - ren file1 file2.

Here, file1 and file2 are arguments, and copy is a command. The first argument is always an executable program followed by associated arguments. If you do not specify the argument, the first program name itself is an argument but the program will not run properly and will flag an error. The contents of argv[] would be as follows:



16.22 Write a program to simulate rename command using command line arguments.





main(int argc, char *argv[])


fstream out;

ifstream in;
if (argc<3 )
cout<<“Insufficient Arguments”;
in.open(argv[1],ios::in | ios::nocreate);
if (in.fail())
cout<<“\nFile Not Found”;
out.open(argv[2],ios::in | ios::nocreate);
if (out.fail())
{ rename(argv[1],argv[2]); }
cout<<“\nDuplicate file name or file is in use.”;
return 0;



Explanation: In the above program, the main() receives two file names. The existence of the file can be checked by opening it in the read mode. If the file does not exist, the program is terminated. On the other hand, if the second file exists, the renaming operation cannot be performed. The renaming operation is carried out only when the first file exists and the second file does not exist. Make exe file of this program and use it on the command prompt.

Test Your Skills Now!
Take a Quiz now
Reviewer Name