Saturday, February 27, 2010

C/C++ Programming under Linux - Part 2

Most console programs in GNU Linux ( for that matter Windows ) accept command line arguments. The following program will spit the arguments given at the command line to the console.


///////////////////////////////////////////
// commandline.cpp
//
// Command Line argument spitter
//
// g++ -ocmdline.exe commandline.cpp
//
//
#include <stdio.h>


int main( int argc , char **argv )
{
if ( argc == 1 ) {
printf("No command Line Argument\n");
//
// argc will be at least 1 in the case of C/C++ Programs
// argv[0] will contain the executable name
return 0;
}


//---------------- Print the Executable name
printf("%s\n", argv[0] );


//------------- Spit the rest of the arguments
for( int j=1; j< argc ; ++j )
puts(argv[j]);

}


1 comments:

[A]lthaf [k] Back[er] said...

when doing "==" operation ,its alway better to place constant to the left of "==" ie
if (1 == argc)
problem is if at all you do
if (1 = argc) it not a valid operation as there is no lvalue.
in other case if (argc = 1) it is a valid one,i hope you know the consequence. well it may not make sense now but when you are into deep coding argc = 1 would be argc == 1 ;-).