Subsections


13. The system unit

refex The system unit contains the standard supported functions of Free Pascal. It is the same for all platforms. Basically it is the same as the system unit provided with Borland or Turbo Pascal.

Functions are listed in alphabetical order. Arguments of functions or procedures that are optional are put between square brackets.

The pre-defined constants and variables are listed in the first section. The second section contains an overview of all functions, grouped by functionality, and the last section contains the supported functions and procedures.

13.1 Types, Constants and Variables

13.1.1 Types

The following integer types are defined in the System unit:
Shortint = -128..127;
SmallInt = -32768..32767;
Longint  = $80000000..$7fffffff;
byte     = 0..255;
word     = 0..65535;
dword    = cardinal;
longword = cardinal;
Integer  = smallint;
The following types are used for the functions that need compiler magic such as Val or Str:
StrLenInt = LongInt;
ValSInt = Longint;
ValUInt = Cardinal;
ValReal = Extended;
The following character types are defined for Delphi compatibility:
TAnsiChar   = Char;
AnsiChar    = TAnsiChar;
And the following pointer types:
  PChar = ^char;
  pPChar = ^PChar;
  PAnsiChar   = PChar;
  PQWord      = ^QWord;
  PInt64      = ^Int64;
  pshortstring = ^shortstring;
  plongstring  = ^longstring;
  pansistring  = ^ansistring;
  pwidestring  = ^widestring;
  pextended    = ^extended;
  ppointer     = ^pointer;
For the SetJmp and LongJmp calls, the following jump bufer type is defined (for the I386 processor):
  jmp_buf = record
    ebx,esi,edi : Longint;
    bp,sp,pc : Pointer;
    end;
  PJmp_buf = ^jmp_buf;
The following records and pointers can be used if you want to scan the entries in the string message handler tables:
  tmsgstrtable = record
     name : pshortstring;
     method : pointer;
  end;
  pmsgstrtable = ^tmsgstrtable;

  tstringmessagetable = record
     count : dword;
     msgstrtable : array[0..0] of tmsgstrtable;
  end;
  pstringmessagetable = ^tstringmessagetable;

The base class for all classes is defined as:

Type
  TObject = Class
  Public
    constructor create;
    destructor destroy;virtual;
    class function newinstance : tobject;virtual;
    procedure freeinstance;virtual;
    function safecallexception(exceptobject : tobject;
      exceptaddr : pointer) : longint;virtual;
    procedure defaulthandler(var message);virtual;
    procedure free;
    class function initinstance(instance : pointer) : tobject;
    procedure cleanupinstance;
    function classtype : tclass;
    class function classinfo : pointer;
    class function classname : shortstring;
    class function classnameis(const name : string) : boolean;
    class function classparent : tclass;
    class function instancesize : longint;
    class function inheritsfrom(aclass : tclass) : boolean;
    class function inheritsfrom(aclass : tclass) : boolean;
    class function stringmessagetable : pstringmessagetable;
    procedure dispatch(var message);
    procedure dispatchstr(var message);
    class function methodaddress(const name : shortstring) : pointer;
    class function methodname(address : pointer) : shortstring;
    function fieldaddress(const name : shortstring) : pointer;
    procedure AfterConstruction;virtual;
    procedure BeforeDestruction;virtual;
    procedure DefaultHandlerStr(var message);virtual;
  end;
  TClass = Class Of TObject;
  PClass = ^TClass;
Unhandled exceptions can be treated using a constant of the TExceptProc type:
TExceptProc = Procedure (Obj : TObject; Addr,Frame: Pointer);
Obj is the exception object that was used to raise the exception, Addr and Frame contain the exact address and stack frame where the exception was raised.

The TVarRec type is used to access the elements passed in a Array of Const argument to a function or procedure:

Type
  PVarRec = ^TVarRec;
  TVarRec = record
    case VType : Longint of
    vtInteger    : (VInteger: Longint);
    vtBoolean    : (VBoolean: Boolean);
    vtChar       : (VChar: Char);
    vtExtended   : (VExtended: PExtended);
    vtString     : (VString: PShortString);
    vtPointer    : (VPointer: Pointer);
    vtPChar      : (VPChar: PChar);
    vtObject     : (VObject: TObject);
    vtClass      : (VClass: TClass);
    vtAnsiString : (VAnsiString: Pointer);
    vtWideString : (VWideString: Pointer);
    vtInt64      : (VInt64: PInt64);
  end;
The heap manager uses the TMemoryManager type:
  PMemoryManager = ^TMemoryManager;
  TMemoryManager = record
    Getmem      : Function(Size:Longint):Pointer;
    Freemem     : Function(var p:pointer):Longint;
    FreememSize : Function(var p:pointer;Size:Longint):Longint;
    AllocMem    : Function(Size:longint):Pointer;
    ReAllocMem  : Function(var p:pointer;Size:longint):Pointer;
    MemSize     : function(p:pointer):Longint;
    MemAvail    : Function:Longint;
    MaxAvail    : Function:Longint;
    HeapSize    : Function:Longint;
  end;
More information on using this record can be found in Programmers' guide.

13.1.2 Constants

The following constants define the maximum values that can be used with various types:
  MaxSIntValue = High(ValSInt);
  MaxUIntValue = High(ValUInt);
  maxint   = maxsmallint;
  maxLongint  = $7fffffff;
  maxSmallint = 32767;
The following constants for file-handling are defined in the system unit:
Const
  fmclosed = $D7B0;
  fminput  = $D7B1;
  fmoutput = $D7B2;
  fminout  = $D7B3;
  fmappend = $D7B4;
  filemode : byte = 2;
Further, the following non processor specific general-purpose constants are also defined:
const
  erroraddr : pointer = nil;
  errorcode : word = 0;
 { max level in dumping on error }
  max_frame_dump : word = 20;

Remark: Processor specific global constants are named Testxxxx where xxxx represents the processor number (such as Test8086, Test68000), and are used to determine on what generation of processor the program is running on.

The following constants are defined to access VMT entries:

   vmtInstanceSize         = 0;
   vmtParent               = 8;
   vmtClassName            = 12;
   vmtDynamicTable         = 16;
   vmtMethodTable          = 20;
   vmtFieldTable           = 24;
   vmtTypeInfo             = 28;
   vmtInitTable            = 32;
   vmtAutoTable            = 36;
   vmtIntfTable            = 40;
   vmtMsgStrPtr            = 44;
   vmtMethodStart          = 48;
   vmtDestroy              = vmtMethodStart;
   vmtNewInstance          = vmtMethodStart+4;
   vmtFreeInstance         = vmtMethodStart+8;
   vmtSafeCallException    = vmtMethodStart+12;
   vmtDefaultHandler       = vmtMethodStart+16;
   vmtAfterConstruction    = vmtMethodStart+20;
   vmtBeforeDestruction    = vmtMethodStart+24;
   vmtDefaultHandlerStr    = vmtMethodStart+28;
You should always use the constant names, and never their values, because the VMT table can change, breaking your code.

The following constants will be used for the planned variant support:

  varEmpty     = $0000;
  varNull      = $0001;
  varSmallint  = $0002;
  varInteger   = $0003;
  varSingle    = $0004;
  varDouble    = $0005;
  varCurrency  = $0006;
  varDate      = $0007;
  varOleStr    = $0008;
  varDispatch  = $0009;
  varError     = $000A;
  varBoolean   = $000B;
  varVariant   = $000C;
  varUnknown   = $000D;
  varByte      = $0011;
  varString    = $0100;
  varAny       = $0101;
  varTypeMask  = $0FFF;
  varArray     = $2000;
  varByRef     = $4000;
