Einzelnen Beitrag anzeigen

shmia

Registriert seit: 2. Mär 2004
5.508 Beiträge
 
Delphi 5 Professional
 
#1

Kommandozeilenparameter parsen

  Alt 15. Jun 2004, 16:54
Hallo,

heute zeige ich ein nützliche Unit, mit der man einfach die Kommandozeilenparameter einer Anwendung parsen kann.

Delphi-Quellcode:
unit UCommandLine;

interface

function GetCmdLineSwitch(const ASwitch: string; const IgnoreCase: Boolean = True): Boolean;
function GetCmdLineSwitchValue(out AValue: string; const ASwitch: string; const IgnoreCase: Boolean = True): Boolean;

implementation

uses
  SysUtils;

function GetCmdLineSwitch(const ASwitch: string; const IgnoreCase: Boolean = True): Boolean;
begin
  Result := FindCmdLineSwitch(ASwitch, ['-','/'], IgnoreCase);
end;


{**************************************************************************
* NAME:    FindCmdLineSwitchValue
* DESC:    Kommandozeilenparser für Optionen der Form:    ['-'|'/']Name[':'|'=']Wert
*
* Beispiel:
*  Kommandozeile "-a:WertA /b:WertB -c=WertC -d=WertD
*    FindCmdLineSwitchValue(Value,'a',False) ==> Result=True, Value=WertA
*    FindCmdLineSwitchValue(Value,'A',False) ==> Result=False
*    FindCmdLineSwitchValue(Value,'A',True) ==> Result=False, Value=WertA
* PARAMS:  out AValue: string; const ASwitch: string; const IgnoreCase: Boolean = True
* RESULT:  Boolean
* CREATED: 14-03-2003/haide
* CHANGED:
*************************************************************************}

function GetCmdLineSwitchValue(out AValue: string; const ASwitch: string; const IgnoreCase: Boolean = True): Boolean;
const
  CompareFunction: array[Boolean] of function(const s1,s2: string): Integer = ( CompareStr, CompareText );
var
  iCmdLine,iSplit: Integer;
  s,sName,sValue: String;
begin
  Result := False;

  for iCmdLine := 1 to ParamCount do
  begin
    s := ParamStr(iCmdLine);

    if not (s[1] in ['-','/']) then
      Continue;

    Delete(s,1,1);
    iSplit := Pos(':',s);
    if iSplit = 0 then
      iSplit := Pos('=',s);

    if iSplit = 0 then
      Continue;

    sName := Copy(s, 1, iSplit - 1);
    sValue := Copy(s, iSplit + 1, 666);

    if CompareFunction[IgnoreCase](ASwitch,sName) = 0 then
    begin
      AValue := sValue;
      Result := True;
      Break;
    end;
  end;
end;

end.
Knauserer, die jedes Kb sparen wollen, dürfen auch folgendes Fragment weglassen:
Delphi-Quellcode:
uses
  SysUtils;
function GetCmdLineSwitch(const ASwitch: string; const IgnoreCase: Boolean = True): Boolean;
begin
  Result := FindCmdLineSwitch(ASwitch, ['-','/'], IgnoreCase);
end;
und stattdessen bei Bedarf den Sourcecode von FindCmdLineSwitch aus der Unit SysUtils auskopieren.

[edit=Chakotay1308]Hinweis zur SysUtils eingefügt. Mfg, Chakotay1308[/edit]
[edit=Matze]Code formatiert. Mfg, Matze[/edit]
Angehängte Dateien
Dateityp: pas ucommandline.pas (2,0 KB, 161x aufgerufen)
Andreas
  Mit Zitat antworten Zitat