Click here to Skip to main content
Click here to Skip to main content
Go to top

Processing Command Line Arguments

, 27 Dec 2006
Rate this:
Please Sign up or sign in to vote.
This article describes an approach to processing multiple command line arguments.

Introduction

This article describes an approach to processing multiple command line arguments. The example provided illustrates processing a variable number of command line arguments, and further describes an approach to processing arguments using a key-value pair for each item processed. The additional examples provided illustrate approaches to processing single arguments and processing a variable number of arguments.

FallingSnow

Figure 1. Processing Multiple Command Line Arguments

Getting Started

There are three example projects included with this article; the examples include:

  • SingleCLA: A console mode application that processes a single command line argument.
  • VariableCLA: A console mode application that processes multiple command line arguments.
  • CommandLineArgs: A console mode application that processes a variable number of arguments in a manner consistent with processing a key-value pair.

You may open and examine each of the projects if you wish; however, the code is quite simple, and will be described in the following sections of this document. All examples were written using Visual Studio 2005 and are in C#; the same code could also be used in earlier versions of Visual Studio.

Code Example 1: Processing Single Command Line Arguments

The first example, SingleCLA, demonstrates an approach to processing a single command line argument. Command line arguments are processed in the Main function of the application, and it does not matter whether or not the application is a Windows application or a console mode application. The Main function accepts a string array as an argument list, and you may either ignore or process any or all of the list as you see fit. If you wanted to do something like open and process a file on initialization, you may wish to allow the application to accept a file path as an argument and process the associated file when the application is started. You may, however, process anything passed as an argument, not just file paths.

In the sample, the application is set up to process the first argument in the argument list; any additional arguments passed in are simply ignored. In this example, an integer value is passed to the Main function; the application will attempt to process the first argument in the list by squaring the value submitted and then displaying that value in the console.

The code used to perform these actions is as follows:

static void Main(string[] args)
{

    if (args.Length == 0)
    {
        Console.WriteLine("No arguments submitted");
        Console.ReadLine();
        return;
    }

    // processing a single argument
    Console.WriteLine("Squared Argument" + Environment.NewLine);

    // create variables to hold arguments
    Int32 orginalValue = 0;
    Int32 squaredValue = 0;

    try
    {
        orginalValue = int.Parse(args[0].ToString()); //first argument only
        squaredValue = orginalValue * orginalValue;
        Console.WriteLine(Environment.NewLine +  
            Convert.ToString(orginalValue) +
            " Squared = " + Convert.ToString(squaredValue) + 
            Environment.NewLine);
        Console.ReadLine();
        return;
    }
    catch
    {
        // display indication of invalid input from command line
        Console.WriteLine(Environment.NewLine + "Invalid Input" + 
             Environment.NewLine);
        Console.ReadLine();
        return;
    }
}

In this example, the code begins by checking to see if any arguments were passed to the Main function; if none were, the user is notified and the Main function is exited.

After making sure that we have an argument to process, the application prints a title out to the screen; two variables are then created and initialized; one will contain the value passed into the Main function as an argument, the second will contain the value obtained by squaring the original value.

Within the try-catch block, the application will assign the first argument in the argument list to the variable used to contain the original value; since the argument is passed as a string, it is converted to an integer value. Next, the original value is squared, and the squared value is assigned to the variable used to contain the original value squared. If the operation is successful, the results are displayed to the user; if the operation fails, the user will receive an indication that the input was invalid.

In order to test the command line interface from the the IDE, you may open the project properties, select the ‘Debug’ tab, and key an argument into the command line arguments field, as indicated in the following figure. You may wish to experiment with the command line here by keying in multiple values (separated by a space), different values, and no value.

Figure 2. Entering Command Line Arguments from the IDE

Figure 3. Results of Executing Example 1 with the Argument “222”

Code Example 2: Processing a Variable Number of Arguments

In this example (VariableCLA), the Main function is configured to process a variable number of arguments. The code is set to add up the values of all of the arguments passed to the function and then, after the last argument is included, return the result of the addition for display. The function will loop through any number of items passed into the Main function as arguments through the argument string array.

The code used in this example is as follows:

static void Main(string[] args)
{
    if (args.Length == 0)
    {
        Console.WriteLine("No arguments submitted");
        Console.ReadLine();
        return;
    }

    Console.WriteLine("Add All" + Environment.NewLine);

    // create variables to hold arguments
    int RunningTotal = 0;

    // populate the variables from the arguments
    for (int i = 0; i < args.Length; i++)
    {
        try
        {
            RunningTotal = RunningTotal + 
                 Convert.ToInt32(args[i].ToString());    
        }
        catch
        {
            // Display error if input is missing or invalid
            Console.WriteLine(Environment.NewLine + "Invalid Input" + 
                 Environment.NewLine);
            Console.ReadLine();
            return;
        }
    }

    Console.WriteLine(Environment.NewLine + "All numbers added = " + 
         RunningTotal.ToString() 
         + Environment.NewLine);
    Console.ReadLine();
    return;
}

As in the last example, this function begins by checking to see if any arguments were passed the the Main function; if none were, the function returns and displays a notice to the user that no arguments were received. Next, a title is printed to the console, and then a variable called “RunningTotal” is declared and initialized; this variable is used to capture the value of the added arguments.

