Programming and Graphics

(Kiana) #1

5.4 Command line arguments 141


we will see on the screen:


1os
2is
3 running

We can use a double pointer to simplify the arguments of the main func-
tion by stating:


int main(int argc, char ** argv)

Building commands


The ability to receive information from the operating system allows us to
build command-line applications. For example, suppose that we want to build
a command that generates a file with a specified name, prints a zero in the file,
and then closes the file. The command is implemented in the following code
contained in the filenfz.ccand compiled into an executable namednfz:


#include <fstream>
using namespace std;

int main(int argc, char **argv)
{
ofstream file1;
file1.open(argv[1]);
file1 << "0";
file1.close();
return 0;
}

Running the code by typing in the command line:


nfz sage

generates a file namedsagecontaining a zero.


What if we forget to type the name of the file or accidentally type multiple
file names? In the first caseargc=1, and in the second caseargc>2. To issue
a warning, we include the iostream system header file and insert the following
block at the top of code:


if(argc != 2 )
{
cout<< "Please use: "<< argv[0] <<" <filename>" << endl;
return 1;
};
Free download pdf