Sign in Join
Wiki copytemporary

Revision 1 of 3, by Trev on 11-23-2021. The page as it is now.

Rosetta Stone

Introduction

Often, people new to a programming language/library have trouble mapping the things they know how to do in other environments to the new environments.

It can be handy to have a sort of "Rosetta stone" that roughly translates tasks from one environment/language into another.

Programming languages

If you have experience in other programming languages (such as C++, Visual Basic), there are some Rosetta stone web pages that might help you. As the Free Pascal/Lazarus syntax and library is fairly consistent with Delphi's, sites that "translate" to Delphi are also a valuable resource.

Some useful pages:

Operating systems

If you know how to do something in an operating system, chances are you can do the same using FPC/Lazarus.

The table below gives a rough mapping of some tasks:

<table> <tbody> <tr> <td style="background:#f0f0f0;"><p><strong>Windows/DOS</strong></p></td> <td style="background:#f0f0f0;"><p><strong>Unix/Linux</strong></p></td> <td style="background:#f0f0f0;"><p><strong>Description</strong></p></td> <td style="background:#f0f0f0;"><p><strong>FreePascal/Lazarus</strong></p></td> </tr> <tr> <td><p>assoc</p></td> <td></td> <td><p>Show/edit file associations</p></td> <td><p>See FileAssociation</p></td> </tr> <tr> <td><p>copy</p></td> <td><p>cp</p></td> <td><p>Copy file</p></td> <td><p>Lazarus fileutil.copyfile; roll your own with filestreams, see e.g. File_Handling_In_Pascal#FileCopy</p></td> </tr> <tr> <td><p>date /t</p></td> <td><p>date</p></td> <td><p>Show current date</p></td> <td><p>sysutils.now (date/time); sysutils.date (date); sysutils.time (time)</p></td> </tr> <tr> <td><p>del, erase</p></td> <td><p>rm, rm -f</p></td> <td><p>Delete file</p></td> <td><p>sysutils.deletefile, erase</p></td> </tr> <tr> <td><p>deltree, rmdir /s</p></td> <td><p>rm -r,rm -rf</p></td> <td><p>Remove directories with subdirectories</p></td> <td><p>Lazarus fileutil.deletedirectory</p></td> </tr> <tr> <td><p>dir</p></td> <td><p>ls</p></td> <td><p>Find files in a directory</p></td> <td><p>Lazarus FindAllFiles</p></td> </tr> <tr> <td><p>diskpart list volume</p></td> <td><p>mount</p></td> <td><p>Show partitions/volumes/drives on a computer</p></td> <td><p>Windows: see Windows_Programming_Tips#Listing_all_available_drives</p> <p>Linux: see Linux_Programming_Tips#Get_the_list_of_mounted_partitions</p> <p>Unix: you'll have to parse some files (e.g. /etc/mtab) yourself, depending on Unix flavour; see <a href="http://lazarus.freepascal.org/index.php/topic,15943.msg86569.html#msg86569">Forum post</a></p></td> </tr> <tr> <td><p>find</p></td> <td><p>grep</p></td> <td><p>Search for a text/string</p></td> <td><p>Several options, including the pos, ansipos functions. Regular expression support is provided by the RegEx packages.</p></td> </tr> <tr> <td><p>ldifde</p></td> <td><p>ldapsearch</p></td> <td><p>Search through Active Directory/LDAP</p></td> <td><p>Use Synapse ldapsend unit to work with LDAP queries; see e.g. <a href="http://leonardorame.blogspot.com/2007_02_01_archive.html">example code on Leonardo Ramé's blog</a></p></td> </tr> <tr> <td><p>md5sum</p></td> <td><p>md5sum</p></td> <td><p>Calculate hash of file contents</p></td> <td><p>You can use the MDFile function in the md5 FPC unit.</p></td> </tr> <tr> <td><p>mkdir</p></td> <td><p>mkdir</p></td> <td><p>Create directory</p></td> <td><p>mkdir; forcedirectories (creates entire path, if necessary)</p></td> </tr> <tr> <td><p>move</p></td> <td><p>mv</p></td> <td><p>Move file to another directory</p></td> <td><p>Within partition/disk: sysutils.renamefile; otherwise copy and delete original</p></td> </tr> <tr> <td><p>rename, ren</p></td> <td><p>mv</p></td> <td><p>Rename file</p></td> <td><p>sysutils.renamefile (can also "move" a file between directories, but only on same partition/disk</p></td> </tr> <tr> <td><p>sc query <servicename></p></td> <td><p>service --status-all</p></td> <td><p>Show status for service</p></td> <td><p>See ServiceManager</p></td> </tr> <tr> <td><p>?</p></td> <td><p>sed -i 's|Delphi|FreePascal|g' readme.txt</p></td> <td><p>Search and replace text in file.</p></td> <td><p>See example code below.</p></td> </tr> <tr> <td><p>shutdown</p></td> <td><p>shutdown</p></td> <td><p>Shut down computer</p></td> <td><p>Windows: see <a href="http://forum.lazarus.freepascal.org/index.php/topic,16258.msg87992.html#msg87992">forum post</a></p></td> </tr> <tr> <td><p>tasklist</p></td> <td><p>ps</p></td> <td><p>List or find processes</p></td> <td><p>Windows: Windows_Programming_Tips#Showing.2Ffinding_processes</p></td> </tr> <tr> <td><p>?</p></td> <td><p>touch</p></td> <td><p>Create a new empty file</p></td> <td><p>sysutils.filecreate(filename)</p></td> </tr> <tr> <td><p>?</p></td> <td><p>touch</p></td> <td><p>Modify file time</p></td> <td><p>See Create a new file date/de</p></td> </tr> <tr> <td><p>?</p></td> <td><p>uname</p></td> <td><p>Get kernel/system info</p></td> <td><p>See uname function below.</p></td> </tr> <tr> <td><p>wget, curl</p></td> <td><p>wget, curl</p></td> <td><p>Download file from HTTP/FTP</p></td> <td><p>Multiple options, e.g. use synapse httpsend or ftpsend units: Synapse#Downloading_files</p></td> </tr> <tr> <td><p>?</p></td> <td><p>which</p></td> <td><p>Search for executable in path</p></td> <td><p>Lazarus fileutil.FindDefaultExecutablePath; see also the example below.</p></td> </tr> <tr> <td><p>?</p></td> <td><p>whoami</p></td> <td><p>Find out username</p></td> <td><p>See UserName function below. On Windows: you can check if you're Administrator: winutils.iswindowsadmin(). On *nix: fpgeteuid shows you the effective userid (0 for root).</p></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table>

Emulating uname

Works on Linux, probably FreeBSD:

pascal
program uname;

uses  baseunix;

var KernelName: UtsName;

begin
 fpuname(KernelName);
 writeln(kernelname.sysname);
 writeln(kernelname.nodename);
 writeln(kernelname.release);
 writeln(kernelname.version);
 writeln(kernelname.machine);
 writeln(kernelname.domain);
end.

Sample output:

Linux
mydebianmachine
3.12-1-amd64
#1 SMP Debian 3.12.6-2 (2013-12-29)
x86_64
(none)

Emulating which

Although Lazarus has FindDefaultExecutablePath, it has some flaws. Use e.g. this code:

pascal
function Which(Executable: string): string;
var
  Output: string;
begin
  {$IFDEF UNIX}
  // Note: we're using external which because
  // FindDefaultExecutablePath
  // doesn't check if the user has execute permission
  // on the found file.
  ExecuteCommand('which '+Executable,Output,false);
  // Remove trailing LF(s) and other control codes:
  while (length(output)>0) and (ord(output[length(output)])<$20) do
    delete(output,length(output),1);
  {$ELSE}
  Output:=FindDefaultExecutablePath(Executable);
  {$ENDIF UNIX}
  // Extra check:
  if (Output<>'') and fileexists(Output) then
  begin
    result:=Output;
  end
  else
  begin
    result:=''; //command failed
  end;
end;

Emulating whoami

... or getting the current user's operating system username. Returns a UTF8 string.

pascal
uses
  {$IFDEF UNIX}
  {$IF (DEFINED(LINUX)) OR (DEFINED(FREEBSD))}
  ,users //not available on OSX
  {$ENDIF}
  ,baseunix //for fpgetuid
  .... //other unix stuff
  {$ENDIF}
  {$IFDEF MSWINDOWS}
  ,windows
  {$ENDIF}
  ,lazutf8

function UserName: string;
// Get Operating System user name
{$IFDEF WINDOWS}
const
  MaxLen = 256;
