Reputation: 13
I have to modify this code which needs 2 command line argument
if (argc == 3){
host = argv[1];
port = atoi(argv[2]);
else {
fprintf(stderr, "usage error: incorrect number of arguments\n");
to have 3 optional command line argument in any order (username,the server host num,the server port num ).I write it this way but it won't work.could somebody please help me to figure out what to do.thanks
if (argc<1 || argc>4)
fprintf(stderr, "usage error: incorrect number of arguments\n");
else
for(int i=1;i<=argc;i++)
{
if (strcmp( argv[i],"-u"==0 )
username=argv[i];
if(strcmp(argv[i],"-p"==0)
port=atoi(argv[i]);
if (strcmp(avrgv[i],"-h"==0)
host=(argv[i]);
Upvotes: 0
Views: 1105
Reputation: 13356
You should increase the index to get value of the argument bypassing the options. e.g. modify your code like this.
if (argc<1 || argc>4)
fprintf(stderr, "usage: %s -u username\n", argv[0]);
else
for(int i=1;i<=argc;i += 2)
{
if (strcmp( argv[i],"-u")==0 )
username=argv[i + 1];
Also you'd better define username
as a char
array and copy argument value into it, so you can modify it directly, like this:
char username[NAME_LEN + 1]; // +1 for tailing '\0'
strncpy(username, argv[i + 1], NAME_LEN);
Upvotes: 0
Reputation: 239311
Use getopt
, it's purpose-built for handling command line arguments in a consistent way, something which is notoriously difficult to do correctly.
Upvotes: 1