The following constants are used in the TVarRec record:
vtInteger    = 0;
vtBoolean    = 1;
vtChar       = 2;
vtExtended   = 3;
vtString     = 4;
vtPointer    = 5;
vtPChar      = 6;
vtObject     = 7;
vtClass      = 8;
vtWideChar   = 9;
vtPWideChar  = 10;
vtAnsiString = 11;
vtCurrency   = 12;
vtVariant    = 13;
vtInterface  = 14;
vtWideString = 15;
vtInt64      = 16;
vtQWord      = 17;
The ExceptProc is called when an unhandled exception occurs:
Const
  ExceptProc : TExceptProc = Nil;
It is set in the objpas unit, but you can set it yourself to change the default exception handling.

13.1.3 Variables

The following variables are defined and initialized in the system unit:
var
  output,input,stderr : text;
  exitproc : pointer;
  exitcode : word;
  stackbottom : Longint;
  loweststack : Longint;
The variables ExitProc, exitcode are used in the Free Pascal exit scheme. It works similarly to the one in Turbo Pascal:

When a program halts (be it through the call of the Halt function or Exit or through a run-time error), the exit mechanism checks the value of ExitProc. If this one is non-Nil, it is set to Nil, and the procedure is called. If the exit procedure exits, the value of ExitProc is checked again. If it is non-Nil then the above steps are repeated. So if you want to install your exit procedure, you should save the old value of ExitProc (may be non-Nil, since other units could have set it before you did). In your exit procedure you then restore the value of ExitProc, such that if it was non-Nil the exit-procedure can be called.

Example
Program Example98;

{ Program to demonstrate the exitproc function. }

Var
  OldExitProc : Pointer;

Procedure MyExit;

begin
  Writeln('My Exitproc was called. Exitcode = ',ExitCode);
  { restore old exit procedure }
  ExitProc:=OldExitProc;
end;

begin
  OldExitProc:=ExitProc;  
  ExitProc:=@MyExit;
  If ParamCount>0 Then
    Halt(66);
end.

The ErrorAddr and ExitCode can be used to check for error-conditions. If ErrorAddr is non-Nil, a run-time error has occurred. If so, ExitCode contains the error code. If ErrorAddr is Nil, then ExitCode contains the argument to Halt or 0 if the program terminated normally.

ExitCode is always passed to the operating system as the exit-code of your process.

Remark: The maximum error code under LINUX is 127.

Under GO32, the following constants are also defined :

const
   seg0040 = $0040;
   segA000 = $A000;
   segB000 = $B000;
   segB800 = $B800;
These constants allow easy access to the bios/screen segment via mem/absolute.

The randomize function uses a seed stored in the RandSeed variable:

  RandSeed    : Cardinal;
This variable is initialized in the initialization code of the system unit.

13.2 Function list by category

What follows is a listing of the available functions, grouped by category. For each function there is a reference to the page where you can find the function.

13.2.1 File handling

Functions concerning input and output from and to file. Append Open a file in append mode]
Assign Assign a name to a file
Blockread Read data from a file into memory
Blockwrite Write data from memory to a file
Close Close a file
Eof Check for end of file
Eoln Check for end of line
Erase Delete file from disk
Filepos Position in file
Filesize Size of file
Flush Write file buffers to disk
IOresult Return result of last file IO operation
Read Read from file into variable
Readln Read from file into variable and goto next line
Rename Rename file on disk
Reset Open file for reading
Rewrite Open file for writing
Seek Set file position
SeekEof Set file position to end of file
SeekEoln Set file position to end of line
SetTextBuf Set size of file buffer
Truncate Truncate the file at position
Write Write variable to file
WriteLn Write variable to file and append newline

13.2.2 Memory management

Functions concerning memory issues. Addr Return address of variable]
Assigned Check if a pointer is valid
CompareByte Compare 2 memory buffers byte per byte
CompareChar Compare 2 memory buffers byte per byte
CompareDWord Compare 2 memory buffers byte per byte
CompareWord Compare 2 memory buffers byte per byte
CSeg Return code segment
Dispose Free dynamically allocated memory
DSeg Return data segment
FillByte Fill memory region with 8-bit pattern
Fillchar Fill memory region with certain character
FillDWord Fill memory region with 32-bit pattern
Fillword Fill memory region with 16-bit pattern
Freemem Release allocated memory
Getmem Allocate new memory
GetMemoryManager Return current memory manager
High Return highest index of open array or enumerated
IsMemoryManagerSet Is the memory manager set
Low Return lowest index of open array or enumerated
Mark Mark current memory position
Maxavail Return size of largest free memory block
Memavail Return total available memory
Move Move data from one location in memory to another
MoveCharNull Move data till first zero character
New Dynamically allocate memory for variable
Ofs Return offset of variable
Ptr Combine segmant and offset to pointer
Release Release memory above mark point
Seg Return segment
SetMemoryManager Set a memory manager
Sptr Return current stack pointer
SSeg Return ESS register value

13.2.3 Mathematical routines

Functions connected to calculating and coverting numbers. Abs Calculate absolute value]
Arctan Calculate inverse tangent
Cos Calculate cosine of angle
Dec Decrease value of variable
Exp Exponentiate
Frac Return fractional part of floating point value
Hi Return high byte/word of value
Inc Increase value of variable
Int Calculate integer part of floating point value
Ln Calculate logarithm
Lo Return low byte/word of value
Odd Is a value odd or even ?
Pi Return the value of pi
Power Raise float to integer power
Random Generate random number
Randomize Initialize random number generator
Round Round floating point value to nearest integer number
Sin Calculate sine of angle
Sqr Calculate the square of a value
Sqrt Calculate the square root of a value
Swap Swap high and low bytes/words of a variable
Trunc Truncate a floating point value

13.2.4 String handling

All things connected to string handling. BinStr Construct binary representation of integer]
Chr Convert ASCII code to character
Concat Concatenate two strings
Copy Copy part of a string
Delete Delete part of a string
HexStr Construct hexadecimal representation of integer
Insert Insert one string in another
Length Return length of string
Lowercase Convert string to all-lowercase
Pos Calculate position of one string in another
SetLength Set length of a string
Str Convert number to string representation
StringOfChar Create string consisting of a number of characters
Upcase Convert string to all-uppercase
Val Convert string to number

13.2.5 Operating System functions

Functions that are connected to the operating system. Chdir Change working directory]
Getdir Return current working directory
Halt Halt program execution
Paramcount Number of parameters with which program was called
Paramstr Retrieve parameters with which program was called
Mkdir Make a directory
Rmdir Remove a directory
Runerror Abort program execution with error condition

13.2.6 Miscellaneous functions

Functions that do not belong in one of the other categories. Break Abort current loop]
Continue Next cycle in current loop
Exit Exit current function or procedure
LongJmp Jump to execution point
Ord Return ordinal value of enumerated type
Pred Return previous value of ordinal type
SetJmp Mark execution point for jump
SizeOf Return size of variable or type
Succ Return next value of ordinal type

13.3 Functions and Procedures


13.3.1 Abs

Declaration
Function Abs (X : Every numerical type) : Every numerical type;
Description
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.
Errors
None.
See also
Round

Example
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.


13.3.2 Addr

Declaration
Function Addr (X : Any type) : Pointer;

Description
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 (Programmers' guide).
Errors
None
See also
SizeOf

Example
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.


13.3.3 Append

Declaration
Procedure Append (Var F : Text);

Description
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.

Errors
If the file can't be created, a run-time error will be generated.
See also
Rewrite,Close, Reset

Example
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.


13.3.4 Arctan

Declaration
Function Arctan (X : Real) : Real;

Description
Arctan returns the Arctangent of X, which can be any Real type. The resulting angle is in radial units.
Errors
None
See also
Sin, Cos

Example
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.


13.3.5 Assign

Declaration
Procedure Assign (Var F; Name : String);

Description
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.
Errors
None.
See also
Reset, Rewrite, Append

Example
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.


13.3.6 Assigned

Declaration
Function Assigned (P : Pointer) : Boolean;
Description
Assigned returns True if P is non-nil and retuns False of P is nil. The main use of Assigned is that Procedural variables, method variables and class-type variables also can be passed to Assigned.
Errors
None
See also
New

Example
Program Example96;

{ Program to demonstrate the Assigned function. }

Var P : Pointer;

begin
  If Not Assigned(P) then
    Writeln ('Pointer is initially NIL');
  P:=@P;
  If Not Assigned(P) then
    Writeln('Internal inconsistency')
  else
    Writeln('All is well in FPC')
end.


13.3.7 BinStr

Declaration
Function BinStr (Value : longint; cnt : byte) : String;

Description
BinStr returns a string with the binary representation of Value. The string has at most cnt characters. (i.e. only the cnt rightmost bits are taken into account) To have a complete representation of any longint-type value, you need 32 bits, i.e. cnt=32

Errors
None.
See also
Str,Val,HexStr

Example
Program example82;

{ Program to demonstrate the BinStr function }

Const Value = 45678;

Var I : longint;

begin
  For I:=8 to 20 do
    Writeln (BinStr(Value,I):20);
end.


13.3.8 Blockread

Declaration
Procedure Blockread (Var F : File; Var Buffer; Var Count : Longint [; var Result : Longint]);

Description
Blockread reads count or less records from file F. A record is a block of bytes with size specified by the Rewrite or Reset statement.

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.

Errors
If Result isn't specified, then a run-time error is generated if less than count records were read.
See also
Blockwrite, Close, Reset, Assign

Example
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));
  close(fin);
  close(fout);
end.


13.3.9 Blockwrite

Declaration
Procedure Blockwrite (Var F : File; Var Buffer; Var Count : Longint);

Description
BlockWrite writes count records from buffer to the file F.A record is a block of bytes with size specified by the Rewrite or Reset statement.

If the records couldn't be written to disk, a run-time error is generated. This behavior can be controlled by the {$i} switch.

Errors
A run-time error is generated if, for some reason, the records couldn't be written to disk.
See also
Blockread,Close, Rewrite, Assign

For the example, see Blockread.


13.3.10 Break

Declaration
Procedure Break;
Description
Break jumps to the statement following the end of the current repetitive statement. The code between the Break call and the end of the repetitive statement is skipped. The condition of the repetitive statement is NOT evaluated.

This can be used with For, varrepeat and While statements.

Note that while this is a procedure, Break is a reserved word and hence cannot be redefined.

Errors
None.
See also
Continue, Exit

Example
Program Example87;

{ Program to demonstrate the Break function. }

Var I : longint;

begin
  I:=0;
  While I<10 Do 
    begin
    Inc(I);
    If I>5 Then 
      Break;
    Writeln (i);
    end;
  I:=0;
  Repeat
    Inc(I);
    If I>5 Then 
      Break;
    Writeln (i);
  Until I>=10;
  For I:=1 to 10 do
    begin
    If I>5 Then 
      Break;
    Writeln (i);
    end;
end.


13.3.11 Chdir

Declaration
Procedure Chdir (const S : string);
Description
Chdir changes the working directory of the process to S.
Errors
If the directory S doesn't exist, a run-time error is generated.
See also
Mkdir, Rmdir

Example
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.


13.3.12 Chr

Declaration
Function Chr (X : byte) : Char;
Description
Chr returns the character which has ASCII value X.
Errors
None.
See also
Ord, Str

Example
Program Example8;

{ Program to demonstrate the Chr function. }

begin
  Write (chr(10),chr(13)); { The same effect as Writeln; } 
end.


13.3.13 Close

Declaration
Procedure Close (Var F : Anyfiletype);

Description
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.
Errors
None.
See also
Assign, Reset, Rewrite, Flush

Example
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.


13.3.14 CompareByte

Declaration
function CompareByte(var buf1,buf2;len:longint):longint;
Description
CompareByte compares two memory regions buf1,buf2 on a byte-per-byte basis for a total of len bytes.

The function returns one of the following values:

-1
if buf1 and buf2 contain different bytes in the first len bytes, and the first such byte is smaller in buf1 than the byte at the same position in buf2.
0
if the first len bytes in buf1 and buf2 are equal.
1
if buf1 and buf2 contain different bytes in the first len bytes, and the first such byte is larger in buf1 than the byte at the same position in buf2.
Errors
None.
See also
CompareChar,CompareWord,CompareDWord

Example
Program Example99;

{ Program to demonstrate the CompareByte function. }

Const 
  ArraySize     = 100;
  HalfArraySize = ArraySize Div 2;
  
Var 
  Buf1,Buf2 : Array[1..ArraySize] of byte;
  I : longint;
  
  Procedure CheckPos(Len : Longint);
  
  Begin
    Write('First ',Len,' positions are ');
    if CompareByte(Buf1,Buf2,Len)<>0 then
      Write('NOT ');
    Writeln('equal');  
  end;


begin
  For I:=1 to ArraySize do
    begin
    Buf1[i]:=I;
    If I<=HalfArraySize Then
      Buf2[I]:=I
    else
      Buf2[i]:=HalfArraySize-I;
    end; 
  CheckPos(HalfArraySize div 2);
  CheckPos(HalfArraySize);
  CheckPos(HalfArraySize+1);
  CheckPos(HalfArraySize + HalfArraySize Div 2);
end.


13.3.15 CompareChar

Declaration
function CompareChar(var buf1,buf2;len:longint):longint; function CompareChar0(var buf1,buf2;len:longint):longint;
Description
CompareChar compares two memory regions buf1,buf2 on a character-per-character basis for a total of len characters.

The CompareChar0 variant compares len bytes, or until a zero character is found.

The function returns one of the following values:

-1
if buf1 and buf2 contain different characters in the first len positions, and the first such character is smaller in buf1 than the character at the same position in buf2.
0
if the first len characters in buf1 and buf2 are equal.
1
if buf1 and buf2 contain different characters in the first len positions, and the first such character is larger in buf1 than the character at the same position in buf2.

Errors
None.
See also
CompareByte,CompareWord,CompareDWord

Example
Program Example100;

{ Program to demonstrate the CompareChar function. }

Const 
  ArraySize     = 100;
  HalfArraySize = ArraySize Div 2;
  
Var 
  Buf1,Buf2 : Array[1..ArraySize] of char;
  I : longint;
  
  Procedure CheckPos(Len : Longint);
  
  Begin
    Write('First ',Len,' characters are ');
    if CompareChar(Buf1,Buf2,Len)<>0 then
      Write('NOT ');
    Writeln('equal');  
  end;

  Procedure CheckNullPos(Len : Longint);
  
  Begin
    Write('First ',Len,' non-null characters are ');
    if CompareChar0(Buf1,Buf2,Len)<>0 then
      Write('NOT ');
    Writeln('equal');  
  end;

begin
  For I:=1 to ArraySize do
    begin
    Buf1[i]:=chr(I);
    If I<=HalfArraySize Then
      Buf2[I]:=chr(I)
    else
      Buf2[i]:=chr(HalfArraySize-I);
    end; 
  CheckPos(HalfArraySize div 2);
  CheckPos(HalfArraySize);
  CheckPos(HalfArraySize+1);
  CheckPos(HalfArraySize + HalfArraySize Div 2);
  For I:=1 to 4 do
    begin
    buf1[Random(ArraySize)+1]:=Chr(0);
    buf2[Random(ArraySize)+1]:=Chr(0);
    end;
  Randomize;  
  CheckNullPos(HalfArraySize div 2);
  CheckNullPos(HalfArraySize);
  CheckNullPos(HalfArraySize+1);
  CheckNullPos(HalfArraySize + HalfArraySize Div 2);
end.


13.3.16 CompareDWord

Declaration
function CompareDWord(var buf1,buf2;len:longint):longint;
Description
CompareDWord compares two memory regions buf1,buf2 on a DWord-per-DWord basis for a total of len DWords. (A DWord is 4 bytes).

The function returns one of the following values:

-1
if buf1 and buf2 contain different DWords in the first len DWords, and the first such DWord is smaller in buf1 than the DWord at the same position in buf2.
0
if the first len DWords in buf1 and buf2 are equal.
1
if buf1 and buf2 contain different DWords in the first len DWords, and the first such DWord is larger in buf1 than the DWord at the same position in buf2.
Errors
None.
See also
CompareChar,CompareByte,CompareWord,

Example
Program Example101;

{ Program to demonstrate the CompareDWord function. }

Const 
  ArraySize     = 100;
  HalfArraySize = ArraySize Div 2;
  
Var 
  Buf1,Buf2 : Array[1..ArraySize] of Dword;
  I : longint;
  
  Procedure CheckPos(Len : Longint);
  
  Begin
    Write('First ',Len,' DWords are ');
    if CompareDWord(Buf1,Buf2,Len)<>0 then
      Write('NOT ');
    Writeln('equal');  
  end;


begin
  For I:=1 to ArraySize do
    begin
    Buf1[i]:=I;
    If I<=HalfArraySize Then
      Buf2[I]:=I
    else
      Buf2[i]:=HalfArraySize-I;
    end; 
  CheckPos(HalfArraySize div 2);
  CheckPos(HalfArraySize);
  CheckPos(HalfArraySize+1);
  CheckPos(HalfArraySize + HalfArraySize Div 2);
end.


13.3.17 CompareWord

Declaration
function CompareWord(var buf1,buf2;len:longint):longint;
Description
CompareWord compares two memory regions buf1,buf2 on a Word-per-Word basis for a total of len Words. (A Word is 2 bytes).

The function returns one of the following values:

-1
if buf1 and buf2 contain different Words in the first len Words, and the first such Word is smaller in buf1 than the Word at the same position in buf2.
0
if the first len Words in buf1 and buf2 are equal.
1
if buf1 and buf2 contain different Words in the first len Words, and the first such Word is larger in buf1 than the Word at the same position in buf2.
Errors
None.
See also
CompareChar,CompareByte,CompareWord,

Example
Program Example102;

{ Program to demonstrate the CompareWord function. }

Const 
  ArraySize     = 100;
  HalfArraySize = ArraySize Div 2;
  
Var 
  Buf1,Buf2 : Array[1..ArraySize] of Word;
  I : longint;
  
  Procedure CheckPos(Len : Longint);
  
  Begin
    Write('First ',Len,' words are ');
    if CompareWord(Buf1,Buf2,Len)<>0 then
      Write('NOT ');
    Writeln('equal');  
  end;


begin
  For I:=1 to ArraySize do
    begin
    Buf1[i]:=I;
    If I<=HalfArraySize Then
      Buf2[I]:=I
    else
      Buf2[i]:=HalfArraySize-I;
    end; 
  CheckPos(HalfArraySize div 2);
  CheckPos(HalfArraySize);
  CheckPos(HalfArraySize+1);
  CheckPos(HalfArraySize + HalfArraySize Div 2);
end.


13.3.18 Concat

Declaration
Function Concat (S1,S2 [,S3, ... ,Sn]) : String;

Description
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.
Errors
None.
See also
Copy, Delete, Insert, Pos, Length

Example
Program Example10;

{ Program to demonstrate the Concat function. }
Var 
  S : String;
  
begin
  S:=Concat('This can be done',' Easier ','with the + operator !');
end.


13.3.19 Continue

Declaration
Procedure Continue;
Description
Continue jumps to the end of the current repetitive statement. The code between the Continue call and the end of the repetitive statement is skipped. The condition of the repetitive statement is then checked again.

This can be used with For, varrepeat and While statements.

Note that while this is a procedure, Continue is a reserved word and hence cannot be redefined.

Errors
None.
See also
Break, Exit

Example
Program Example86;

{ Program to demonstrate the Continue function. }

Var I : longint;

begin
  I:=0;
  While I<10 Do 
    begin
    Inc(I);
    If I<5 Then 
      Continue;
    Writeln (i);
    end;
  I:=0;
  Repeat
    Inc(I);
    If I<5 Then 
      Continue;
    Writeln (i);
  Until I>=10;
  For I:=1 to 10 do
    begin
    If I<5 Then 
      Continue;
    Writeln (i);
    end;
end.


13.3.20 Copy

Declaration
Function Copy (Const S : String;Index : Integer;Count : Byte) : String;

Description
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.
Errors
None.
See also
Delete, Insert, Pos

Example
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.


13.3.21 Cos

Declaration
Function Cos (X : Real) : Real;

Description
Cos returns the cosine of X, where X is an angle, in radians.

If the absolute value of the argument is larger than 2^63, then the result is undefined.

Errors
None.
See also
Arctan, Sin

Example
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.


13.3.22 CSeg

Declaration
Function CSeg : Word;

Description
CSeg returns the Code segment register. In Free Pascal, it returns always a zero, since Free Pascal is a 32 bit compiler.
Errors
None.
See also
DSeg, Seg, Ofs, Ptr

Example
Program Example13;

{ Program to demonstrate the CSeg function. }

var W : word;

begin
  W:=CSeg; {W:=0, provided for compatibility,
                  FPC is 32 bit.}
end.


13.3.23 Dec

Declaration
Procedure Dec (Var X : Any ordinal type[; Decrement : Longint]);

Description
Dec decreases the value of X with Decrement. If Decrement isn't specified, then 1 is taken as a default.
Errors
A range check can occur, or an underflow error, if you try to decrease X below its minimum value.
See also
Inc

Example
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.


13.3.24 Delete

Declaration
Procedure Delete (var S : string;Index : Integer;Count : Integer);

Description
Delete removes Count characters from string S, starting at position Index. All characters after the delected characters are shifted Count positions to the left, and the length of the string is adjusted.

Errors
None.
See also
Copy,Pos,Insert

Example
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.


13.3.25 Dispose

Declaration
Procedure Dispose (P : pointer);
Procedure Dispiose (P : Typed Pointer; Des : Procedure);
Description
The first form Dispose releases the memory allocated with a call to New. The pointer P must be typed. The released memory is returned to the heap.

The second form of Dispose accepts as a first parameter a pointer to an object type, and as a second parameter the name of a destructor of this object. The destructor will be called, and the memory allocated for the object will be freed.

Errors
An error will occur if the pointer doesn't point to a location in the heap.
See also
New, Getmem, Freemem

Example
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.


13.3.26 DSeg

Declaration
Function DSeg : Word;

Description
DSeg returns the data segment register. In Free Pascal, it returns always a zero, since Free Pascal is a 32 bit compiler.
Errors
None.
See also
CSeg, Seg, Ofs, Ptr

Example
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.


13.3.27 Eof

Declaration
Function Eof [(F : Any file type)] : Boolean;

Description
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.
Errors
None.
See also
Eoln, Assign, Reset, Rewrite

Example
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.


13.3.28 Eoln

Declaration
Function Eoln [(F : Text)] : Boolean;

Description
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.
Errors
None.
See also
Eof, Assign, Reset, Rewrite

Example
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.}
  While not Eoln do
    Writeln (eoln);
end.


13.3.29 Erase

Declaration
Procedure Erase (Var F : Any file type);

Description
Erase removes an unopened file from disk. The file should be assigned with Assign, but not opened with Reset or Rewrite
Errors
A run-time error will be generated if the specified file doesn't exist, or is opened by the program.
See also
Assign

Example
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.


13.3.30 Exit

Declaration
Procedure Exit ([Var X : return type )];

Description
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.
Errors
None.
See also
Halt

Example
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.


13.3.31 Exp

Declaration
Function Exp (Var X : Real) : Real;

Description
Exp returns the exponent of X, i.e. the number e to the power X.
Errors
None.
See also
Ln, Power

Example
Program Example22;

{ Program to demonstrate the Exp function. }

begin
  Writeln (Exp(1):8:2); { Should print 2.72 }
end.


13.3.32 Filepos

Declaration
Function Filepos (Var F : Any file type) : Longint;

Description
Filepos returns the current record position of the file-pointer in file F. It cannot be invoked with a file of type Text. If you try to do this, a compiler error will be generated.
Errors
None.
See also
Filesize

Example
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 all goes well, nothing is displayed here. }
  While not (Eof(F)) do
    begin
    FP:=FilePos (F);
    Read (F,L);
    if L<>FP then 
      Writeln ('Something wrong: Got ',l,' on pos ',FP);
    end;
  Close (F);
  Erase (f);
end.


13.3.33 Filesize

Declaration
Function Filesize (Var F : Any file type) : Longint;
Description
Filesize 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.
Errors
None.
See also
Filepos

Example
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.


13.3.34 FillByte

Declaration
Procedure FillByte(var X;Count:longint;Value:byte);
Description
FillByte fills the memory starting at X with Count bytes with value equal to Value.

This is useful for quickly zeroing out a memory location. If you know that the size of the memory location to be filled out is a multiple of 2 bytes, it is better to use Fillword, and if it is a multiple of 4 bytes it's better to use FillDWord, these routines are optimized for their respective sizes.

Errors
No checking on the size of X is done.
See also
Fillchar, FillDWord, Fillword, Move

Example
Program Example102;

{ Program to demonstrate the CompareWord function. }

Const 
  ArraySize     = 100;
  HalfArraySize = ArraySize Div 2;
  
Var 
  Buf1,Buf2 : Array[1..ArraySize] of Word;
  I : longint;
  
  Procedure CheckPos(Len : Longint);
  
  Begin
    Write('First ',Len,' words are ');
    if CompareWord(Buf1,Buf2,Len)<>0 then
      Write('NOT ');
    Writeln('equal');  
  end;


begin
  For I:=1 to ArraySize do
    begin
    Buf1[i]:=I;
    If I<=HalfArraySize Then
      Buf2[I]:=I
    else
      Buf2[i]:=HalfArraySize-I;
    end; 
  CheckPos(HalfArraySize div 2);
  CheckPos(HalfArraySize);
  CheckPos(HalfArraySize+1);
  CheckPos(HalfArraySize + HalfArraySize Div 2);
end.


13.3.35 Fillchar

Declaration
Procedure Fillchar (Var X;Count : Longint;Value : char or byte);;

Description
Fillchar fills the memory starting at X with Count bytes or characters with value equal to Value.

Errors
No checking on the size of X is done.
See also
Fillword, Move, FillByte, FillDWord

Example
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 }
    SetLength(S,I);
    Writeln (s,'*');
    end;
end.


13.3.36 FillDWord

Declaration
Procedure FillDWord (Var X;Count : Longint;Value : DWord);;
Description
Fillword fills the memory starting at X with Count DWords with value equal to Value. A DWord is 4 bytes in size.

Errors
No checking on the size of X is done.
See also
FillByte, Fillchar, Fillword, Move

Example
Program Example103;

{ Program to demonstrate the FillByte function. }

Var S : String[10];
    I : Byte;

begin
  For i:=10 downto 0 do
    begin
    { Fill S with i bytes }
    FillChar (S,SizeOf(S),32);
    { Set Length }
    SetLength(S,I);
    Writeln (s,'*');
    end;
end.


13.3.37 Fillword

Declaration
Procedure Fillword (Var X;Count : Longint;Value : Word);;
Description
Fillword fills the memory starting at X with Count words with value equal to Value. A word is 2 bytes in size.
Errors
No checking on the size of X is done.
See also
Fillchar, Move

Example
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.


13.3.38 Flush

Declaration
Procedure Flush (Var F : Text);

Description
Flush empties the internal buffer of an opened file F and writes the contents to disk. The file is not closed as a result of this call.
Errors
If the disk is full, a run-time error will be generated.
See also
Close

Example
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.


13.3.39 Frac

Declaration
Function Frac (X : Real) : Real;

Description
Frac returns the non-integer part of X.
Errors
None.
See also
Round, Int

Example
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.


13.3.40 Freemem

Declaration
Procedure Freemem (Var P : pointer; Count : Longint);

Description
Freemem releases the memory occupied by the pointer P, of size Count (in bytes), and returns it to the heap. P should point to the memory allocated to a dynamical variable.
Errors
An error will occur when P doesn't point to the heap.
See also
Getmem, New, Dispose

Example
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.


13.3.41 Getdir

Declaration
Procedure Getdir (drivenr : byte;var dir : string);

Description
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.
Errors
An error is returned under DOS, if the drive requested isn't ready.
See also
Chdir

Example
Program Example29;

{ Program to demonstrate the GetDir function. }

Var S : String;

begin
  GetDir (0,S);
  Writeln ('Current directory is : ',S);
end.


13.3.42 Getmem

Declaration
Procedure Getmem (var p : pointer;size : Longint);

Description
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.
Errors
None.
See also
Freemem, Dispose, New
For an example, see Freemem.


13.3.43 GetMemoryManager

Declaration
procedure GetMemoryManager(var MemMgr: TMemoryManager);
Description
GetMemoryManager stores the current Memory Manager record in MemMgr.
Errors
None.
See also
SetMemoryManager, IsMemoryManagerSet.

For an example, see Programmers' guide.


13.3.44 Halt

Declaration
Procedure Halt [(Errnum : byte)];
Description
Halt stops program execution and returns control to the calling program. The optional argument Errnum specifies an exit value. If omitted, zero is returned.
Errors
None.
See also
Exit

Example
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.


13.3.45 HexStr

Declaration
Function HexStr (Value : longint; cnt : byte) : String;
Description
HexStr returns a string with the hexadecimal representation of Value. The string has at most cnt charaters. (i.e. only the cnt rightmost nibbles are taken into account) To have a complete representation of a Longint-type value, you need 8 nibbles, i.e. cnt=8.

Errors
None.
See also
Str, Val, BinStr

Example
Program example81;

{ Program to demonstrate the HexStr function }

Const Value = 45678;

Var I : longint;

begin
  For I:=1 to 10 do
    Writeln (HexStr(Value,I));
end.


13.3.46 Hi

Declaration
Function Hi (X : Ordinal type) : Word or byte;

Description
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 returned. Hi cannot be invoked on types of size 1, such as byte or char.
Errors
None
See also
Lo

Example
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.


13.3.47 High

Declaration
Function High (Type identifier or variable reference) : Ordinal;

Description
The return value of High depends on it's argument:
  1. If the argument is an ordinal type, High returns the lowest value in the range of the given ordinal type.
  2. If the argument is an array type or an array type variable then High returns the highest possible value of it's index.
  3. If the argument is an open array identifier in a function or procedure, then High returns the highest index of the array, as if the array has a zero-based index.
The return type is always the same type as the type of the argument (This can lead to some nasty surprises !).
Errors
None.
See also
Low, Ord, Pred, Succ

Example
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));  
  Write ('Type of return value is always same as type of argument:');
  Writeln(high(high(word)));
end.


13.3.48 Inc

Declaration
Procedure Inc (Var X : Any ordinal type[; Increment : Longint]);

Description
Inc increases the value of X with Increment. If Increment isn't specified, then 1 is taken as a default.
Errors
If range checking is on, then A range check can occur, or an overflow error, if you try to increase X over its maximum value.
See also
Dec

Example
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.


13.3.49 IndexByte

Declaration
function IndexByte(var buf;len:longint;b:byte):longint;
Description
IndexByte searches the memory at buf for maximally len positions for the byte b and returns it's position if it found one. If b is not found then -1 is returned.

The position is zero-based.

Errors
Buf and Len are not checked to see if they are valid values.
See also
IndexChar, IndexDWord, IndexWord, CompareByte

Example
Program Example105;

{ Program to demonstrate the IndexByte function. }

Const
  ArraySize = 256;
  MaxValue = 256;
  
Var
  Buffer : Array[1..ArraySize] of Byte; 
  I,J : longint;
  K : Byte;
  
begin
  Randomize;
  For I:=1 To ArraySize do 
    Buffer[I]:=Random(MaxValue);
  For I:=1 to 10 do
    begin
    K:=Random(MaxValue);
    J:=IndexByte(Buffer,ArraySize,K);
    if J=-1 then
      Writeln('Value ',K,' was not found in buffer.')
    else
      Writeln('Found ',K,' at position ',J,' in buffer');
    end;  
end.


13.3.50 IndexChar

Declaration
function IndexChar(var buf;len:longint;b:char):longint; function IndexChar0(var buf;len:longint;b:char):longint;
Description
IndexChar searches the memory at buf for maximally len positions for the character b and returns it's position if it found one. If b is not found then -1 is returned.

The position is zero-based. The IndexChar0 variant stops looking if a null character is found, and returns -1 in that case.

Errors
Buf and Len are not checked to see if they are valid values.
See also
IndexByte, IndexDWord, IndexWord, CompareChar

Example
Program Example108;

{ Program to demonstrate the IndexChar function. }

Const
  ArraySize = 1000;
  MaxValue = 26;
  
Var
  Buffer : Array[1..ArraySize] of Char; 
  I,J : longint;
  K : Char;
  
begin
  Randomize;
  For I:=1 To ArraySize do 
    Buffer[I]:=chr(Ord('A')+Random(MaxValue));
  For I:=1 to 10 do
    begin
    K:=chr(Ord('A')+Random(MaxValue));
    J:=IndexChar(Buffer,ArraySize,K);
    if J=-1 then
      Writeln('Value ',K,' was not found in buffer.')
    else
      Writeln('Found ',K,' at position ',J,' in buffer');
    end;  
end.


13.3.51 IndexDWord

Declaration
function IndexDWord(var buf;len:longint;DW:DWord):longint; IndexChar searches the memory at buf for maximally len positions for the DWord DW and returns it's position if it found one. If DW is not found then -1 is returned.

The position is zero-based.

Errors
Buf and Len are not checked to see if they are valid values.
See also
IndexByte, IndexChar, IndexWord, CompareDWord

Example
Program Example106;

{ Program to demonstrate the IndexDWord function. }

Const
  ArraySize = 1000;
  MaxValue = 1000;
  
Var
  Buffer : Array[1..ArraySize] of DWord; 
  I,J : longint;
  K : DWord;
  
begin
  Randomize;
  For I:=1 To ArraySize do 
    Buffer[I]:=Random(MaxValue);
  For I:=1 to 10 do
    begin
    K:=Random(MaxValue);
    J:=IndexDWord(Buffer,ArraySize,K);
    if J=-1 then
      Writeln('Value ',K,' was not found in buffer.')
    else
      Writeln('Found ',K,' at position ',J,' in buffer');
    end;  
end.


13.3.52 IndexWord

Declaration
function IndexWord(var buf;len:longint;W:word):longint; IndexChar searches the memory at buf for maximally len positions for the Word W and returns it's position if it found one. If W is not found then -1 is returned.
Errors
Buf and Len are not checked to see if they are valid values.
See also
IndexByte, IndexDWord, IndexChar, CompareWord

Example
Program Example107;

{ Program to demonstrate the IndexWord function. }

Const
  ArraySize = 1000;
  MaxValue = 1000;
  
Var
  Buffer : Array[1..ArraySize] of Word; 
  I,J : longint;
  K : Word;
  
begin
  Randomize;
  For I:=1 To ArraySize do 
    Buffer[I]:=Random(MaxValue);
  For I:=1 to 10 do
    begin
    K:=Random(MaxValue);
    J:=IndexWord(Buffer,ArraySize,K);
    if J=-1 then
      Writeln('Value ',K,' was not found in buffer.')
    else
      Writeln('Found ',K,' at position ',J,' in buffer');
    end;  
end.


13.3.53 Insert

Declaration
Procedure Insert (Const Source : String;var S : String;Index : Longint);

Description
Insert inserts string Source in string S, at position Index, shifting all characters after Index to the right. The resulting string is truncated at 255 characters, if needed. (i.e. for shortstrings)
Errors
None.
See also
Delete, Copy, Pos

Example
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.


13.3.54 IsMemoryManagerSet

Declaration
function IsMemoryManagerSet: Boolean;
Description
IsMemoryManagerSet will return True if the memory manager has been set to another value than the system heap manager, it will return False otherwise.
Errors
None.
See also
SetMemoryManager, GetMemoryManager


13.3.55 Int

Declaration
Function Int (X : Real) : Real;

Description
Int returns the integer part of any Real X, as a Real.
Errors
None.
See also
Frac, Round

Example
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.


13.3.56 IOresult

Declaration
Function IOresult : Word;

Description
IOresult contains the result of any input/output call, when the {$i-} compiler directive is active, disabling IO checking. 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 :

2
File not found.
3
Path not found.
4
Too many open files.
5
Access denied.
6
Invalid file handle.
12
Invalid file-access mode.
15
Invalid disk number.
16
Cannot remove current directory.
17
Cannot rename across volumes.
I/O errors :
100
Error when reading from disk.
101
Error when writing to disk.
102
File not assigned.
103
File not open.
104
File not opened for input.
105
File not opened for output.
106
Invalid number.
Fatal errors :
150
Disk is write protected.
151
Unknown device.
152
Drive not ready.
153
Unknown command.
154
CRC check failed.
155
Invalid drive specified..
156
Seek error on disk.
157
Invalid media type.
158
Sector not found.
159
Printer out of paper.
160
Error when writing to device.
161
Error when reading from device.
162
Hardware failure.

Errors
None.
See also
All I/O functions.

Example
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.


13.3.57 Length

Declaration
Function Length (S : String) : Byte;

Description
Length returns the length of the string S, which is limited to 255 for shortstrings. If the strings S is empty, 0 is returned. Note: The length of the string S is stored in S[0] for shortstrings only. Ansistrings have their length stored elsewhere, the Length fuction should always be used on ansistrings.

Errors
None.
See also
Pos

Example
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.


13.3.58 Ln

Declaration
Function Ln (X : Real) : Real;

Description

Ln returns the natural logarithm of the Real parameter X. X must be positive.

Errors
An run-time error will occur when X is negative.
See also
Exp, Power

Example
Program Example37;

{ Program to demonstrate the Ln function. }

begin
  Writeln (Ln(1));      { Prints 0 }
  Writeln (Ln(Exp(1))); { Prints 1 }
end.


13.3.59 Lo

Declaration
Function Lo (O : Word or Longint) : Byte or Word;

Description
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.
Errors
None.
See also
Ord, Chr, Hi

Example
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.


13.3.60 LongJmp

Declaration
Procedure LongJmp (Var env : Jmp_Buf; Value : Longint);

Description

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.

Errors
None.
See also
SetJmp
For an example, see SetJmp


13.3.61 Low

Declaration
Function Low (Type identifier or variable reference) : Longint;

Description
The return value of Low depends on it's argument:
  1. If the argument is an ordinal type, Low returns the lowest value in the range of the given ordinal type.
  2. If the argument is an array type or an array type variable then Low returns the lowest possible value of it's index.