After the variable declaration, the contents of the argument list are processed, and each value captured is added to the RunningTotal value. If an invalid value is encountered, the loop exits and the user is notified that an invalid value was submitted. If the entire argument list is processed without error, the function prints the total value calculated to the console.

To test the function, open up the Debug tab of the Properties page, and key some integer values into the Command Line Arguments field (arguments are delimited with a space):

Figure 4. Command Line Arguments

Entering the values indicated in figure 3 will result in this display when the application is executed:

Figure 5. Variable Command Line Arguments Running

Code Example 3: Processing a Variable Number of Arguments as Key and Value Pairs

This example demonstrates an approach where the application will process a variable number of arguments as a key and value pair. This approach would be useful if the function were to process any of a number of different activities each time it is executed but it is unknown as to which of the activities would be executed.

In this example, the arguments are processed as pairs where the first argument in the pair defines what value is to be set, and the second argument in each pair defines what value is to be applied to the first value. To illustrate the point, this function is set to process the status of four fictitious systems, the APU, and Engines 1, 2, and 3. Any of these systems can be set to any of three status types (Fire, OK, and Offline). Based upon the arguments passed to the function, as each pair is passed in, the effected system is identified in the first value of the pair, and the status of the identified system is set by the second value of the pair.

The code used in this example is as follows:

static void Main(string[] args)
{

    if (args.Length == 0)
    {
        Console.WriteLine("No arguments submitted");
        Console.ReadLine();
        return;
    }

    // processing a variable number of arguments as a key-value pair
    Console.WriteLine(Environment.NewLine + "Power/Propulsion" + 
         Environment.NewLine);

    // create variables to hold arguments
    string effectedSystem = "";
    string systemStatus = "";

    // populate the variables from the arguments, since we have key-value 
    // pairs passed in, we skip through them by twos
    for (int i = 0; i < args.Length; i+=2)
    {
        try
        {
            effectedSystem = args[i].ToString();    // first arg-the key
            systemStatus = args[i + 1].ToString();   // second arg-the value
        }
        catch
        {
            // if an incorrect number of items were listed, show the
            // correctly populated items and then exit out after a pause
            Console.ReadLine();
            return;
        }

        // sets the message associated with the system selected
        switch (systemStatus)
        {
            case "1":
                systemStatus = "FIRE";
                break;
            case "2":
                systemStatus = "OK";
                break;
            default:
                systemStatus = "OFFLINE";
                break;
        }

        // sets the system and displays the message
        switch (effectedSystem)
        {
            case "1":
                Console.WriteLine(Environment.NewLine + "(APU Fire Light)" + 
                     Environment.NewLine);
                Console.WriteLine("APU STATUS: " + systemStatus.ToString() + 
                     Environment.NewLine);
                break;
            case "2":
                Console.WriteLine(Environment.NewLine + "(Engine 1 Fire 
                     Light)" + Environment.NewLine);
                Console.WriteLine("ENG 1 STATUS: " + systemStatus.ToString() 
                     + Environment.NewLine);
                break;
            case "3":
                Console.WriteLine(Environment.NewLine + "(Engine 2 Fire 
                     Light)" + Environment.NewLine);
                Console.WriteLine("ENG 2 STATUS: " + systemStatus.ToString() 
                     + Environment.NewLine);
                break;
            case "4":
                Console.WriteLine(Environment.NewLine + "(Engine 3 Fire 
                     Light)" + Environment.NewLine);
                Console.WriteLine("ENG 3 STATUS: " + systemStatus.ToString() 
                     + Environment.NewLine);
                break;
            default:
                Console.WriteLine(Environment.NewLine + "INVALID ENTRY " + 
                     Environment.NewLine);
                break;
        }

    }

    // delay
    Console.ReadLine();
}

As with the previous examples, this code block begins by checking to see if any arguments were submitted. If so, the Main function writes out a title into the console window; if not, the user is notified that no arguments were submitted and the function returns.

Assuming there are some arguments to process, the next thing to do is to declare two variables, one to contain the system description, and one to contain the system status. After the variables are initialized, the argument array is evaluated in pairs; this is merely accomplished by cycling through the list whilst incrementing by twos.

In each pass, within a try-catch block, the current and next values from the argument list are used to set the system and status variables. If an error is encountered, the function notifies the user and the function returns. If no errors are detected, the two switch statements used evaluate the variables to format a message that will be displayed to the user regarding the system and its status. The first switch statement sets the status portion of the message to either “OK”, “FIRE”, or “OFFLINE”. When the second switch statement runs, the system portion of the message is set and combined with the status portion of the message, the combined values are then displayed to the user.

Each argument in the list will be processed in pairs and written out to the screen. Once all messages have been written out, the screen will pause waiting for a user input. When the user hits any key, the console window will close.

Figure 6. Command Line Arguments Passed to Example 3

Summary

This article demonstrates a few different ways to process command line arguments. Argument lists are passed to the Main function as string arrays, and naturally there are any number of alternative ways to process the contents of a string array. It was the intent of this article to demonstrate three possible approaches to include processing single arguments, a variable list of arguments, and a list of arguments presented as a simulation of key-value pair.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

salysle
Software Developer (Senior)
United States United States
No Biography provided

Comments and Discussions

 
GeneralDood... PinmemberMarc Leger25-Jun-07 10:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 27 Dec 2006
Article Copyright 2006 by salysle
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid