Sign in Join
Wiki copytemporary

Rosetta Stone: what changed

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

Title: Rosetta Stone

OldNewLine
1+## Introduction
2+
3+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.
4+
5+It can be handy to have a sort of "Rosetta stone" that roughly translates tasks from one environment/language into another.
6+
7+## Programming languages
8+
9+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.
10+
11+Some useful pages:
12+
13+- [<http://mc-computing.com/Languages/>](http://mc-computing.com/Languages/) This page has some explanation of the concepts involved
14+- [<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
15+- [[Pascal for C users]]
16+- [[Pascal for CSharp users]]
17+- [[Pascal for Java users]]
18+
19+## Operating systems
20+
21+If you know how to do something in an operating system, chances are you can do the same using FPC/Lazarus.
22+
23+The table below gives a rough mapping of some tasks:
24+
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>
181+
182+## Emulating uname
183+
184+Works on Linux, probably FreeBSD:
185+
186+``` pascal
187+program uname;
188+
189+uses baseunix;
190+
191+var KernelName: UtsName;
192+
193+begin
194+ fpuname(KernelName);
195+ writeln(kernelname.sysname);
196+ writeln(kernelname.nodename);
197+ writeln(kernelname.release);
198+ writeln(kernelname.version);
199+ writeln(kernelname.machine);
200+ writeln(kernelname.domain);
201+end.
202+```
203+
204+Sample output:
205+
206+`Linux`\
207+`mydebianmachine`\
208+`3.12-1-amd64`\
209+`#1 SMP Debian 3.12.6-2 (2013-12-29)`\
210+`x86_64`\
211+`(none)`
212+
213+## Emulating which
214+
215+Although Lazarus has FindDefaultExecutablePath, it has some flaws. Use e.g. this code:
216+
217+``` pascal
218+function Which(Executable: string): string;
219+var
220+ Output: string;
221+begin
222+ {$IFDEF UNIX}
223+ // Note: we're using external which because
224+ // FindDefaultExecutablePath
225+ // doesn't check if the user has execute permission
226+ // on the found file.
227+ ExecuteCommand('which '+Executable,Output,false);
228+ // Remove trailing LF(s) and other control codes:
229+ while (length(output)>0) and (ord(output[length(output)])<$20) do
230+ delete(output,length(output),1);
231+ {$ELSE}
232+ Output:=FindDefaultExecutablePath(Executable);
233+ {$ENDIF UNIX}
234+ // Extra check:
235+ if (Output<>'') and fileexists(Output) then
236+ begin
237+ result:=Output;
238+ end
239+ else
240+ begin
241+ result:=''; //command failed
242+ end;
243+end;
244+```
245+
246+## Emulating whoami
247+
248+... or getting the current user's operating system username. Returns a UTF8 string.
249+
250+``` pascal
251+uses
252+ {$IFDEF UNIX}
253+ {$IF (DEFINED(LINUX)) OR (DEFINED(FREEBSD))}
254+ ,users //not available on OSX
255+ {$ENDIF}
256+ ,baseunix //for fpgetuid
257+ .... //other unix stuff
258+ {$ENDIF}
259+ {$IFDEF MSWINDOWS}
260+ ,windows
261+ {$ENDIF}
262+ ,lazutf8
263+
264+function UserName: string;
265+// Get Operating System user name
266+{$IFDEF WINDOWS}
267+const
268+ MaxLen = 256;
269+var
270+ Len: DWORD;
271+ WS: WideString;
272+ Res: windows.BOOL;
273+{$ENDIF}
274+begin
275+ Result := '';
276+ {$IFDEF WINDOWS}
277+ Len := MaxLen;
278+ {$IFNDEF WINCE}
279+ // Check for Win98..WinME:
280+ if Win32MajorVersion <= 4 then
281+ begin
282+ SetLength(Result,MaxLen);
283+ Res := Windows.GetUserName(@Result[1], Len);
284+ if Res then
285+ begin
286+ SetLength(Result,Len-1);
287+ Result := SysToUtf8(Result);
288+ end
289+ else
290+ SetLength(Result,0);
291+ end
292+ else
293+ {$ENDIF NOT WINCE}
294+ begin
295+ SetLength(WS, MaxLen-1);
296+ Res := Windows.GetUserNameW(@WS[1], Len);
297+ if Res then
298+ begin
299+ SetLength(WS, Len - 1);
300+ Result := Utf16ToUtf8(WS);
301+ end
302+ else
303+ SetLength(Result,0);
304+ end;
305+ {$ENDIF WINDOWS}
306+ {$IFDEF UNIX}
307+ {$IF (DEFINED(LINUX)) OR (DEFINED(FREEBSD))}
308+ Result := SysToUtf8(GetUserName(fpgetuid));
309+ {$ENDIF}
310+ if Result = '' then
311+ Result := GetEnvironmentVariableUTF8('USER'); //fallback or other unixes which export $USER and don't support GetUserName
312+ {$ENDIF}
313+end;
314+```
315+
316+## Finding all occurrences of some bytes in a file
317+
318+A sort of grep. From forum post by KpjComp: [1](http://lazarus.freepascal.org/index.php/topic,16574.msg90287.html#msg90287)
319+
320+The block search class:
321+
322+``` pascal
323+unit block_search;
324+
325+{$mode objfpc}{$H+}
326+
327+interface
328+
329+uses
330+ Classes, SysUtils, fgl;
331+
332+type
333+
334+ { TBlockSearch }
335+ TBlockSearchResults = specialize TFPGList<int64>;
336+
337+ TBlockSearch = class
338+ private
339+ src:TStream;
340+ fresults:TBlockSearchResults;
341+ block:array of byte;
342+ public
343+ procedure SearchFor(a:array of byte);
344+ constructor Create(_Src:TStream; blocksize:integer = 1024*1024);
345+ destructor Destroy; override;
346+ property Results:TBlockSearchResults read fResults;
347+ end;
348+
349+implementation
350+
351+{ TBlockSearch }
352+
353+procedure TBlockSearch.SearchFor(a: array of byte);
354+var
355+ readsize:integer;
356+ fPos:Int64;
357+ fifoBuff:array of byte;
358+ fifoSt,fifoEn,searchLen,lpbyte:integer;
359+
360+ //
361+ procedure CheckPos;
362+ var
363+ l,p:integer;
364+ begin
365+ p := fifoST;
366+ for l := 0 to pred(SearchLen) do
367+ begin
368+ if a[l] <> fifoBuff[p] then exit;
369+ //p := (p+1) mod SearchLen, the if seems quicker
370+ inc(p); if p >= SearchLen then p := 0;
371+ end;
372+ fresults.Add(fpos-searchLen);
373+ end;
374+ //
375+begin
376+ fresults.clear;
377+ src.Position:=0;
378+ readsize := src.Read(block[0],Length(block));
379+ searchLen := length(a);
380+ if searchLen > length(block) then
381+ raise Exception.Create('Search term larger than blocksize');
382+ if readsize < searchLen then exit;
383+ setlength(fifoBuff,searchLen);
384+ move(block[0],fifoBuff[0],searchLen);
385+ fPos:=0;
386+ fifoSt:=0;
387+ fifoEn:=SearchLen-1;
388+ CheckPos;
389+ while readsize > 0 do
390+ begin
391+ for lpByte := 0 to pred(readsize) do
392+ begin
393+ inc(fifoSt); if fifoSt>=SearchLen then fifoST := 0;
394+ inc(fifoEn); if fifoEn>=SearchLen then fifoEn := 0;
395+ fifoBuff[fifoEn] := block[lpByte];
396+ inc(fPos);
397+ CheckPos;
398+ end;
399+ readsize := src.Read(block[0],Length(block));
400+ end;
401+end;
402+
403+constructor TBlockSearch.Create(_Src: TStream; blocksize: integer);
404+begin
405+ inherited Create;
406+ setlength(block,blocksize);
407+ src := _src;
408+ fresults := TBlockSearchResults.Create;
409+end;
410+
411+destructor TBlockSearch.Destroy;
412+begin
413+ freeAndNil(fresults);
414+ inherited Destroy;
415+end;
416+
417+end.
418+```
419+
420+Example of usage:
421+
422+``` pascal
423+var
424+ bs:TBlockSearch;
425+..
426+..
427+ bs := TBlockSearch.Create(SourceFile);
428+ try
429+ bs.SearchFor(WhatIAmSearchingFor);
430+ for i := 0 to bs.results.count-1 do
431+ begin
432+ // Example: we need to do something at an offset after the result
433+ SourceFile.Position := bs.Results.Items[i] + 5;
434+ SourceFile.ReadBuffer(RecordToParse, SizeOf(RecordToParse));
435+ // And now I work on the data in the second packed record of arrays and output to memo or whatever
436+ end;
437+ finally
438+ bs.free;
439+ end;
440+```
441+
442+## Search and replace in a file
443+
444+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.
445+
446+``` pascal
447+procedure FindAndReplace(SearchFor, ReplaceWith, FileName: string);
448+var
449+ FileContents: TStringList;
450+begin
451+ FileContents:=TStringList.Create;
452+ try
453+ FileContents.LoadFromFile(FileName);
454+ FileContents.Text:=StringReplace(FileContents.Text, SearchFor, ReplaceWith, [rfReplaceAll,rfIgnoreCase]);
455+ FileContents.SaveToFile(FileName);
456+ finally
457+ FileContents.Free;
458+ end;
459+end;
460+```
461+
462+---
463+*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).*
464+Category: Code
465+Category: Code Snippets
466+Category: FPC
467+Category: Lazarus
468+Category: Rosetta Stone
469+Category: Tutorials

Back to history