Sign in Join
Wiki copytemporary

Rosetta Stone: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11## Introduction
22
33Often, people new to a programming language/library have trouble mapping the things they know how to do in other environments to the new environments.
44
55It can be handy to have a sort of "Rosetta stone" that roughly translates tasks from one environment/language into another.
66
77## Programming languages
88
99If 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.
1010
1111Some useful pages:
1212
1313- [<http://mc-computing.com/Languages/>](http://mc-computing.com/Languages/) This page has some explanation of the concepts involved
1414- [<http://rosettacode.org/wiki/Category:Pascal>](http://rosettacode.org/wiki/Category:Pascal) A huge number of languages, even esoteric, and tasks, make this site special
1515- [[Pascal for C users]]
1616- [[Pascal for CSharp users]]
1717- [[Pascal for Java users]]
1818
1919## Operating systems
2020
2121If you know how to do something in an operating system, chances are you can do the same using FPC/Lazarus.
2222
2323The table below gives a rough mapping of some tasks:
2424
25-<table>
26-<tbody>
27-<tr>
28-<td style="background:#f0f0f0;"><p><strong>Windows/DOS</strong></p></td>
29-<td style="background:#f0f0f0;"><p><strong>Unix/Linux</strong></p></td>
30-<td style="background:#f0f0f0;"><p><strong>Description</strong></p></td>
31-<td style="background:#f0f0f0;"><p><strong>FreePascal/Lazarus</strong></p></td>
32-</tr>
33-<tr>
34-<td><p>assoc</p></td>
35-<td></td>
36-<td><p>Show/edit file associations</p></td>
37-<td><p>See [[FileAssociation]]</p></td>
38-</tr>
39-<tr>
40-<td><p>copy</p></td>
41-<td><p>cp</p></td>
42-<td><p>Copy file</p></td>
43-<td><p>Lazarus [[CopyFile|fileutil.copyfile]]; roll your own with filestreams, see e.g. [[File Handling In Pascal|File_Handling_In_Pascal#FileCopy]]</p></td>
44-</tr>
45-<tr>
46-<td><p>date /t</p></td>
47-<td><p>date</p></td>
48-<td><p>Show current date</p></td>
49-<td><p>sysutils.now (date/time); sysutils.date (date); sysutils.time (time)</p></td>
50-</tr>
51-<tr>
52-<td><p>del, erase</p></td>
53-<td><p>rm, rm -f</p></td>
54-<td><p>Delete file</p></td>
55-<td><p>sysutils.deletefile, erase</p></td>
56-</tr>
57-<tr>
58-<td><p>deltree, rmdir /s</p></td>
59-<td><p>rm -r,rm -rf</p></td>
60-<td><p>Remove directories with subdirectories</p></td>
61-<td><p>Lazarus fileutil.deletedirectory</p></td>
62-</tr>
63-<tr>
64-<td><p>dir</p></td>
65-<td><p>ls</p></td>
66-<td><p>Find files in a directory</p></td>
67-<td><p>Lazarus [[FindAllFiles]]</p></td>
68-</tr>
69-<tr>
70-<td><p>diskpart list volume</p></td>
71-<td><p>mount</p></td>
72-<td><p>Show partitions/volumes/drives on a computer</p></td>
73-<td><p>Windows: see [[Windows Programming Tips|Windows_Programming_Tips#Listing_all_available_drives]]</p>
74-<p>Linux: see [[Linux Programming Tips|Linux_Programming_Tips#Get_the_list_of_mounted_partitions]]</p>
75-<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>
76-</tr>
77-<tr>
78-<td><p>find</p></td>
79-<td><p>grep</p></td>
80-<td><p>Search for a text/string</p></td>
81-<td><p>Several options, including the pos, ansipos functions. Regular expression support is provided by the [[RegEx packages]].</p></td>
82-</tr>
83-<tr>
84-<td><p>ldifde</p></td>
85-<td><p>ldapsearch</p></td>
86-<td><p>Search through Active Directory/LDAP</p></td>
87-<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>
88-</tr>
89-<tr>
90-<td><p>md5sum</p></td>
91-<td><p>md5sum</p></td>
92-<td><p>Calculate hash of file contents</p></td>
93-<td><p>You can use the MDFile function in the md5 FPC unit.</p></td>
94-</tr>
95-<tr>
96-<td><p>mkdir</p></td>
97-<td><p>mkdir</p></td>
98-<td><p>Create directory</p></td>
99-<td><p>mkdir; forcedirectories (creates entire path, if necessary)</p></td>
100-</tr>
101-<tr>
102-<td><p>move</p></td>
103-<td><p>mv</p></td>
104-<td><p>Move file to another directory</p></td>
105-<td><p>Within partition/disk: sysutils.renamefile; otherwise copy and delete original</p></td>
106-</tr>
107-<tr>
108-<td><p>rename, ren</p></td>
109-<td><p>mv</p></td>
110-<td><p>Rename file</p></td>
111-<td><p>sysutils.renamefile (can also "move" a file between directories, but only on same partition/disk</p></td>
112-</tr>
113-<tr>
114-<td><p>sc query &lt;servicename&gt;</p></td>
115-<td><p>service --status-all</p></td>
116-<td><p>Show status for service</p></td>
117-<td><p>See [[ServiceManager]]</p></td>
118-</tr>
119-<tr>
120-<td><p>?</p></td>
121-<td><p>sed -i 's|Delphi|FreePascal|g' readme.txt</p></td>
122-<td><p>Search and replace text in file.</p></td>
123-<td><p>See example code below.</p></td>
124-</tr>
125-<tr>
126-<td><p>shutdown</p></td>
127-<td><p>shutdown</p></td>
128-<td><p>Shut down computer</p></td>
129-<td><p>Windows: see <a href="http://forum.lazarus.freepascal.org/index.php/topic,16258.msg87992.html#msg87992">forum post</a></p></td>
130-</tr>
131-<tr>
132-<td><p>tasklist</p></td>
133-<td><p>ps</p></td>
134-<td><p>List or find processes</p></td>
135-<td><p>Windows: [[Windows Programming Tips|Windows_Programming_Tips#Showing.2Ffinding_processes]]</p></td>
136-</tr>
137-<tr>
138-<td><p>?</p></td>
139-<td><p>touch</p></td>
140-<td><p>Create a new empty file</p></td>
141-<td><p>sysutils.filecreate(filename)</p></td>
142-</tr>
143-<tr>
144-<td><p>?</p></td>
145-<td><p>touch</p></td>
146-<td><p>Modify file time</p></td>
147-<td><p>See [[Create a new file date/de]]</p></td>
148-</tr>
149-<tr>
150-<td><p>?</p></td>
151-<td><p>uname</p></td>
152-<td><p>Get kernel/system info</p></td>
153-<td><p>See uname function below.</p></td>
154-</tr>
155-<tr>
156-<td><p>wget, curl</p></td>
157-<td><p>wget, curl</p></td>
158-<td><p>Download file from HTTP/FTP</p></td>
159-<td><p>Multiple options, e.g. use synapse httpsend or ftpsend units: [[Synapse|Synapse#Downloading_files]]</p></td>
160-</tr>
161-<tr>
162-<td><p>?</p></td>
163-<td><p>which</p></td>
164-<td><p>Search for executable in path</p></td>
165-<td><p>Lazarus fileutil.FindDefaultExecutablePath; see also the example below.</p></td>
166-</tr>
167-<tr>
168-<td><p>?</p></td>
169-<td><p>whoami</p></td>
170-<td><p>Find out username</p></td>
171-<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>
172-</tr>
173-<tr>
174-<td></td>
175-<td></td>
176-<td></td>
177-<td></td>
178-</tr>
179-</tbody>
180-</table>
25+**Windows/DOS**
26+
27+**Unix/Linux**
28+
29+**Description**
30+
31+**FreePascal/Lazarus**
32+
33+assoc
34+
35+Show/edit file associations
36+
37+See [[FileAssociation]]
38+
39+copy
40+
41+cp
42+
43+Copy file
44+
45+Lazarus [[CopyFile|fileutil.copyfile]]; roll your own with filestreams, see e.g. [[File Handling In Pascal|File_Handling_In_Pascal#FileCopy]]
46+
47+date /t
48+
49+date
50+
51+Show current date
52+
53+sysutils.now (date/time); sysutils.date (date); sysutils.time (time)
54+
55+del, erase
56+
57+rm, rm -f
58+
59+Delete file
60+
61+sysutils.deletefile, erase
62+
63+deltree, rmdir /s
64+
65+rm -r,rm -rf
66+
67+Remove directories with subdirectories
68+
69+Lazarus fileutil.deletedirectory
70+
71+dir
72+
73+ls
74+
75+Find files in a directory
76+
77+Lazarus [[FindAllFiles]]
78+
79+diskpart list volume
80+
81+mount
82+
83+Show partitions/volumes/drives on a computer
84+
85+Windows: see [[Windows Programming Tips|Windows_Programming_Tips#Listing_all_available_drives]]
86+
87+Linux: see [[Linux Programming Tips|Linux_Programming_Tips#Get_the_list_of_mounted_partitions]]
88+
89+Unix: you'll have to parse some files (e.g. /etc/mtab) yourself, depending on Unix flavour; see [Forum post](http://lazarus.freepascal.org/index.php/topic,15943.msg86569.html#msg86569)
90+
91+find
92+
93+grep
94+
95+Search for a text/string
96+
97+Several options, including the pos, ansipos functions. Regular expression support is provided by the [[RegEx packages]].
98+
99+ldifde
100+
101+ldapsearch
102+
103+Search through Active Directory/LDAP
104+
105+Use [[Synapse]] ldapsend unit to work with LDAP queries; see e.g. [example code on Leonardo Ramé's blog](http://leonardorame.blogspot.com/2007_02_01_archive.html)
106+
107+md5sum
108+
109+md5sum
110+
111+Calculate hash of file contents
112+
113+You can use the MDFile function in the md5 FPC unit.
114+
115+mkdir
116+
117+mkdir
118+
119+Create directory
120+
121+mkdir; forcedirectories (creates entire path, if necessary)
122+
123+move
124+
125+mv
126+
127+Move file to another directory
128+
129+Within partition/disk: sysutils.renamefile; otherwise copy and delete original
130+
131+rename, ren
132+
133+mv
134+
135+Rename file
136+
137+sysutils.renamefile (can also "move" a file between directories, but only on same partition/disk
138+
139+sc query \<servicename\>
140+
141+service --status-all
142+
143+Show status for service
144+
145+See [[ServiceManager]]
146+
147+?
148+
149+sed -i 's\|Delphi\|FreePascal\|g' readme.txt
150+
151+Search and replace text in file.
152+
153+See example code below.
154+
155+shutdown
156+
157+shutdown
158+
159+Shut down computer
160+
161+Windows: see [forum post](http://forum.lazarus.freepascal.org/index.php/topic,16258.msg87992.html#msg87992)
162+
163+tasklist
164+
165+ps
166+
167+List or find processes
168+
169+Windows: [[Windows Programming Tips|Windows_Programming_Tips#Showing.2Ffinding_processes]]
170+
171+?
172+
173+touch
174+
175+Create a new empty file
176+
177+sysutils.filecreate(filename)
178+
179+?
180+
181+touch
182+
183+Modify file time
184+
185+See [[Create a new file date/de]]
186+
187+?
188+
189+uname
190+
191+Get kernel/system info
192+
193+See uname function below.
194+
195+wget, curl
196+
197+wget, curl
198+
199+Download file from HTTP/FTP
200+
201+Multiple options, e.g. use synapse httpsend or ftpsend units: [[Synapse|Synapse#Downloading_files]]
202+
203+?
204+
205+which
206+
207+Search for executable in path
208+
209+Lazarus fileutil.FindDefaultExecutablePath; see also the example below.
210+
211+?
212+
213+whoami
214+
215+Find out username
216+
217+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).
181218
182219## Emulating uname
183220
184221Works on Linux, probably FreeBSD:
185222
186223``` pascal
187224program uname;
188225
189226uses baseunix;
190227
191228var KernelName: UtsName;
192229
193230begin
194231 fpuname(KernelName);
195232 writeln(kernelname.sysname);
196233 writeln(kernelname.nodename);
197234 writeln(kernelname.release);
198235 writeln(kernelname.version);
199236 writeln(kernelname.machine);
200237 writeln(kernelname.domain);
201238end.
202239```
203240
204241Sample output:
205242
206243`Linux`\
207244`mydebianmachine`\
208245`3.12-1-amd64`\
209246`#1 SMP Debian 3.12.6-2 (2013-12-29)`\
210247`x86_64`\
211248`(none)`
212249
213250## Emulating which
214251
215252Although Lazarus has FindDefaultExecutablePath, it has some flaws. Use e.g. this code:
216253
217254``` pascal
218255function Which(Executable: string): string;
219256var
220257 Output: string;
221258begin
222259 {$IFDEF UNIX}
223260 // Note: we're using external which because
224261 // FindDefaultExecutablePath
225262 // doesn't check if the user has execute permission
226263 // on the found file.
227264 ExecuteCommand('which '+Executable,Output,false);
228265 // Remove trailing LF(s) and other control codes:
229266 while (length(output)>0) and (ord(output[length(output)])<$20) do
230267 delete(output,length(output),1);
231268 {$ELSE}
232269 Output:=FindDefaultExecutablePath(Executable);
233270 {$ENDIF UNIX}
234271 // Extra check:
235272 if (Output<>'') and fileexists(Output) then
236273 begin
237274 result:=Output;
238275 end
239276 else
240277 begin
241278 result:=''; //command failed
242279 end;
243280end;
244281```
245282
246283## Emulating whoami
247284
248285... or getting the current user's operating system username. Returns a UTF8 string.
249286
250287``` pascal
251288uses
252289 {$IFDEF UNIX}
253290 {$IF (DEFINED(LINUX)) OR (DEFINED(FREEBSD))}
254291 ,users //not available on OSX
255292 {$ENDIF}
256293 ,baseunix //for fpgetuid
257294 .... //other unix stuff
258295 {$ENDIF}
259296 {$IFDEF MSWINDOWS}
260297 ,windows
261298 {$ENDIF}
262299 ,lazutf8
263300
264301function UserName: string;
265302// Get Operating System user name
266303{$IFDEF WINDOWS}
267304const
268305 MaxLen = 256;
269306var
270307 Len: DWORD;
271308 WS: WideString;
272309 Res: windows.BOOL;
273310{$ENDIF}
274311begin
275312 Result := '';
276313 {$IFDEF WINDOWS}
277314 Len := MaxLen;
278315 {$IFNDEF WINCE}
279316 // Check for Win98..WinME:
280317 if Win32MajorVersion <= 4 then
281318 begin
282319 SetLength(Result,MaxLen);
283320 Res := Windows.GetUserName(@Result[1], Len);
284321 if Res then
285322 begin
286323 SetLength(Result,Len-1);
287324 Result := SysToUtf8(Result);
288325 end
289326 else
290327 SetLength(Result,0);
291328 end
292329 else
293330 {$ENDIF NOT WINCE}
294331 begin
295332 SetLength(WS, MaxLen-1);
296333 Res := Windows.GetUserNameW(@WS[1], Len);
297334 if Res then
298335 begin
299336 SetLength(WS, Len - 1);
300337 Result := Utf16ToUtf8(WS);
301338 end
302339 else
303340 SetLength(Result,0);
304341 end;
305342 {$ENDIF WINDOWS}
306343 {$IFDEF UNIX}
307344 {$IF (DEFINED(LINUX)) OR (DEFINED(FREEBSD))}
308345 Result := SysToUtf8(GetUserName(fpgetuid));
309346 {$ENDIF}
310347 if Result = '' then
311348 Result := GetEnvironmentVariableUTF8('USER'); //fallback or other unixes which export $USER and don't support GetUserName
312349 {$ENDIF}
313350end;
314351```
315352
316353## Finding all occurrences of some bytes in a file
317354
318355A sort of grep. From forum post by KpjComp: [1](http://lazarus.freepascal.org/index.php/topic,16574.msg90287.html#msg90287)
319356
320357The block search class:
321358
322359``` pascal
323360unit block_search;
324361
325362{$mode objfpc}{$H+}
326363
327364interface
328365
329366uses
330367 Classes, SysUtils, fgl;
331368
332369type
333370
334371 { TBlockSearch }
335372 TBlockSearchResults = specialize TFPGList<int64>;
336373
337374 TBlockSearch = class
338375 private
339376 src:TStream;
340377 fresults:TBlockSearchResults;
341378 block:array of byte;
342379 public
343380 procedure SearchFor(a:array of byte);
344381 constructor Create(_Src:TStream; blocksize:integer = 1024*1024);
345382 destructor Destroy; override;
346383 property Results:TBlockSearchResults read fResults;
347384 end;
348385
349386implementation
350387
351388{ TBlockSearch }
352389
353390procedure TBlockSearch.SearchFor(a: array of byte);
354391var
355392 readsize:integer;
356393 fPos:Int64;
357394 fifoBuff:array of byte;
358395 fifoSt,fifoEn,searchLen,lpbyte:integer;
359396
360397 //
361398 procedure CheckPos;
362399 var
363400 l,p:integer;
364401 begin
365402 p := fifoST;
366403 for l := 0 to pred(SearchLen) do
367404 begin
368405 if a[l] <> fifoBuff[p] then exit;
369406 //p := (p+1) mod SearchLen, the if seems quicker
370407 inc(p); if p >= SearchLen then p := 0;
371408 end;
372409 fresults.Add(fpos-searchLen);
373410 end;
374411 //
375412begin
376413 fresults.clear;
377414 src.Position:=0;
378415 readsize := src.Read(block[0],Length(block));
379416 searchLen := length(a);
380417 if searchLen > length(block) then
381418 raise Exception.Create('Search term larger than blocksize');
382419 if readsize < searchLen then exit;
383420 setlength(fifoBuff,searchLen);
384421 move(block[0],fifoBuff[0],searchLen);
385422 fPos:=0;
386423 fifoSt:=0;
387424 fifoEn:=SearchLen-1;
388425 CheckPos;
389426 while readsize > 0 do
390427 begin
391428 for lpByte := 0 to pred(readsize) do
392429 begin
393430 inc(fifoSt); if fifoSt>=SearchLen then fifoST := 0;
394431 inc(fifoEn); if fifoEn>=SearchLen then fifoEn := 0;
395432 fifoBuff[fifoEn] := block[lpByte];
396433 inc(fPos);
397434 CheckPos;
398435 end;
399436 readsize := src.Read(block[0],Length(block));
400437 end;
401438end;
402439
403440constructor TBlockSearch.Create(_Src: TStream; blocksize: integer);
404441begin
405442 inherited Create;
406443 setlength(block,blocksize);
407444 src := _src;
408445 fresults := TBlockSearchResults.Create;
409446end;
410447
411448destructor TBlockSearch.Destroy;
412449begin
413450 freeAndNil(fresults);
414451 inherited Destroy;
415452end;
416453
417454end.
418455```
419456
420457Example of usage:
421458
422459``` pascal
423460var
424461 bs:TBlockSearch;
425462..
426463..
427464 bs := TBlockSearch.Create(SourceFile);
428465 try
429466 bs.SearchFor(WhatIAmSearchingFor);
430467 for i := 0 to bs.results.count-1 do
431468 begin
432469 // Example: we need to do something at an offset after the result
433470 SourceFile.Position := bs.Results.Items[i] + 5;
434471 SourceFile.ReadBuffer(RecordToParse, SizeOf(RecordToParse));
435472 // And now I work on the data in the second packed record of arrays and output to memo or whatever
436473 end;
437474 finally
438475 bs.free;
439476 end;
440477```
441478
442479## Search and replace in a file
443480
444481This 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.
445482
446483``` pascal
447484procedure FindAndReplace(SearchFor, ReplaceWith, FileName: string);
448485var
449486 FileContents: TStringList;
450487begin
451488 FileContents:=TStringList.Create;
452489 try
453490 FileContents.LoadFromFile(FileName);
454491 FileContents.Text:=StringReplace(FileContents.Text, SearchFor, ReplaceWith, [rfReplaceAll,rfIgnoreCase]);
455492 FileContents.SaveToFile(FileName);
456493 finally
457494 FileContents.Free;
458495 end;
459496end;
460497```
461498
462499---
463500*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](/wiki-contact).*
464501Category: Code
465502Category: Code Snippets
466503Category: FPC
467504Category: Lazarus
468505Category: Rosetta Stone
469506Category: Tutorials

Back to history