The return type is always the same type as the type of the argument
Errors
None.
See also
High, Ord, Pred, Succ
for an example, see High.


13.3.62 Lowercase

Declaration
Function Lowercase (C : Char or String) : Char or String;

Description
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.
Errors
None.
See also
Upcase

Example
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.


13.3.63 Mark

Declaration
Procedure Mark (Var P : Pointer);

Description
Mark copies the current heap-pointer to P.
Errors
None.
See also
Getmem, Freemem, New, Dispose, Maxavail

Example
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.


13.3.64 Maxavail

Declaration
Function Maxavail : Longint;

Description
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.

Errors
None.
See also
Release, Memavail,Freemem, Getmem

Example
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.


13.3.65 Memavail

Declaration
Function Memavail : Longint;

Description
Memavail returns the size, in bytes, of the free heap memory.

Remark: The heap grows dynamically if more memory is needed than is available.

Errors
None.
See also
Maxavail,Freemem, Getmem

Example
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.


13.3.66 Mkdir

Declaration
Procedure Mkdir (const S : string);

Description
Mkdir creates a new directory S.
Errors
If a parent-directory of directory S doesn't exist, a run-time error is generated.
See also
Chdir, Rmdir
For an example, see Rmdir.


13.3.67 Move

Declaration
Procedure Move (var Source,Dest;Count : Longint);
Description
Move moves Count bytes from Source to Dest.
Errors
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.
See also
Fillword, Fillchar

Example
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.


13.3.68 MoveChar0

Declaration
procedure MoveChar0(var Src,Dest;Count:longint);
Description
MoveChar0 moves Count bytes from Src to Dest, and stops moving if a zero character is found.
Errors
No checking is done to see if Count stays within the memory allocated to the process.
See also
Move

Example
Program Example109;

{ Program to demonstrate the MoveChar0 function. }

Var 
  Buf1,Buf2 : Array[1..80] of char;
  I : longint;
    
begin
  Randomize;
  For I:=1 to 80 do
    Buf1[i]:=chr(Random(16)+Ord('A'));
  Writeln('Original buffer');
  writeln(Buf1);
  Buf1[Random(80)+1]:=#0;
  MoveChar0(Buf1,Buf2,80);  
  Writeln('Randomly zero-terminated Buffer');
  Writeln(Buf2);
end.


13.3.69 New

Declaration
Procedure New (Var P : Pointer[, Constructor]);

Description
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.
Errors
If not enough memory is available, Nil will be returned.
See also
Dispose, Freemem, Getmem, Memavail, Maxavail
For an example, see Dispose.


13.3.70 Odd

Declaration
Function Odd (X : Longint) : Boolean;

Description
Odd returns True if X is odd, or False otherwise.
Errors
None.
See also
Abs, Ord

Example
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.


13.3.71 Ofs

Declaration
Function Ofs Var X : Longint;

Description
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.

Errors
None.
See also
DSeg, CSeg, Seg, Ptr

Example
Program Example44;

{ Program to demonstrate the Ofs function. }

Var W : Pointer;


begin
  W:=Pointer(Ofs(W)); { W contains its own offset. } 
end.


13.3.72 Ord

Declaration
Function Ord (X : Any ordinal type) : Longint;

Description
Ord returns the Ordinal value of a ordinal-type variable X.
Errors
None.
See also
Chr, Succ, Pred, High, Low

Example
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.


13.3.73 Paramcount

Declaration
Function Paramcount : Longint;

Description
Paramcount returns the number of command-line arguments. If no arguments were given to the running program, 0 is returned.

Errors
None.
See also
Paramstr

Example
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.


13.3.74 Paramstr

Declaration
Function Paramstr (L : Longint) : String;

Description
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.

Errors
None.
See also
Paramcount
For an example, see Paramcount.


13.3.75 Pi

Declaration
Function Pi : Real;

Description
Pi returns the value of Pi (3.1415926535897932385).
Errors
None.
See also
Cos, Sin

Example
Program Example47;

{ Program to demonstrate the Pi function. }

begin
  Writeln (Pi);         {3.1415926}
  Writeln (Sin(Pi));
end.


13.3.76 Pos

Declaration
Function Pos (Const Substr : String;Const S : String) : Byte;
Description
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.
Errors
None
See also
Length, Copy, Delete, Insert

Example
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.


13.3.77 Power

Declaration
Function Power (base,expon : Real) : Real;
Description

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))

Errors
None.
See also
Exp, Ln

Example
Program Example78;

{ Program to demonstrate the Power function. }

begin
  Writeln (Power(exp(1.0),1.0):8:2); { Should print 2.72 }
end.


13.3.78 Pred

Declaration
Function Pred (X : Any ordinal type) : Same type;
Description
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.
Errors
Run-time error 201 is generated when the result is out of range.
See also
Ord, Pred, High, Low

for an example, see Ord


13.3.79 Ptr

Declaration
Function Ptr (Sel,Off : Longint) : Pointer;
Description
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.
  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.

Errors
None.
See also
Addr

Example
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.


13.3.80 Random

Declaration
Function Random [(L : Longint)] : Longint or Real;

Description
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)
Errors
None.
See also
Randomize

Example
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.


13.3.81 Randomize

Declaration
Procedure Randomize ;

Description
Randomize initializes the random number generator of Free Pascal, by giving a value to Randseed, calculated with the system clock.

Errors
None.
See also
Random
For an example, see Random.


13.3.82 Read

Declaration
Procedure Read ([Var F : Any file type], V1 [, V2, ... , Vn]);

Description
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, String or PChar. 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.
Errors
If no data is available, a run-time error is generated. This behavior can be controlled with the {$i} compiler switch.
See also
Readln, Blockread, Write, Blockwrite

Example
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.


13.3.83 Readln

Declaration
Procedure Readln [Var F : Text], V1 [, V2, ... , Vn]);

Description
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.

Errors
If no data is available, a run-time error is generated. This behavior can be controlled with the {$i} compiler switch.
See also
Read, Blockread, Write, Blockwrite
For an example, see Read.


13.3.84 Release

Declaration
Procedure Release (Var P : pointer);

Description
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.
Errors
A run-time error will be generated if P points to memory outside the heap.
See also
Mark, Memavail, Maxavail, Getmem, Freemem New, Dispose
For an example, see Mark.


13.3.85 Rename

Declaration
Procedure Rename (Var F : Any Filetype; Const S : String);
Description
Rename changes the name of the assigned file F to S. F must be assigned, but not opened.
Errors
A run-time error will be generated if F isn't assigned, or doesn't exist.
See also
Erase

Example
Program Example77;

{ Program to demonstrate the Rename function. }
Var F : Text;

begin
  Assign (F,paramstr(1));
  Rename (F,paramstr(2));
end.


13.3.86 Reset

Declaration
Procedure Reset (Var F : Any File Type[; L : Longint]);
Description
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.
Errors
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.
See also
Rewrite, Assign, Close, Append

Example
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.


13.3.87 Rewrite

Declaration
Procedure Rewrite (Var F : Any File Type[; L : Longint]);
Description
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.

Contrary to , Free Pascal opens the file with mode fmoutput. If you want to get it in fminout mode, you'll need to do an extra call to Reset.

Errors
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.
See also
Reset, Assign, Close, Flush, Append

Example
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.


13.3.88 Rmdir

Declaration
Procedure Rmdir (const S : string);

Description
Rmdir removes the directory S.
Errors
If S doesn't exist, or isn't empty, a run-time error is generated.

See also
Chdir, Mkdir

Example
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.


13.3.89 Round

Declaration
Function Round (X : Real) : Longint;

Description
Round rounds X to the closest integer, which may be bigger or smaller than X.
Errors
None.
See also
Frac, Int, Trunc

