Back

Tip 33. Command Line Arguments.

The CommandParm() function will handle arguments passed into the application.

My technique for handling the string of arguments is to first break the arguments into an array ensuring that text inside single or double quotes are treated as a single argument.

I then loop through the array looking for known switches like -R . Once found I then check the arguments that go with that switch like -R <report> . This allows the user to enter the arguments in any order and have optional switches. If you only have a fixed number of arguments that are not optional you can simply access the argument array.

//---------------------------------------------------------------------------
//  Event Name : open for application
//     Purpose : decode cmdline and start app
//        Sets : None
//---------------------------------------------------------------------------
integer   li_argnct, li_pos1
string    ls_arg[]
string    ls_cmd
string    ls_filename, ls_report
integer   li_arg

   // Get the arguments and strip blanks 
   // from start and end of string
ls_cmd = Trim(CommandParm())

li_argcnt = 0

DO WHILE Len(ls_cmd ) > 0
   li_argcnt++

      // Check for quotes
   IF Left(ls_cmd, 1) = "'" THEN
            // Find the end single quote
      li_pos1 = Pos( ls_cmd, "'", 2)      
   ELSEIF Left(ls_cmd, 1) = '"' THEN
            // Find the end double quote
      li_pos1 = Pos( ls_cmd, '"', 2)            
   ELSE
         // Find the first blank
      li_pos1 = Pos( ls_cmd, " " )
   END IF

      // If no blanks (only one argument), 
      // set i to point to the hypothetical character
      // after the end of the string
   IF li_pos1 = 0 THEN
      li_pos1 = Len(ls_cmd) + 1
   END IF
   
      // Assign the arg to the argument array. 
      // Number of chars copied is one less than the 
   
      // position of the space found with Pos
   ls_arg[li_argcnt] = Left( ls_cmd, li_pos1 - 1 )

      // Remove the argument from the string 
      // so the next argument becomes first
   IF Left(ls_cmd, 1) = "'" OR Left(ls_cmd, 1) = '"' THEN
      ls_cmd = Trim(Replace( ls_cmd, 1, li_pos1 + 1, "" ))      
            // Remove first quote
      ls_arg[li_argcnt] = Replace( ls_arg[li_argcnt], 1, 1, "" )
   ELSE
      ls_cmd = Trim(Replace( ls_cmd, 1, li_pos1, "" ))
   END IF
LOOP

IF li_argcnt = 0 THEN
   ls_err_msg = "No Arguments found."
   MessageBox("Error", ls_err_msg)
   RETURN -1
END IF

ll_arg = 0
         // Parse the argument list
DO WHILE ll_arg < li_argcnt
   ll_arg++
   
   CHOOSE CASE Upper(ls_arg[ll_arg])
      CASE "-R"
                  // Report Name
         ll_arg++               
         ls_report = ls_arg[ll_arg]
      CASE "-F"
                  // Filename               
         ll_arg++               
         ls_filename = ls_arg[ll_arg]                     
   END CHOOSE
LOOP

Added before 01 Jan 2000

Back