Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run specific part of program from command line c [closed]

Tags:

c

I have a program that does two separate things. But I want to the program to only run one specific part based on what I enter in the command like in the format

program -a
program -s

where the a or s would be programmed to tell it to do something specific.

For example, if my program was something like:

# program -a entered
z = x + y
# program -s entered
z = x - y

Now I could easily do this with an if statement after running the program, but is it possible to directly skip to a statement like I said from the command prompt?

like image 202
mysterybands Avatar asked Dec 17 '22 20:12

mysterybands


2 Answers

int main(int argc, char* argv[]) {
    if (argc >= 2) {
        if (strcmp(argv[1], "-a") == 0) {
            z = x + y;
        } else if (strcmp(argv[1], "-s") == 0) {
            z = x - y;
        }
    }

    return 0;
}

Determine if the value of argv[1] equal to "-a" or "-s"

like image 79
sundb Avatar answered Dec 20 '22 10:12

sundb


You can use a switch statement on command-line arguments (in this case argv[1]).
argv[1] is a string containing the options you have given ("-a", "-s" etc).

But you have to perform certain checks for the validity of the command-line arguments before you can use them like this.

  1. Check if argc == 2
  2. Check if strlen(argv[1]) == 2
  3. Check if argv[1][0] == '-'

An MCVE would look like this:

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

int main(int argc, char* argv[]) {

    if(argc == 2 && strlen(argv[1]) == 2 && argv[1][0] == '-')
    {
        switch(argv[1][1])
        {
          case 'a':
           //do something 
             break;
          case 's':
           //do something else
             break;
          default:
           //do the default thing 
             break;
        }
    }
    else
    {
        //print appropriate error message
    }   
}
like image 20
P.W Avatar answered Dec 20 '22 10:12

P.W