Sunday, May 18, 2008

Trick to track the argument in console

On last week, I was working so hard to put in three features for the search program.


- Search path. This feature allows dynamically to search the desired path
- List. This is to show out the search result.
- Output. Export search result to text file.

The first two already done. Third feature still in progress.

During this experience project, I found a very interesting issue. How to track the input passing in through the command line? Lets take a look:

void main(int argc, char *argv[], char *envp[])

Initially I was using argc to track how many command was passing in. This is not really a good method of doing this because when passing in more and more options, it duplicate the same task. Refer to the code below:

case 1: // no option was pass in

case 2: // 1st option was pass in

case 3: // 1st and 2nd option was pass in


case n: // until n number of option was pass in

Anyhow I have overcome this issue by tracking down the number of command passing in by using the argv pointer array. If argv[1] is empty, definitely I know that option number 1 is not there. Otherwise there must be an option passing in. For doing that, I just need a while loop to track every element in argv. But how do I know how many option was passing in? By using NULL checker? Actually I was using argc to get the total element in argv. I get this inspiration from MSDN.

No comments: