[Previous][Up] |
The simplest way to use CmdLine unit is to create a callback function that will be called for each parameter of the command line.
1 (*demo1.pas*) 2 program Demo1; 3 {$mode objfpc}{$h+} 4 uses 5 Classes, SysUtils, CmdLine; 6 7 procedure Handler(Kind: TOptionKind; const Option, Value: String); 8 begin 9 case Kind of 10 okShort: WriteLn('opt: -', Option); 11 okLong: WriteLn('opt: --', Option); 12 okShortWithVal: WriteLn('opt: -', Option, '=', Value); 13 okLongWithVal: WriteLn('opt: --', Option, '=', Value); 14 okArgument: WriteLn('arg: ', Value); 15 end; 16 end; 17 18 begin 19 SetCallback(@Handler); 20 InitializeCommandLineScan; 21 ScanCommandLine; 22 FinalizeCommandLineScan; 23 end.
Lines 7-16: Here is the callback function that will be called for each parameter of the command line. It receives the parameters of the command line already identified (Kind) and cut into option (Option) and value (Value).
Line 19: Here we set the callback function.
Line 20: Prepare for scanning.
Line 21: Do command line scanning.
Trying this program you’ll get something like:
------------------------------------------------------------------------------ ~$ ./demo_1 -a --long-a -b=45 --long-b=78 arg1 arg2 arg3 -- -s --long-s opt: -a opt: --long-a opt: -b=45 opt: --long-b=78 arg: arg1 arg: arg2 arg: arg3 arg: -s arg: --long-s ------------------------------------------------------------------------------
You can see that :