Passing arguments into C program from a command line

1137475 pts.
Tags:
C program
Command line
Linux
My friend and I are using Linux and we want to have our program accept arguments when it'executed from the command line. So, here's our example:
./myprogram 42 -b -s
So our program would store the number 42 an an int and execute certain parts of code (depending on what arguments it gets). How can we do that?
1

Answer Wiki

Thanks. We'll let you know when a new response is added.

Hi 

you will use getopt.

 #include <ctype.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
 int
 main (int argc, char **argv)
 {
   int bflag = 0;
   int sflag = 0;
   int index;
   int c;
   opterr = 0;
   while ((c = getopt (argc, argv, “bs”)) != -1)
     switch (c)
       {
       case ‘b’:
         bflag = 1;
         break;
       case ‘s’:
         sflag = 1;
         break;
       case ‘?’:
         if (isprint (optopt))
           fprintf (stderr, “Unknown option `-%c’.\n”, optopt);
         else
           fprintf (stderr,
                    “Unknown option character `\\x%x’.\n”,
                    optopt);
         return 1;
       default:
         abort ();
       }
   printf (“bflag = %d, sflag = %d\n”, bflag, sflag);
   for (index = optind; index < argc; index++)
     printf (“Non-option argument %s\n”, argv[index]);
   return 0;
 }
Thanks & Regards
Clark Kent

Discuss This Question:  

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

Thanks! We'll email you when relevant content is added and updated.

Following

Share this item with your network: