Shekhar
Shekhar

Reputation: 49

Command-line argument in C

I am very new to C programming. I am stuck in a very trivial problem. I have a C program where I am passing the value of one variable through a text file. Based on this variable I am passing one condition, e.g. if bDrw==true then proceed else not. Now I want my program to take the condition from from the command line instead of a text file. i.e. when I type "Drw" on the command line, the program should make bDrw==true.

How can I do this? I am giving the rest of arguents through :

int main(int argc, char *argv[])
{
bool    bArgs = false;
bool    bConf = false;
bool    bUgMgr = false;
bool    bFile = false;
bool    bErp  = false;

char    acAttrFile[(MAX_FSPEC_SIZE*2) + 1 ]="";
char    acPartFile[(MAX_FSPEC_SIZE*2) + 1 ]="";
char    acConfFile[(MAX_FSPEC_SIZE*2) + 1 ]="";
char    acSingleItem[UF_UGMGR_PARTNO_SIZE + 1]="";
char    acItemRevSeed[UF_UGMGR_PARTNO_SIZE + UF_UGMGR_PARTREV_SIZE + 1]="";
char    acUser[MAX_FSPEC_SIZE + 1]="";
char    acPass[MAX_FSPEC_SIZE + 1]="";
char    acLogDir[(MAX_FSPEC_SIZE*2) + 1]="";
char    acNatDir[(MAX_FSPEC_SIZE*2) + 1]="";
char    msg[MAX_LINE_SIZE + 1]="";

bArgs = getArgs(argc,argv,acAttrFile,acPartFile,acConfFile,acSingleItem,acItemRevSeed,acUser,acPass,acLogDir,acNatDir,&bUgMgr,&bErp);

Upvotes: 1

Views: 367

Answers (4)

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74202

For complex argument parsing, you should consider the getopt library.

However, in this case:

#include <stdio.h>
#include <string.h>

int main( int argc, char** argv ) {
    unsigned short int bDrw = 0;

    if ( argc == 2 && strcmp( argv[1], "Drw" ) == 0 ) {
        bDrw = 1;
    }

    printf( "bDrw = %d\n", bDrw );

    return 0;
}

Upvotes: 0

icyrock.com
icyrock.com

Reputation: 28578

Take a look at this tutorial:

Upvotes: 0

user191776
user191776

Reputation:

Try this, assuming you run the program by typing its name followed by Drw:

int main(int argc, char *argv[])
{
...
  if(argc > 1 && strncmp("Drw",argv[1],4) == 0)
  {
     ...  // bDrw is true
  }
...
}

Upvotes: 1

Bret Savage
Bret Savage

Reputation: 201

Assuming c99:

#include <string.h>
int main(int argc, void **argv)
{
    bool bDrw = false;
    if (argc > 1  && strcmp(argv[1], "bDrw") == 0)
        bDrw = true;
    /* take it from here.... */
    return 0;
}

Upvotes: 1

Related Questions