0

I have to write an encrypt/decrypt C program and to start off it needs to take 6 CL arguments. This is normally fine for me, but this time the argument order needs to not matter. The flags also always match the argument type. eg. -t will always be before a csv file.

For example, the following are all equivalent ways to run the program and will yield the same behavior:

./encrypt -t mappingfile.csv -m 1 -i words.txt
./encrypt -m 2 -i words.txt -t mappingfile.csv
./encrypt -m 1 -i words_to_encrypt.txt -t mappingfile.csv

I'm not exactly sure how to check for this, any info helps! Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
AaronTrip
  • 1
  • 4

1 Answers1

1

If you don't want to use some other library and would rather handle everything yourself, you would want to run a loop to handle needed arguments.

Typically, if you are certain that a value will come after an argument, you can do something like this:

for( int i; i < argc; i++ ){
    if( [ argument is equal to some tag ] ){
        [ handle argument at args[i+1] ]
        i++; // Skip the next arg
    } else if ( [ argument is equal to next tag ] ) {

    } // Use for any additional tags you need
}

You can add a check before handling the argument to insure that i+1 does not pass the bound of the args array. To check if the argument is equal you could use the <string.h> function strcmp() or write your own.

Handling the argument could be something as simple as copying the string into some other char[] array or maybe even remembering the index of the desired argument. That all depends on how you want to use it.

Looping through the tags like this means you will not need them to be in any particular order.

--- Hope my first SA answer wasn't too bad :)

Grant
  • 75
  • 1
  • 7
  • @AaronTrip Glad I could help! -- If you feel this answers the question, could you select it as the answer? It would give us both some needed rep. – Grant Feb 03 '19 at 00:47