C++ gives you the privilege to make use of Command Line Arguments. Most important thing is to get aware of the int main(). This gets 2 arguments. First argument is about the number and the second is about the listing procedure of command line arguments.
Its format is given below:
In order to count the amount of arguments which are entered in a program coming from command line, int argc is used. Each and everything, related to program even its name is included in it.
All arguments are cataloged in the array having character pointers. Here, argv[0] can be used as the very name of that program. If there is no name then it can be used as an unfilled string. Now, each and every constituent whose number is not greater to argc is called command line argument. It is possible that every argc factor can be used as string. It can also be used as 2 dimensional arrays. Here, argv[argc] can be known as a void pointer.
What will be the way of using it? Approximately, all programs if they like to lay down the limitation of their program can use it. Mostly, it is used in the form of writing a function which gets box file’s name and shows all the manuscript on the screen.
You can make a program like this:
#include <iostream>
using namespace std;
int main ( int argc, char *argv[] )
{
if ( argc != 2 ) // argc must be equal to two for right implementation
// We print argv[0] Let’s suppose it as a name of the program
cout<<"usage: "<< argv[0] <<" <filename>\n";
else {
// Suppose argv[1] as a filename for opening
ifstream the_file ( argv[1] );
// Don’t forget to check that the file is completely opened
if ( !the_file.is_open() )
cout<<"File can’t be opened\n";
else {
char x;
// the_file.get ( x ) it gives back false, when there is fault or file is finished while ( the_file.get ( x ) )
cout<< x;
}
// the execution of the file is stopped now
}
}
The program is straightforward. It includes the complete edition of main. The next thing is to make sure whether a user has given 2nd argument or not. After that, it is the liability of the program to verify the file by giving the command of open. This process is trouble-free and authentic. The file will be opened by command, if it has no fault. It is easy to identify the code but comments are given for your ease. The reason is that, you will feel unproblematic while learning the command line argument.
Leave a Reply