Example
Program Example54;

{ Program to demonstrate the Round function. }

begin
  Writeln (Round(1234.56));  { Prints 1235  }
  Writeln (Round(-1234.56)); { Prints -1235 }
  Writeln (Round(12.3456));  { Prints 12    }
  Writeln (Round(-12.3456)); { Prints -12   }
end.


13.3.90 Runerror

Declaration
Procedure Runerror (ErrorCode : Word);

Description
Runerror stops the execution of the program, and generates a run-time error ErrorCode.
Errors
None.
See also
Exit, Halt

Example
Program Example55;

{ Program to demonstrate the RunError function. }

begin
  { The program will stop end emit a run-error 106 }
  RunError (106);
end.


13.3.91 Seek

Declaration
Procedure Seek (Var F; Count : Longint);

Description
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 record size specified in Reset or Rewrite, 128 is assumed.
Errors
A run-time error is generated if Count points to a position outside the file, or the file isn't opened.
See also
Eof, SeekEof, SeekEoln

Example
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.


13.3.92 SeekEof

Declaration
Function SeekEof [(Var F : text)] : Boolean;

Description
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.

Errors
A run-time error is generated if the file F isn't opened.
See also
Eof, SeekEoln, Seek

Example
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.


13.3.93 SeekEoln

Declaration
Function SeekEoln [(Var F : text)] : Boolean;

Description
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.
Errors
A run-time error is generated if the file F isn't opened.
See also
Eof, SeekEof, Seek

Example
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.


13.3.94 Seg

Declaration
Function Seg Var X : Longint;

Description
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.

Errors
None.
See also
DSeg, CSeg, Ofs, Ptr

Example
Program Example60;

{ Program to demonstrate the Seg function. }
Var 
  W : Word;

begin
  W:=Seg(W);  { W contains its own Segment}
end.


13.3.95 SetMemoryManager

Declaration
procedure SetMemoryManager(const MemMgr: TMemoryManager);
Description
SetMemoryManager sets the current memory manager record to MemMgr.
Errors
None.
See also
GetMemoryManager, IsMemoryManagerSet

For an example, see Programmers' guide.


13.3.96 SetJmp

Declaration
Function SetJmp (Var Env : Jmp_Buf) : Longint;

Description

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.

Errors
None.
See also
LongJmp

Example
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.


13.3.97 SetLength

Declaration
Procedure SetLength(var S : String; Len : Longint);
Description
SetLength sets the length of the string S to Len. S can be an ansistring or a short string. For ShortStrings, Len can maximally be 255. For AnsiStrings it can have any value. For AnsiString strings, SetLength must be used to set the length of the string.
Errors
None.
See also
Length

Example
Program Example85;

{ Program to demonstrate the SetLength function. }

Var S : String;

begin
  FillChar(S[1],100,#32);
  Setlength(S,100);
  Writeln ('"',S,'"');
end.


13.3.98 SetTextBuf

Declaration
Procedure SetTextBuf (Var f : Text; Var Buf[; Size : Word]);

Description
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:

Errors
No checking on Size is done.
See also
Assign, Reset, Rewrite, Append

Example
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.


13.3.99 Sin

Declaration
Function Sin (X : Real) : Real;

Description
Sin returns the sine of its argument X, where X is an angle in radians.

If the absolute value of the argument is larger than 2^63, then the result is undefined.

Errors
None.
See also
Cos, Pi, Exp, Ln

Example
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.


13.3.100 SizeOf

Declaration
Function SizeOf (X : Any Type) : Longint;

Description
SizeOf returns the size, in bytes, of any variable or type-identifier.

Remark: This isn't really a RTL function. It's result is calculated at compile-time, and hard-coded in your executable.

Errors
None.
See also
Addr

Example
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.


13.3.101 Sptr

Declaration
Function Sptr : Pointer;

Description
Sptr returns the current stack pointer.

Errors
None.
See also
SSeg

Example
Program Example64;

{ Program to demonstrate the SPtr function. }
Var
  P :Longint;

begin
  P:=Sptr; { P Contains now the current stack position. }
end.


13.3.102 Sqr

Declaration
Function Sqr (X : Real) : Real;

Description
Sqr returns the square of its argument X.
Errors
None.
See also
Sqrt, Ln, Exp

Example
Program Example65;

{ Program to demonstrate the Sqr function. }
Var i : Integer;
    
begin
  For i:=1 to 10 do
    writeln (Sqr(i):3);
end.


13.3.103 Sqrt

Declaration
Function Sqrt (X : Real) : Real;

Description
Sqrt returns the square root of its argument X, which must be positive.
Errors
If X is negative, then a run-time error is generated.
See also
Sqr, Ln, Exp

Example
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.


13.3.104 SSeg

Declaration
Function SSeg : Longint;

Description
SSeg returns the Stack Segment. This function is only supported for compatibility reasons, as Sptr returns the correct contents of the stackpointer.
Errors
None.
See also
Sptr

Example
Program Example67;

{ Program to demonstrate the SSeg function. }
Var W : Longint;

begin
  W:=SSeg;  
end.


13.3.105 Str

Declaration
Procedure Str (Var X[:NumPlaces[:Decimals]]; Var S : String);

Description
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.
Errors
None.
See also
Val

Example
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.


13.3.106 StringOfChar

Declaration
Function StringOfChar(c : char;l : longint) : AnsiString;
Description
StringOfChar creates a new Ansistring of length l and fills it with the character c.

It is equivalent to the following calls:

SetLength(StringOfChar,l);
FillChar(Pointer(StringOfChar)^,Length(StringOfChar),c);
Errors
None.
See also
SetLength

Example
Program Example97;

{$H+}

{ Program to demonstrate the StringOfChar function. }

Var S : String;

begin
  S:=StringOfChar(' ',40)+'Aligned at column 41.';
  Writeln(s);
end.


13.3.107 Succ

Declaration
Function Succ (X : Any ordinal type) : Same type;

Description
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.

Errors
Run-time error 201 is generated when the result is out of range.
See also
Ord, Pred, High, Low
for an example, see Ord.


13.3.108 Swap

Declaration
Function Swap (X) : Type of X;

Description
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
Errors
None.
See also
Lo, Hi

Example
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.


13.3.109 Trunc

Declaration
Function Trunc (X : Real) : Longint;

Description
Trunc returns the integer part of X, which is always smaller than (or equal to) X in absolute value.
Errors
None.
See also
Frac, Int, Round

Example
Program Example70;

{ 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.


13.3.110 Truncate

Declaration
Procedure Truncate (Var F : file);

Description
Truncate truncates the (opened) file F at the current file position.

Errors
Errors are reported by IOresult.
See also
Append, Filepos, Seek

Example
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.


13.3.111 Upcase

Declaration
Function Upcase (C : Char or string) : Char or String;

Description
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.
Errors
None.
See also
Lowercase

Example
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.


13.3.112 Val

Declaration
Procedure Val (const S : string;var V;var Code : word);

Description
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 allowed to contain spaces.
Errors
If the conversion doesn't succeed, the value of Code indicates the position where the conversion went wrong.
See also
Str

Example
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.


13.3.113 Write

Declaration
Procedure Write ([Var F : Any filetype;] V1 [; V2; ... , Vn)];

Description
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 nothing 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.

Errors
If an error occurs, a run-time error is generated. This behavior can be controlled with the {$i} switch.
See also
WriteLn, Read, Readln, Blockwrite


13.3.114 WriteLn

Declaration
Procedure WriteLn [([Var F : Text;] [V1 [; V2; ... , Vn)]];

Description
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.

Errors
If an error occurs, a run-time error is generated. This behavior can be controlled with the {$i} switch.
See also
Write, Read, Readln, Blockwrite
Example
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.



root
2000-12-20