Command Line Arguments in Pascal

Our program demonstrates how to work with command-line arguments. Here’s the full source code:

program CommandLineArguments;

uses
  SysUtils;

var
  i: Integer;
  argsWithProg: array of string;
  argsWithoutProg: array of string;
  arg: string;

begin
  // ParamStr(0) provides the program name, and ParamCount gives the number of additional arguments
  SetLength(argsWithProg, ParamCount + 1);
  for i := 0 to ParamCount do
    argsWithProg[i] := ParamStr(i);

  // Create an array without the program name
  SetLength(argsWithoutProg, ParamCount);
  for i := 1 to ParamCount do
    argsWithoutProg[i-1] := ParamStr(i);

  // You can get individual args with normal indexing
  if ParamCount >= 3 then
    arg := ParamStr(3)
  else
    arg := 'Not enough arguments';

  WriteLn(string.Join(' ', argsWithProg));
  WriteLn(string.Join(' ', argsWithoutProg));
  WriteLn(arg);
end.

In Pascal, we use the ParamStr function to access command-line arguments. ParamStr(0) gives the program name, and ParamStr(1) to ParamStr(ParamCount) provide the additional arguments.

To experiment with command-line arguments, compile the program first:

$ fpc command_line_arguments.pas
$ ./command_line_arguments a b c d
./command_line_arguments a b c d
a b c d
c

Note that Pascal arrays are typically 0-based, but ParamStr is 1-based for the arguments (0 is reserved for the program name). We’ve adjusted our code accordingly.

Next, we’ll look at more advanced command-line processing with options or flags, which would typically involve parsing the arguments manually or using a third-party library in Pascal.