Function Abs (X : Every numerical type) : Every numerical type;
Abs returns the absolute value of a variable. The result of the function has the same type as its argument, which can be any numerical type.
None.
{
Program Example1; { Program to demonstrate the Abs function. } Var r : real; i : integer; begin r:=abs(-1.0); { r:=1.0 } i:=abs(-21); { i:=21 } end.
Function Addr (X : Any type) : Pointer;
Addr returns a pointer to its argument, which can be any type, or a function or procedure name. The returned pointer isn't typed. The same result can be obtained by the @ operator, which can return a typed pointer (Programmer's guide\).
None
{
Program Example2; { Program to demonstrate the Addr function. } Const Zero : integer = 0; Var p : pointer; i : Integer; begin p:=Addr(p); { P points to itself } p:=Addr(I); { P points to I } p:=Addr(Zero); { P points to 'Zero' } end.
Procedure Append (Var F : Text) ;
Append opens an existing file in append mode. Any data written to F will be appended to the file. If the file didn't exist, it will be created, contrary to the Turbo Pascal implementation of Append, where a file needed to exist in order to be opened by append.
Only text files can be opened in append mode.
If the file can't be created, a run-time error will be generated.
{
Program Example3; { Program to demonstrate the Append function. } Var f : text; begin Assign (f,'test.txt'); Rewrite (f); { file is opened for write, and emptied } Writeln (F,'This is the first line of text.txt'); close (f); Append(f); { file is opened for write, but NOT emptied. any text written to it is appended.} Writeln (f,'This is the second line of text.txt'); close (f); end.
Function Arctan (X : Real) : Real;
Arctan returns the Arctangent of X, which can be any Real type. The resulting angle is in radial units.
None
{
Program Example4; { Program to demonstrate the ArcTan function. } Var R : Real; begin R:=ArcTan(0); { R:=0 } R:=ArcTan(1)/pi; { R:=0.25 } end.
Procedure Assign (Var F; Name : String) ;
Assign assigns a name to F, which can be any file type. This call doesn't open the file, it just assigns a name to a file variable, and marks the file as closed.
None.
{
Program Example5; { Program to demonstrate the Assign function. } Var F : text; begin Assign (F,''); Rewrite (f); { The following can be put in any file by redirecting it from the command line.} Writeln (f,'This goes to standard output !'); Close (f); Assign (F,'Test.txt'); rewrite (f); writeln (f,'This doesn''t go to standard output !'); close (f); end.
Procedure Blockread (Var F : File; Var Buffer; Var Count : Longint [; var Result : Longint]) ;
Blockread reads count or less records from file F. The result is placed in Buffer, which must contain enough room for Count records. The function cannot read partial records.
If Result is specified, it contains the number of records actually read. If Result isn't specified, and less than Count records were read, a run-time error is generated. This behavior can be controlled by the {$i} switch.
If Result isn't specified, then a run-time error is generated if less than count records were read.
Blockwrite, Close, Reset, Assign
{
Program Example6; { Program to demonstrate the BlockRead and BlockWrite functions. } Var Fin, fout : File; NumRead,NumWritten : Word; Buf : Array[1..2048] of byte; Total : Longint; begin Assign (Fin, Paramstr(1)); Assign (Fout,Paramstr(2)); Reset (Fin,1); Rewrite (Fout,1); Total:=0; Repeat BlockRead (Fin,buf,Sizeof(buf),NumRead); BlockWrite (Fout,Buf,NumRead,NumWritten); inc(Total,NumWritten); Until (NumRead=0) or (NumWritten<>NumRead); Write ('Copied ',Total,' bytes from file ',paramstr(1)); Writeln (' to file ',paramstr(2)); end.
Procedure Blockwrite (Var F : File; Var Buffer; Var Count : Longint) ;
BlockWrite writes count records from buffer to the file F. If the records couldn't be written to disk, a run-time error is generated. This behavior can be controlled by the {$i} switch.
A run-time error is generated if, for some reason, the records couldn't be written to disk.
Blockread,Close, Rewrite, Assign
For the example, see Blockread.
Procedure Chdir (const S : string) ;
Chdir changes the working directory of the process to S.
If the directory S doesn't exist, a run-time error is generated.
{
Program Example7; { Program to demonstrate the ChDir function. } begin {$I-} ChDir (ParamStr(1)); if IOresult<>0 then Writeln ('Cannot change to directory : ',paramstr (1)); end.
Function Chr (X : byte) : Char;
Chr returns the character which has ASCII value X.
None.
{
Program Example8; { Program to demonstrate the Chr function. } begin Write (chr(10),chr(13)); { The same effect as Writeln; } end.
Procedure Close (Var F : Anyfiletype) ;
Close flushes the buffer of the file F and closes F. After a call to Close, data can no longer be read from or written to F.
To reopen a file closed with Close, it isn't necessary to assign the file again. A call to Reset or Rewrite is sufficient.
None.
{
Program Example9; { Program to demonstrate the Close function. } Var F : text; begin Assign (f,'Test.txt'); ReWrite (F); Writeln (F,'Some text written to Test.txt'); close (f); { Flushes contents of buffer to disk, closes the file. Omitting this may cause data NOT to be written to disk.} end.
Function Concat (S1,S2 [,S3, ... ,Sn]) : String;
Concat concatenates the strings S1,S2 etc. to one long string. The resulting string is truncated at a length of 255 bytes.
The same operation can be performed with the + operation.
None.
Copy, Delete, Insert, Pos, Length
{
Program Example10; { Program to demonstrate the Concat function. } Var S : String; begin S:=Concat('This can be done',' Easier ','with the + operator !'); end.
Function Copy (Const S : String;Index : Integer;Count : Byte) : String;
Copy returns a string which is a copy if the Count characters in S, starting at position Index. If Count is larger than the length of the string S, the result is truncated.
If Index is larger than the length of the string S, then an empty string is returned.
None.
{
Program Example11; { Program to demonstrate the Copy function. } Var S,T : String; begin T:='1234567'; S:=Copy (T,1,2); { S:='12' } S:=Copy (T,4,2); { S:='45' } S:=Copy (T,4,8); { S:='4567' } end.
Function Cos (X : Real) : Real;
Cos returns the cosine of X, where X is an angle, in radians.
None.
{
Program Example12; { Program to demonstrate the Cos function. } Var R : Real; begin R:=Cos(Pi); { R:=-1 } R:=Cos(Pi/2); { R:=0 } R:=Cos(0); { R:=1 } end.
Function CSeg : Word;
CSeg returns the Code segment register. In Free Pascal, it returns always a zero, since Free Pascal is a 32 bit compiler.
None.
{
Program Example13; { Program to demonstrate the CSeg function. } var W : word; begin W:=CSeg; {W:=0, provided for comppatibility, FPC is 32 bit.} end.
Procedure Dec (Var X : Any ordinal type[; Decrement : Longint]) ;
Dec decreases the value of X with Decrement. If Decrement isn't specified, then 1 is taken as a default.
A range check can occur, or an underflow error, if you try to decrease X below its minimum value.
{
Program Example14; { Program to demonstrate the Dec function. } Var I : Integer; L : Longint; W : Word; B : Byte; Si : ShortInt; begin I:=1; L:=2; W:=3; B:=4; Si:=5; Dec (i); { i:=0 } Dec (L,2); { L:=0 } Dec (W,2); { W:=1 } Dec (B,-2); { B:=6 } Dec (Si,0); { Si:=5 } end.
Procedure Delete (var S : string;Index : Integer;Count : Integer) ;
Delete removes Count characters from string S, starting at position Index. All remaining characters are shifted Count positions to the left, and the length of the string is adjusted.
None.
{
Program Example15; { Program to demonstrate the Delete function. } Var S : String; begin S:='This is not easy !'; Delete (S,9,4); { S:='This is easy !' } end.
Procedure Dispose (P : pointer) ;
Dispose releases the memory allocated with a call to New. The pointer P must be typed. The released memory is returned to the heap.
An error will occur if the pointer doesn't point to a location in the heap.
{
Program Example16; { Program to demonstrate the Dispose and New functions. } Type SS = String[20]; AnObj = Object I : integer; Constructor Init; Destructor Done; end; Var P : ^SS; T : ^AnObj; Constructor Anobj.Init; begin Writeln ('Initializing an instance of AnObj !'); end; Destructor AnObj.Done; begin Writeln ('Destroying an instance of AnObj !'); end; begin New (P); P^:='Hello, World !'; Dispose (P); { P is undefined from here on !} New(T,Init); T^.i:=0; Dispose (T,Done); end.
Function DSeg : Word;
DSeg returns the data segment register. In Free Pascal, it returns always a zero, since Free Pascal is a 32 bit compiler.
None.
{
Program Example17; { Program to demonstrate the DSeg function. } Var W : Word; begin W:=DSeg; {W:=0, This function is provided for compatibility, FPC is a 32 bit comiler.} end.
Function Eof [(F : Any file type)] : Boolean;
Eof returns True if the file-pointer has reached the end of the file, or if the file is empty. In all other cases Eof returns False.
If no file F is specified, standard input is assumed.
None.
{
Program Example18; { Program to demonstrate the Eof function. } Var T1,T2 : text; C : Char; begin { Set file to read from. Empty means from standard input.} assign (t1,paramstr(1)); reset (t1); { Set file to write to. Empty means to standard output. } assign (t2,paramstr(2)); rewrite (t2); While not eof(t1) do begin read (t1,C); write (t2,C); end; Close (t1); Close (t2); end.
Function Eoln [(F : Text)] : Boolean;
Eof returns True if the file pointer has reached the end of a line, which is demarcated by a line-feed character (ASCII value 10), or if the end of the file is reached. In all other cases Eof returns False.
If no file F is specified, standard input is assumed. It can only be used on files of type Text.
None.
{
Program Example19; { Program to demonstrate the Eoln function. } begin { This program waits for keyboard input. } { It will print True when an empty line is put in, and false when you type a non-empty line. It will only stop when you press enter.} Writeln (eoln); end.
Procedure Erase (Var F : Any file type) ;
Erase removes an unopened file from disk. The file should be assigned with Assign, but not opened with Reset or Rewrite
A run-time error will be generated if the specified file doesn't exist.
{
Program Example20; { Program to demonstrate the Erase function. } Var F : Text; begin { Create a file with a line of text in it} Assign (F,'test.txt'); Rewrite (F); Writeln (F,'Try and find this when I''m finished !'); close (f); { Now remove the file } Erase (f); end.
Procedure Exit ([Var X : return type )] ;
Exit exits the current subroutine, and returns control to the calling routine. If invoked in the main program routine, exit stops the program.
The optional argument X allows to specify a return value, in the case Exit is invoked in a function. The function result will then be equal to X.
None.
{
Program Example21; { Program to demonstrate the Exit function. } Procedure DoAnExit (Yes : Boolean); { This procedure demonstrates the normal Exit } begin Writeln ('Hello from DoAnExit !'); If Yes then begin Writeln ('Bailing out early.'); exit; end; Writeln ('Continuing to the end.'); end; Function Positive (Which : Integer) : Boolean; { This function demonstrates the extra FPC feature of Exit : You can specify a return value for the function } begin if Which>0 then exit (True) else exit (False); end; begin { This call will go to the end } DoAnExit (False); { This call will bail out early } DoAnExit (True); if Positive (-1) then Writeln ('The compiler is nuts, -1 is not positive.') else Writeln ('The compiler is not so bad, -1 seems to be negative.'); end.
Function Exp (Var X : Real) : Real;
Exp returns the exponent of X, i.e. the number e to the power X.
None.
{
Program Example22; { Program to demonstrate the Exp function. } begin Writeln (Exp(1):8:2); { Should print 2.72 } end.
Function Filepos (Var F : Any file type) : Longint;
Filepos returns the current record position of the file-pointer in file F. It cannot be invoked with a file of type Text.
None.
{
Program Example23; { Program to demonstrate the FilePos function. } Var F : File of Longint; L,FP : longint; begin { Fill a file with data : Each position contains the position ! } Assign (F,'test.dat'); Rewrite (F); For L:=0 to 100 do begin FP:=FilePos(F); Write (F,FP); end; Close (F); Reset (F); { If ll goes well, nothing is displayed here. } While not (Eof(F)) do begin FP:=FilePos (F); Read (F,L); if L<>FP then Writeln ('Something is wrong here ! : Got ',l,' on pos ',FP); end; Close (F); Erase (f); end.
Function Filesize (Var F : Any file type) : Longint;
Filepos returns the total number of records in file F. It cannot be invoked with a file of type Text. (under LINUX, this also means that it cannot be invoked on pipes.)
If F is empty, 0 is returned.
None.
{
Program Example24; { Program to demonstrate the FileSize function. } Var F : File Of byte; L : File Of Longint; begin Assign (F,paramstr(1)); Reset (F); Writeln ('File size in bytes : ',FileSize(F)); Close (F); Assign (L,paramstr (1)); Reset (L); Writeln ('File size in Longints : ',FileSize(L)); Close (f); end.
Procedure Fillchar (Var X;Count : Longint;Value : char or byte); ;
Fillchar fills the memory starting at X with Count bytes or characters with value equal to Value.
No checking on the size of X is done.
{
Program Example25; { Program to demonstrate the FillChar function. } Var S : String[10]; I : Byte; begin For i:=10 downto 0 do begin { Fill S with i spaces } FillChar (S,SizeOf(S),' '); { Set Length } S[0]:=chr(i); Writeln (s,'*'); end; end.
Procedure Fillword (Var X;Count : Longint;Value : Word); ;
Fillword fills the memory starting at X with Count words with value equal to Value.
No checking on the size of X is done.
{
Program Example76; { Program to demonstrate the FillWord function. } Var W : Array[1..100] of Word; begin { Quick initialization of array W } FillWord(W,100,0); end.
Procedure Flush (Var F : Text) ;
Flush empties the internal buffer of file F and writes the contents to disk. The file is not closed as a result of this call.
If the disk is full, a run-time error will be generated.
{
Program Example26; { Program to demonstrate the Flush function. } Var F : Text; begin { Assign F to standard output } Assign (F,''); Rewrite (F); Writeln (F,'This line is written first, but appears later !'); { At this point the text is in the internal pascal buffer, and not yet written to standard output } Writeln ('This line appears first, but is written later !'); { A writeln to 'output' always causes a flush - so this text is written to screen } Flush (f); { At this point, the text written to F is written to screen. } Write (F,'Finishing '); Close (f); { Closing a file always causes a flush first } Writeln ('off.'); end.
Function Frac (X : Real) : Real;
Frac returns the non-integer part of X.
None.
{
Program Example27; { Program to demonstrate the Frac function. } Var R : Real; begin Writeln (Frac (123.456):0:3); { Prints O.456 } Writeln (Frac (-123.456):0:3); { Prints -O.456 } end.
Procedure Freemem (Var P : pointer; Count : Longint) ;
Freemem releases the memory occupied by the pointer P, of size Count, and returns it to the heap. P should point to the memory allocated to a dynamical variable.
An error will occur when P doesn't point to the heap.
{
Program Example28; { Program to demonstrate the FreeMem and GetMem functions. } Var P : Pointer; MM : Longint; begin { Get memory for P } MM:=MemAvail; Writeln ('Memory available before GetMem : ',MemAvail); GetMem (P,80); MM:=MM-Memavail; Write ('Memory available after GetMem : ',MemAvail); Writeln (' or ',MM,' bytes less than before the call.'); { fill it with spaces } FillChar (P^,80,' '); { Free the memory again } FreeMem (P,80); Writeln ('Memory available after FreeMem : ',MemAvail); end.
Procedure Getdir (drivenr : byte;var dir : string) ;
Getdir returns in dir the current directory on the drive drivenr, where drivenr is 1 for the first floppy drive, 3 for the first hard disk etc. A value of 0 returns the directory on the current disk.
On LINUX, drivenr is ignored, as there is only one directory tree.
An error is returned under DOS, if the drive requested isn't ready.
{
Program Example29; { Program to demonstrate the GetDir function. } Var S : String; begin GetDir (0,S); Writeln ('Current directory is : ',S); end.
Procedure Getmem (var p : pointer;size : Longint) ;
Getmem reserves Size bytes memory on the heap, and returns a pointer to this memory in p. If no more memory is available, nil is returned.
None.
For an example, see Freemem.
Procedure Halt [(Errnum : byte] ;
Halt stops program execution and returns control to the calling program. The optional argument Errnum specifies an exit value. If omitted, zero is returned.
None.
{
Program Example30; { Program to demonstrate the Halt function. } begin Writeln ('Before Halt.'); Halt (1); { Stop with exit code 1 } Writeln ('After Halt doesn''t get executed.'); end.
Function Hi (X : Ordinal type) : Word or byte;
Hi returns the high byte or word from X, depending on the size of X. If the size of X is 4, then the high word is returned. If the size is 2 then the high byte is retuned. hi cannot be invoked on types of size 1, such as byte or char.
None
{
Program Example31; { Program to demonstrate the Hi function. } var L : Longint; W : Word; begin L:=1 Shl 16; { = $10000 } W:=1 Shl 8; { = $100 } Writeln (Hi(L)); { Prints 1 } Writeln (Hi(W)); { Prints 1 } end.
Function High (Type identifier or variable reference) : Longint;
The return value of High depends on it's argument:
None.
{
Program example80; { Example to demonstrate the High and Low functions. } Type TEnum = ( North, East, South, West ); TRange = 14..55; TArray = Array [2..10] of Longint; Function Average (Row : Array of Longint) : Real; Var I : longint; Temp : Real; begin Temp := Row[0]; For I := 1 to High(Row) do Temp := Temp + Row[i]; Average := Temp / (High(Row)+1); end; Var A : TEnum; B : TRange; C : TArray; I : longint; begin Writeln ('TEnum goes from : ',Ord(Low(TEnum)),' to ', Ord(high(TEnum)),'.'); Writeln ('A goes from : ',Ord(Low(A)),' to ', Ord(high(A)),'.'); Writeln ('TRange goes from : ',Ord(Low(TRange)),' to ', Ord(high(TRange)),'.'); Writeln ('B goes from : ',Ord(Low(B)),' to ', Ord(high(B)),'.'); Writeln ('TArray index goes from : ',Ord(Low(TArray)),' to ', Ord(high(TArray)),'.'); Writeln ('C index goes from : ',Low(C),' to ', high(C),'.'); For I:=Low(C) to High(C) do C[i]:=I; Writeln ('Average :',Average(c)); end.
Procedure Inc (Var X : Any ordinal type[; Increment : Longint]) ;
Inc increases the value of X with Increment. If Increment isn't specified, then 1 is taken as a default.
A range check can occur, or an overflow error, if you try to increase X over its maximum value.
{
Program Example32; { Program to demonstrate the Inc function. } Const C : Cardinal = 1; L : Longint = 1; I : Integer = 1; W : Word = 1; B : Byte = 1; SI : ShortInt = 1; CH : Char = 'A'; begin Inc (C); { C:=2 } Inc (L,5); { L:=6 } Inc (I,-3); { I:=-2 } Inc (W,3); { W:=4 } Inc (B,100); { B:=101 } Inc (SI,-3); { Si:=-2 } Inc (CH,1); { ch:='B' } end.
Procedure Insert (Var Source : String;var S : String;Index : integer) ;
Insert inserts string S in string Source, at position Index, shifting all characters after Index to the right. The resulting string is truncated at 255 characters, if needed.
None.
{
Program Example33; { Program to demonstrate the Insert function. } Var S : String; begin S:='Free Pascal is difficult to use !'; Insert ('NOT ',S,pos('difficult',S)); writeln (s); end.
Function Int (X : Real) : Real;
Int returns the integer part of any Real X, as a Real.
None.
{
Program Example34; { Program to demonstrate the Int function. } begin Writeln (Int(123.456):0:1); { Prints 123.0 } Writeln (Int(-123.456):0:1); { Prints -123.0 } end.
Function IOresult : Word;
IOresult contains the result of any input/output call, when the {$i-} compiler directive is active, and IO checking is disabled. When the flag is read, it is reset to zero.
If IOresult is zero, the operation completed successfully. If non-zero, an error occurred. The following errors can occur:
DOS errors :
I/O errors :
Fatal errors :
None.
All I/O functions.
{
Program Example35; { Program to demonstrate the IOResult function. } Var F : text; begin Assign (f,paramstr(1)); {$i-} Reset (f); {$i+} If IOresult<>0 then writeln ('File ',paramstr(1),' doesn''t exist') else writeln ('File ',paramstr(1),' exists'); end.
Function Length (S : String) : Byte;
Length returns the length of the string S, which is limited to 255. If the strings S is empty, 0 is returned.
Note: The length of the string S is stored in S[0].
None.
{
Program Example36; { Program to demonstrate the Length function. } Var S : String; I : Integer; begin S:=''; for i:=1 to 10 do begin S:=S+'*'; Writeln (Length(S):2,' : ',s); end; end.
Function Ln (X : Real) : Real;
Ln returns the natural logarithm of the Real parameter X. X must be positive.
An run-time error will occur when X is negative.
{
Program Example37; { Program to demonstrate the Ln function. } begin Writeln (Ln(1)); { Prints 0 } Writeln (Ln(Exp(1))); { Prints 1 } end.
Function Lo (O : Word or Longint) : Byte or Word;
Lo returns the low byte of its argument if this is of type Integer or Word. It returns the low word of its argument if this is of type Longint or Cardinal.
None.
{
Program Example38; { Program to demonstrate the Lo function. } Var L : Longint; W : Word; begin L:=(1 Shl 16) + (1 Shl 4); { $10010 } Writeln (Lo(L)); { Prints 16 } W:=(1 Shl 8) + (1 Shl 4); { $110 } Writeln (Lo(W)); { Prints 16 } end.
Procedure LongJmp (Var env : Jmp_Buf; Value : Longint) ;
LongJmp jumps to the adress in the env jmp_buf, and resores the registers that were stored in it at the corresponding SetJmp call.
In effect, program flow will continue at the SetJmp call, which will return value instead of 0. If you pas a value equal to zero, it will be converted to 1 before passing it on. The call will not return, so it must be used with extreme care.
This can be used for error recovery, for instance when a segmentation fault occurred.
None.
For an example, see SetJmp
Function Low (Type identifier or variable reference) : Longint;
The return value of Low depends on it's argument:
None.
for an example, see High.
Function Lowercase (C : Char or String) : Char or String;
Lowercase returns the lowercase version of its argument C. If its argument is a string, then the complete string is converted to lowercase. The type of the returned value is the same as the type of the argument.
None.
{
Program Example73; { Program to demonstrate the Lowercase function. } Var I : Longint; begin For i:=ord('A') to ord('Z') do write (lowercase(chr(i))); Writeln; Writeln (Lowercase('ABCDEFGHIJKLMNOPQRSTUVWXYZ')); end.
Procedure Mark (Var P : Pointer) ;
Mark copies the current heap-pointer to P.
None.
Getmem, Freemem, New, Dispose, Maxavail
{
Program Example39; { Program to demonstrate the Mark and Release functions. } Var P,PP,PPP,MM : Pointer; begin Getmem (P,100); Mark (MM); Writeln ('Getmem 100 : Memory available : ',MemAvail,' (marked)'); GetMem (PP,1000); Writeln ('Getmem 1000 : Memory available : ',MemAvail); GetMem (PPP,100000); Writeln ('Getmem 10000 : Memory available : ',MemAvail); Release (MM); Writeln ('Released : Memory available : ',MemAvail); { At this point, PP and PPP are invalid ! } end.
Function Maxavail : Longint;
Maxavail returns the size, in bytes, of the biggest free memory block in the heap.
Remark: The heap grows dynamically if more memory is needed than is available.
None.
Release, Memavail,Freemem, Getmem
{
Program Example40; { Program to demonstrate the MaxAvail function. } Var P : Pointer; I : longint; begin { This will allocate memory until there is no more memory} I:=0; While MaxAvail>=1000 do begin Inc (I); GetMem (P,1000); end; { Default 4MB heap is allocated, so 4000 blocks should be allocated. When compiled with the -Ch10000 switch, the program will be able to allocate 10 block } Writeln ('Allocated ',i,' blocks of 1000 bytes'); end.
Function Memavail : Longint;
Memavail returns the size, in bytes, of the free heap memory.
Remark: The heap grows dynamically if more memory is needed than is available.
None.
{
Program Example41; { Program to demonstrate the MemAvail function. } Var P, PP : Pointer; begin GetMem (P,100); GetMem (PP,10000); FreeMem (P,100); { Due to the heap fragmentation introduced By the previous calls, the maximum amount of memory isn't equal to the maximum block size available. } Writeln ('Total heap available (Bytes) : ',MemAvail); Writeln ('Largest block available (Bytes) : ',MaxAvail); end.
Procedure Mkdir (const S : string) ;
Chdir creates a new directory S.
If a parent-directory of directory S doesn't exist, a run-time error is generated.
For an example, see Rmdir.
Procedure Move (var Source,Dest;Count : Longint) ;
Move moves Count bytes from Source to Dest.
If either Dest or Source is outside the accessible memory for the process, then a run-time error will be generated. With older versions of the compiler, a segmentation-fault will occur.
{
Program Example42; { Program to demonstrate the Move function. } Var S1,S2 : String [30]; begin S1:='Hello World !'; S2:='Bye, bye !'; Move (S1,S2,Sizeof(S1)); Writeln (S2); end.
Procedure New (Var P : Pointer[, Constructor]) ;
New allocates a new instance of the type pointed to by P, and puts the address in P.
If P is an object, then it is possible to specify the name of the constructor with which the instance will be created.
If not enough memory is available, Nil will be returned.
Dispose, Freemem, Getmem, Memavail, Maxavail
For an example, see Dispose.
Function Odd (X : Longint) : Boolean;
Odd returns True if X is odd, or False otherwise.
None.
{
Program Example43; { Program to demonstrate the Odd function. } begin If Odd(1) Then Writeln ('Everything OK with 1 !'); If Not Odd(2) Then Writeln ('Everything OK with 2 !'); end.
Function Ofs Var X : Longint;
Ofs returns the offset of the address of a variable.
This function is only supported for compatibility. In Free Pascal, it returns always the complete address of the variable, since Free Pascal is a 32 bit compiler.
None.
{
Program Example44; { Program to demonstrate the Ofs function. } Var W : Pointer; begin W:=Pointer(Ofs(W)); { W contains its own offset. } end.
Function Ord (X : Any ordinal type) : Longint;
Ord returns the Ordinal value of a ordinal-type variable X.
None.
{
Program Example45; { Program to demonstrate the Ord,Pred,Succ functions. } Type TEnum = (Zero, One, Two, Three, Four); Var X : Longint; Y : TEnum; begin X:=125; Writeln (Ord(X)); { Prints 125 } X:=Pred(X); Writeln (Ord(X)); { prints 124 } Y:= One; Writeln (Ord(y)); { Prints 1 } Y:=Succ(Y); Writeln (Ord(Y)); { Prints 2} end.
Function Paramcount : Longint;
Paramcount returns the number of command-line arguments. If no arguments were given to the running program, 0 is returned.
None.
{
Program Example46; { Program to demonstrate the ParamCount and ParamStr functions. } Var I : Longint; begin Writeln (paramstr(0),' : Got ',ParamCount,' command-line parameters: '); For i:=1 to ParamCount do Writeln (ParamStr (i)); end.
Function Paramstr (L : Longint) : String;
Paramstr returns the L-th command-line argument. L must be between 0 and Paramcount, these values included. The zeroth argument is the name with which the program was started.
In all cases, the command-line will be truncated to a length of 255, even though the operating system may support bigger command-lines. If you want to access the complete command-line, you must use the argv pointer to access the Real values of the command-line parameters.
For an example, see Paramcount.
Function Pi : Real;
Pi returns the value of Pi (3.1415926535897932385).
None.
{
Program Example47; { Program to demonstrate the Pi function. } begin Writeln (Pi); {3.1415926} Writeln (Sin(Pi)); end.
Function Pos (Const Substr : String;Const S : String) : Byte;
Pos returns the index of Substr in S, if S contains Substr. In case Substr isn't found, 0 is returned.
The search is case-sensitive.
None
{
Program Example48; { Program to demonstrate the Pos function. } Var S : String; begin S:='The first space in this sentence is at position : '; Writeln (S,pos(' ',S)); S:='The last letter of the alphabet doesn''t appear in this sentence '; If (Pos ('Z',S)=0) and (Pos('z',S)=0) then Writeln (S); end.
Function Power (base,expon : Real) : Real;
Power returns the value of base to the power expon. Base and expon can be of type Longint, in which case the result will also be a Longint.
The function actually returns Exp(expon*Ln(base))
None.
{
Program Example78; { Program to demonstrate the Power function. } begin Writeln (Power(exp(1.0),1.0):8:2); { Should print 2.72 } end.
Function Pred (X : Any ordinal type) : Same type;
Pred returns the element that precedes the element that was passed to it. If it is applied to the first value of the ordinal type, and the program was compiled with range checking on ({$R+}, then a run-time error will be generated.
Run-time error 201 is generated when the result is out of range.
for an example, see Ord
{
Program example80; { Example to demonstrate the High and Low functions. } Type TEnum = ( North, East, South, West ); TRange = 14..55; TArray = Array [2..10] of Longint; Function Average (Row : Array of Longint) : Real; Var I : longint; Temp : Real; begin Temp := Row[0]; For I := 1 to High(Row) do Temp := Temp + Row[i]; Average := Temp / (High(Row)+1); end; Var A : TEnum; B : TRange; C : TArray; I : longint; begin Writeln ('TEnum goes from : ',Ord(Low(TEnum)),' to ', Ord(high(TEnum)),'.'); Writeln ('A goes from : ',Ord(Low(A)),' to ', Ord(high(A)),'.'); Writeln ('TRange goes from : ',Ord(Low(TRange)),' to ', Ord(high(TRange)),'.'); Writeln ('B goes from : ',Ord(Low(B)),' to ', Ord(high(B)),'.'); Writeln ('TArray index goes from : ',Ord(Low(TArray)),' to ', Ord(high(TArray)),'.'); Writeln ('C index goes from : ',Low(C),' to ', high(C),'.'); For I:=Low(C) to High(C) do C[i]:=I; Writeln ('Average :',Average(c)); end.
Function Ptr (Sel,Off : Longint) : Pointer;
Ptr returns a pointer, pointing to the address specified by segment Sel and offset Off.
Remark 1: In the 32-bit flat-memory model supported by Free Pascal, this function is obsolete.
Remark 2: The returned address is simply the offset. If you recompile the RTL with -dDoMapping defined, then the compiler returns the following : ptr := pointer($e0000000+sel shl 4+off) under DOS, or ptr := pointer(sel shl 4+off) on other OSes.
None.
{
Program Example59; { Program to demonstrate the Ptr function. } Var P : ^String; S : String; begin S:='Hello, World !'; P:=Ptr(Seg(S),Longint(Ofs(S))); {P now points to S !} Writeln (P^); end.
Function Random [(L : Longint)] : Longint or Real;
Random returns a random number larger or equal to 0 and strictly less than L.
If the argument L is omitted, a Real number between 0 and 1 is returned. (0 included, 1 excluded)
None.
{
Program Example49; { Program to demonstrate the Random and Randomize functions. } Var I,Count,guess : Longint; R : Real; begin Randomize; { This way we generate a new sequence every time the program is run} Count:=0; For i:=1 to 1000 do If Random>0.5 then inc(Count); Writeln ('Generated ',Count,' numbers > 0.5'); Writeln ('out of 1000 generated numbers.'); count:=0; For i:=1 to 5 do begin write ('Guess a number between 1 and 5 : '); readln(Guess); If Guess=Random(5)+1 then inc(count); end; Writeln ('You guessed ',Count,' out of 5 correct.'); end.
Procedure Randomize ;
Randomize initializes the random number generator of Free Pascal, by giving a value to Randseed, calculated with the system clock.
None.
For an example, see Random.
Procedure Read ([Var F : Any file type], V1 [, V2, ... , Vn]) ;
Read reads one or more values from a file F, and stores the result in V1, V2, etc.; If no file F is specified, then standard input is read.
If F is of type Text, then the variables V1, V2 etc. must be of type Char, Integer, Real or String.
If F is a typed file, then each of the variables must be of the type specified in the declaration of F. Untyped files are not allowed as an argument.
If no data is available, a run-time error is generated. This behavior can be controlled with the {$i} compiler switch.
Readln, Blockread, Write, Blockwrite
{
Program Example50; { Program to demonstrate the Read(Ln) function. } Var S : String; C : Char; F : File of char; begin Assign (F,'ex50.pp'); Reset (F); C:='A'; Writeln ('The characters before the first space in ex50.pp are : '); While not Eof(f) and (C<>' ') do Begin Read (F,C); Write (C); end; Writeln; Close (F); Writeln ('Type some words. An empty line ends the program.'); repeat Readln (S); until S=''; end.
Procedure Readln [Var F : Text], V1 [, V2, ... , Vn]) ;
Read reads one or more values from a file F, and stores the result in V1, V2, etc. After that it goes to the next line in the file (defined by the LineFeed (#10) character). If no file F is specified, then standard input is read.
The variables V1, V2 etc. must be of type Char, Integer, Real, String or PChar.
If no data is available, a run-time error is generated. This behavior can be controlled with the {$i} compiler switch.
Read, Blockread, Write, Blockwrite
For an example, see Read.
Procedure Release (Var P : pointer) ;
Release sets the top of the Heap to the location pointed to by P. All memory at a location higher than P is marked empty.
A run-time error will be generated if P points to memory outside the heap.
Mark, Memavail, Maxavail, Getmem, Freemem New, Dispose
For an example, see Mark.
Procedure Rename (Var F : Any Filetype; Const S : String) ;
Rename changes the name of the assigned file F to S. F must be assigned, but not opened.
A run-time error will be generated if F isn't assigned, or doesn't exist.
{
Program Example77; { Program to demonstrate the Rename function. } Var F : Text; begin Assign (F,paramstr(1)); Rename (F,paramstr(2)); end.
Procedure Reset (Var F : Any File Type[; L : Longint]) ;
Reset opens a file F for reading. F can be any file type. If F is an untyped or typed file, then it is opened for reading and writing. If F is an untyped file, the record size can be specified in the optional parameter L. Default a value of 128 is used.
If the file cannot be opened for reading, then a run-time error is generated. This behavior can be changed by the {$i} compiler switch.
{
Program Example51; { Program to demonstrate the Reset function. } Function FileExists (Name : String) : boolean; Var F : File; begin {$i-} Assign (F,Name); Reset (F); {$I+} FileExists:=(IoResult=0) and (Name<>''); Close (f); end; begin If FileExists (Paramstr(1)) then Writeln ('File found') else Writeln ('File NOT found'); end.
Procedure Rewrite (Var F : Any File Type[; L : Longint]) ;
Rewrite opens a file F for writing. F can be any file type. If F is an untyped or typed file, then it is opened for reading and writing. If F is an untyped file, the record size can be specified in the optional parameter L. Default a value of 128 is used.
if Rewrite finds a file with the same name as F, this file is truncated to length 0. If it doesn't find such a file, a new file is created.
If the file cannot be opened for writing, then a run-time error is generated. This behavior can be changed by the {$i} compiler switch.
{
Program Example52; { Program to demonstrate the Rewrite function. } Var F : File; I : longint; begin Assign (F,'Test.dat'); { Create the file. Recordsize is 4 } Rewrite (F,Sizeof(I)); For I:=1 to 10 do BlockWrite (F,I,1); close (f); { F contains now a binary representation of 10 longints going from 1 to 10 } end.
Procedure Rmdir (const S : string) ;
Rmdir removes the directory S.
If S doesn't exist, or isn't empty, a run-time error is generated.
{
Program Example53; { Program to demonstrate the MkDir and RmDir functions. } Const D : String[8] = 'TEST.DIR'; Var S : String; begin Writeln ('Making directory ',D); Mkdir (D); Writeln ('Changing directory to ',D); ChDir (D); GetDir (0,S); Writeln ('Current Directory is : ',S); WRiteln ('Going back'); ChDir ('..'); Writeln ('Removing directory ',D); RmDir (D); end.
Function Round (X : Real) : Longint;
Round rounds X to the closest integer, which may be bigger or smaller than X.
None.
{
Program Example54; { Program to demonstrate the Round function. } begin Writeln (Round(123.456)); { Prints 124 } Writeln (Round(-123.456)); { Prints -124 } Writeln (Round(12.3456)); { Prints 12 } Writeln (Round(-12.3456)); { Prints -12 } end.
Procedure Runerror (ErrorCode : Word) ;
Runerror stops the execution of the program, and generates a run-time error ErrorCode.
None.
{
Program Example55; { Program to demonstrate the RunError function. } begin { The program will stop end emit a run-error 106 } RunError (106); end.
Procedure Seek (Var F; Count : Longint) ;
Seek sets the file-pointer for file F to record Nr. Count. The first record in a file has Count=0. F can be any file type, except Text. If F is an untyped file, with no specified record size, 128 is assumed.
A run-time error is generated if Count points to a position outside the file, or the file isn't opened.
{
Program Example56; { Program to demonstrate the Seek function. } Var F : File; I,j : longint; begin { Create a file and fill it with data } Assign (F,'test.dat'); Rewrite(F); { Create file } Close(f); FileMode:=2; ReSet (F,Sizeof(i)); { Opened read/write } For I:=0 to 10 do BlockWrite (F,I,1); { Go Back to the begining of the file } Seek(F,0); For I:=0 to 10 do begin BlockRead (F,J,1); If J<>I then Writeln ('Error: expected ' ,i,', got ',j); end; Close (f); end.
Function SeekEof [(Var F : text)] : Boolean;
SeekEof returns True is the file-pointer is at the end of the file. It ignores all whitespace.
Calling this function has the effect that the file-position is advanced until the first non-whitespace character or the end-of-file marker is reached. If the end-of-file marker is reached, True is returned. Otherwise, False is returned.
If the parameter F is omitted, standard Input is assumed.
A run-time error is generated if the file F isn't opened.
{
Program Example57; { Program to demonstrate the SeekEof function. } Var C : Char; begin { this will print all characters from standard input except Whitespace characters. } While Not SeekEof do begin Read (C); Write (C); end; end.
Function SeekEoln [(Var F : text)] : Boolean;
SeekEoln returns True is the file-pointer is at the end of the current line. It ignores all whitespace.
Calling this function has the effect that the file-position is advanced until the first non-whitespace character or the end-of-line marker is reached. If the end-of-line marker is reached, True is returned. Otherwise, False is returned.
The end-of-line marker is defined as #10, the LineFeed character.
If the parameter F is omitted, standard Input is assumed.
A run-time error is generated if the file F isn't opened.
{
Program Example58; { Program to demonstrate the SeekEoln function. } Var C : Char; begin { This will read the first line of standard output and print all characters except whitespace. } While not SeekEoln do Begin Read (c); Write (c); end; end.
Function Seg Var X : Longint;
Seg returns the segment of the address of a variable.
This function is only supported for compatibility. In Free Pascal, it returns always 0, since Free Pascal is a 32 bit compiler, segments have no meaning.
None.
{
Program Example60; { Program to demonstrate the Seg function. } Var W : Word; begin W:=Seg(W); { W contains its own Segment} end.
Function SetJmp (Var Env : Jmp_Buf) : Longint;
SetJmp fills env with the necessary data for a jump back to the point where it was called. It returns zero if called in this way.
If the function returns nonzero, then it means that a call to LongJmp with env as an argument was made somewhere in the program.
None.
{
program example79; { Program to demonstrate the setjmp, longjmp functions } procedure dojmp(var env : jmp_buf; value : longint); begin value:=2; Writeln ('Going to jump !'); { This will return to the setjmp call, and return value instead of 0 } longjmp(env,value); end; var env : jmp_buf; begin if setjmp(env)=0 then begin writeln ('Passed first time.'); dojmp(env,2); end else writeln ('Passed second time.'); end.
Procedure SetTextBuf (Var f : Text; Var Buf[; Size : Word]) ;
SetTextBuf assigns an I/O buffer to a text file. The new buffer is located at Buf and is Size bytes long. If Size is omitted, then SizeOf(Buf) is assumed.
The standard buffer of any text file is 128 bytes long. For heavy I/0 operations this may prove too slow. The SetTextBuf procedure allows you to set a bigger buffer for your application, thus reducing the number of system calls, and thus reducing the load on the system resources.
The maximum size of the newly assigned buffer is 65355 bytes.
Remark 1: Never assign a new buffer to an opened file. You can assign a new buffer immediately after a call to Rewrite, Reset or Append, but not after you read from/wrote to the file. This may cause loss of data. If you still want to assign a new buffer after read/write operations have been performed, flush the file first. This will ensure that the current buffer is emptied.
Remark 2: Take care that the buffer you assign is always valid. If you assign a local variable as a buffer, then after your program exits the local program block, the buffer will no longer be valid, and stack problems may occur.
No checking on Size is done.
Assign, Reset, Rewrite, Append
{
Program Example61; { Program to demonstrate the SetTextBuf function. } Var Fin,Fout : Text; Ch : Char; Bufin,Bufout : Array[1..10000] of byte; begin Assign (Fin,paramstr(1)); Reset (Fin); Assign (Fout,paramstr(2)); Rewrite (Fout); { This is harmless before IO has begun } { Try this program again on a big file, after commenting out the following 2 lines and recompiling it. } SetTextBuf (Fin,Bufin); SetTextBuf (Fout,Bufout); While not eof(Fin) do begin Read (Fin,ch); write (Fout,ch); end; Close (Fin); Close (Fout); end.
Function Sin (X : Real) : Real;
Sin returns the sine of its argument X, where X is an angle in radians.
None.
{
Program Example62; { Program to demonstrate the Sin function. } begin Writeln (Sin(Pi):0:1); { Prints 0.0 } Writeln (Sin(Pi/2):0:1); { Prints 1.0 } end.
Function SizeOf (X : Any Type) : Longint;
SizeOf Returns the size, in bytes, of any variable or type-identifier.
Remark: this isn't Really a RTL function. Its result is calculated at compile-time, and hard-coded in your executable.
None.
{
Program Example63; { Program to demonstrate the SizeOf function. } Var I : Longint; S : String [10]; begin Writeln (SizeOf(I)); { Prints 4 } Writeln (SizeOf(S)); { Prints 11 } end.
Function Sptr : Pointer;
Sptr returns the current stack pointer.
None.
{
Program Example64; { Program to demonstrate the SPtr function. } Var P :Longint; begin P:=Sptr; { P Contains now the current stack position. } end.
Function Sqr (X : Real) : Real;
Sqr returns the square of its argument X.
None.
{
Program Example65; { Program to demonstrate the Sqr function. } Var i : Integer; begin For i:=1 to 10 do writeln (Sqr(i):3); end.
Function Sqrt (X : Real) : Real;
Sqrt returns the square root of its argument X, which must be positive.
If X is negative, then a run-time error is generated.
{
Program Example66; { Program to demonstrate the Sqrt function. } begin Writeln (Sqrt(4):0:3); { Prints 2.000 } Writeln (Sqrt(2):0:3); { Prints 1.414 } end.
Function SSeg : Longint;
SSeg returns the Stack Segment. This function is only supported for compatibolity reasons, as Sptr returns the correct contents of the stackpointer.
None.
{
Program Example67; { Program to demonstrate the SSeg function. } Var W : Longint; begin W:=SSeg; end.
Procedure Str (Var X[:NumPlaces[:Decimals]]; Var S : String) ;
Str returns a string which represents the value of X. X can be any numerical type.
The optional NumPLaces and Decimals specifiers control the formatting of the string.
None.
{
Program Example68; { Program to demonstrate the Str function. } Var S : String; Function IntToStr (I : Longint) : String; Var S : String; begin Str (I,S); IntToStr:=S; end; begin S:='*'+IntToStr(-233)+'*'; Writeln (S); end.
Function Succ (X : Any ordinal type) : Same type;
Succ returns the element that succeeds the element that was passed to it. If it is applied to the last value of the ordinal type, and the program was compiled with range checking on ({$R+}, then a run-time error will be generated.
Run-time error 201 is generated when the result is out of range.
for an example, see Ord.
Function Swap (X) : Type of X;
Swap swaps the high and low order bytes of X if X is of type Word or Integer, or swaps the high and low order words of X if X is of type Longint or Cardinal.
The return type is the type of X
None.
{
Program Example69; { Program to demonstrate the Swap function. } Var W : Word; L : Longint; begin W:=$1234; W:=Swap(W); if W<>$3412 then writeln ('Error when swapping word !'); L:=$12345678; L:=Swap(L); if L<>$56781234 then writeln ('Error when swapping Longint !'); end.
Function Trunc (X : Real) : Longint;
Trunc returns the integer part of X, which is always smaller than (or equal to) X.
None.
{
Program Example54; { Program to demonstrate the Trunc function. } begin Writeln (Trunc(123.456)); { Prints 123 } Writeln (Trunc(-123.456)); { Prints -123 } Writeln (Trunc(12.3456)); { Prints 12 } Writeln (Trunc(-12.3456)); { Prints -12 } end.
Procedure Truncate (Var F : file) ;
Truncate truncates the (opened) file F at the current file position.
Errors are reported by IOresult.
{
Program Example71; { Program to demonstrate the Truncate function. } Var F : File of longint; I,L : Longint; begin Assign (F,'test.dat'); Rewrite (F); For I:=1 to 10 Do Write (F,I); Writeln ('Filesize before Truncate : ',FileSize(F)); Close (f); Reset (F); Repeat Read (F,I); Until i=5; Truncate (F); Writeln ('Filesize after Truncate : ',Filesize(F)); Close (f); end.
Function Upcase (C : Char or string) : Char or String;
Upcase returns the uppercase version of its argument C. If its argument is a string, then the complete string is converted to uppercase. The type of the returned value is the same as the type of the argument.
None.
{
Program Example72; { Program to demonstrate the Upcase function. } Var I : Longint; begin For i:=ord('a') to ord('z') do write (upcase(chr(i))); Writeln; { This doesn't work in TP, but it does in Free Pascal } Writeln (Upcase('abcdefghijklmnopqrstuvwxyz')); end.
Procedure Val (const S : string;var V;var Code : word) ;
Val converts the value represented in the string S to a numerical value, and stores this value in the variable V, which can be of type Longint, Real and Byte.
If the conversion isn't succesfull, then the parameter Code contains the index of the character in S which prevented the conversion.
The string S isn't allow to contain spaces.
If the conversion doesn't succeed, the value of Code indicates the position where the conversion went wrong.
{
Program Example74; { Program to demonstrate the Val function. } Var I, Code : Integer; begin Val (ParamStr (1),I,Code); If Code<>0 then Writeln ('Error at position ',code,' : ',Paramstr(1)[Code]) else Writeln ('Value : ',I); end.
Procedure Write ([Var F : Any filetype;] V1 [; V2; ... , Vn)] ;
Write writes the contents of the variables V1, V2 etc. to the file F. F can be a typed file, or a Text file.
If F is a typed file, then the variables V1, V2 etc. must be of the same type as the type in the declaration of F. Untyped files are not allowed.
If the parameter F is omitted, standard output is assumed.
If F is of type Text, then the necessary conversions are done such that the output of the variables is in human-readable format. This conversion is done for all numerical types. Strings are printed exactly as they are in memory, as well as PChar types. The format of the numerical conversions can be influenced through the following modifiers:
OutputVariable : NumChars [: Decimals ]
This will print the value of OutputVariable with a minimum of NumChars characters, from which Decimals are reserved for the decimals. If the number cannot be represented with NumChars characters, NumChars will be increased, until the representation fits. If the representation requires less than NumChars characters then the output is filled up with spaces, to the left of the generated string, thus resulting in a right-aligned representation.
If no formatting is specified, then the number is written using its natural length, with a space in front of it if it's positive, and a minus sign if it's negative.
Real numbers are, by default, written in scientific notation.
If an error occurs, a run-time error is generated. This behavior can be controlled with the {$i} switch.
WriteLn, Read, Readln, Blockwrite
Procedure WriteLn [([Var F : Text;] [V1 [; V2; ... , Vn)]] ;
WriteLn does the same as Write for text files, and emits a Carriage Return - LineFeed character pair after that.
If the parameter F is omitted, standard output is assumed.
If no variables are specified, a Carriage Return - LineFeed character pair is emitted, resulting in a new line in the file F.
Remark: Under LINUX, the Carriage Return character is omitted, as customary in Unix environments.
If an error occurs, a run-time error is generated. This behavior can be controlled with the {$i} switch.
Write, Read, Readln, Blockwrite
{
Program Example75; { Program to demonstrate the Write(ln) function. } Var F : File of Longint; L : Longint; begin Write ('This is on the first line ! '); { No CR/LF pair! } Writeln ('And this too...'); Writeln ('But this is already on the second line...'); Assign (f,'test.dat'); Rewrite (f); For L:=1 to 10 do write (F,L); { No writeln allowed here ! } Close (f); end.