var
  Len: DWORD;
  WS: WideString;
  Res: windows.BOOL;
{$ENDIF}
begin
  Result := '';
  {$IFDEF WINDOWS}
    Len := MaxLen;
    {$IFNDEF WINCE}
    // Check for Win98..WinME:
    if Win32MajorVersion <= 4 then
    begin
      SetLength(Result,MaxLen);
      Res := Windows.GetUserName(@Result[1], Len);
      if Res then
      begin
        SetLength(Result,Len-1);
        Result := SysToUtf8(Result);
      end
      else
        SetLength(Result,0);
    end
    else
    {$ENDIF NOT WINCE}
    begin
      SetLength(WS, MaxLen-1);
      Res := Windows.GetUserNameW(@WS[1], Len);
      if Res then
      begin
        SetLength(WS, Len - 1);
        Result := Utf16ToUtf8(WS);
      end
      else
        SetLength(Result,0);
    end;
    {$ENDIF WINDOWS}
    {$IFDEF UNIX}
    {$IF (DEFINED(LINUX)) OR (DEFINED(FREEBSD))}
    Result := SysToUtf8(GetUserName(fpgetuid));
    {$ENDIF}
    if Result = '' then
      Result := GetEnvironmentVariableUTF8('USER'); //fallback or other unixes which export $USER and don't support GetUserName
  {$ENDIF}
end;

Finding all occurrences of some bytes in a file

A sort of grep. From forum post by KpjComp: 1

The block search class:

pascal
unit block_search;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, fgl;

type

  { TBlockSearch }
  TBlockSearchResults = specialize TFPGList<int64>;

  TBlockSearch = class
  private
    src:TStream;
    fresults:TBlockSearchResults;
    block:array of byte;
  public
    procedure SearchFor(a:array of byte);
    constructor Create(_Src:TStream; blocksize:integer = 1024*1024);
    destructor Destroy; override;
    property Results:TBlockSearchResults read fResults;
  end;

implementation

{ TBlockSearch }

procedure TBlockSearch.SearchFor(a: array of byte);
var
  readsize:integer;
  fPos:Int64;
  fifoBuff:array of byte;
  fifoSt,fifoEn,searchLen,lpbyte:integer;

  //
  procedure CheckPos;
  var
    l,p:integer;
  begin
    p := fifoST;
    for l := 0 to pred(SearchLen) do
    begin
      if a[l] <> fifoBuff[p] then exit;
      //p := (p+1) mod SearchLen,   the if seems quicker
      inc(p); if p >= SearchLen then p := 0;
    end;
    fresults.Add(fpos-searchLen);
  end;
  //
begin
  fresults.clear;
  src.Position:=0;
  readsize := src.Read(block[0],Length(block));
  searchLen := length(a);
  if searchLen > length(block) then
    raise Exception.Create('Search term larger than blocksize');
  if readsize < searchLen then exit;
  setlength(fifoBuff,searchLen);
  move(block[0],fifoBuff[0],searchLen);
  fPos:=0;
  fifoSt:=0;
  fifoEn:=SearchLen-1;
  CheckPos;
  while readsize > 0 do
  begin
    for lpByte := 0 to pred(readsize) do
    begin
      inc(fifoSt); if fifoSt>=SearchLen then fifoST := 0;
      inc(fifoEn); if fifoEn>=SearchLen then fifoEn := 0;
      fifoBuff[fifoEn] := block[lpByte];
      inc(fPos);
      CheckPos;
    end;
    readsize := src.Read(block[0],Length(block));
  end;
end;

constructor TBlockSearch.Create(_Src: TStream; blocksize: integer);
begin
  inherited Create;
  setlength(block,blocksize);
  src := _src;
  fresults := TBlockSearchResults.Create;
end;

destructor TBlockSearch.Destroy;
begin
  freeAndNil(fresults);
  inherited Destroy;
end;

end.

Example of usage:

pascal
var
  bs:TBlockSearch;
..
..
  bs := TBlockSearch.Create(SourceFile);
  try
    bs.SearchFor(WhatIAmSearchingFor);
    for i := 0 to bs.results.count-1 do
    begin
      // Example: we need to do something at an offset after the result
      SourceFile.Position := bs.Results.Items[i] + 5;
      SourceFile.ReadBuffer(RecordToParse, SizeOf(RecordToParse)); 
      // And now I work on the data in the second packed record of arrays and output to memo or whatever
    end;
  finally
    bs.free;
  end;

Search and replace in a file

This will search and replace by loading the entire file into the stringlist in memory and replacing there, then saving the stringlist again. While fine for small files, performance will likely suffer for large files.

pascal
procedure FindAndReplace(SearchFor, ReplaceWith, FileName: string);
var
  FileContents: TStringList;
begin
  FileContents:=TStringList.Create;
  try
    FileContents.LoadFromFile(FileName);
    FileContents.Text:=StringReplace(FileContents.Text, SearchFor, ReplaceWith, [rfReplaceAll,rfIgnoreCase]);
    FileContents.SaveToFile(FileName);
  finally
    FileContents.Free;
  end;
end;

From the Free Pascal wiki, page "Rosetta Stone", as it stood on 2021-11-23 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.