-1

In our Systems Programming class, we were given the assignment of recreating a simple 'ls' style program.

I am near completion and needed some guidance on how to determine which functions to execute based off of which flags were passed in.

I am able to loop through the char* argv[] array to determine which flags were used, but with 4 different options, I'm stuck on trying to find an efficient way to call functions.

The flags can be:

  • -l for long listing
  • -a for exposing hidden files
  • -U for unsorted listing
  • -s for sorted listing

These can be passed in any order.

Any tips?

Thanks all

rafa
  • 47
  • 8
  • Can you use [getopt(3)](https://www.freebsd.org/cgi/man.cgi?query=getopt&sektion=3)? – ghoti Sep 14 '15 at 04:03
  • possible duplicate of [Pass arguments into C program from command line](http://stackoverflow.com/questions/498320/pass-arguments-into-c-program-from-command-line) – gavv Sep 17 '15 at 14:55

1 Answers1

0

Have a series of flags indicating the options, then run through all the arguments setting each flag as appropriate. In pseudo-code, that would be something like:

flagLongListing = false
flagAllFiles = false
flagSorted = false

for each arg in args:
    if arg starts with '-':
        for each char in args[1:]:
            if char is 'l': flagLongListing = true
            if char is 'a': flagAllFiles = true
            if char is 'U': flagSorted = false
            if char is 's': flagSorted = true

and so on. This approach would handle all forms of option passing (combined, separate or a mixture):

ls -alU
ls -a -l -U
ls -al -U

Once you've finished processing the flags, you can go back and process the non-flags (like *.c if you're interested only in C files, for example).

But the output of each file would then be dictated by the flags that were set in the initial pass.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • I have something similar though how would I know if it was a -ls or -la? Would I have to create 2 different print functions to handle that? I have a way of figuring out which flags were used, but how can I call functions based off of that without making so many different function calls for every combination of characters? – rafa Sep 14 '15 at 03:55