next up previous contents index search.gif
Next: Index Up: 12. The system unit Previous: 12.1 Types, Constants and

Subsections


12.2 Functions and Procedures


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


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


12.2.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,Append, 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.


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


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


12.2.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 it that Procedural variables and class-type variables also can be passed to Assigned.

Errors
None
See also


12.2.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,seepVal,HexStr

Example

Program example81;

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


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


12.2.9 Blockwrite

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

Description
BlockWrite writes count records from buffer to the file F. If the records couldn't be written to disk, a run-time error is generated. This behavior can be controlled by the {$i} switch.

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.


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


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


12.2.12 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

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.


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


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


12.2.15 Cos

Declaration
Function Cos (X : Real) : Real;

Description
Cos returns the cosine of X, where X is an angle, in radians.
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.


12.2.16 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 comppatibility,
                  FPC is 32 bit.}
end.


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


12.2.18 Delete

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

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

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.


12.2.19 Dispose

Declaration
Procedure Dispose (P : pointer);

Description
Dispose releases the memory allocated with a call to New. The pointer P must be typed. The released memory is returned to the heap.
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.


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


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


12.2.22 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.}
  Writeln (eoln);
end.


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


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


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


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


12.2.27 Filesize

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

Description
Filepos returns the total number of records in file F. It cannot be invoked with a file of type Text. (under LINUX, this also means that it cannot be invoked on pipes.) If F is empty, 0 is returned.

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.


12.2.28 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

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 }
    S[0]:=chr(i);
    Writeln (s,'*');
    end;
end.


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

Errors
No checking on the size of X is done.
See also
Fillword, 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.


12.2.30 Flush

Declaration
Procedure Flush (Var F : Text);

Description
Flush empties the internal buffer of file F and writes the contents to disk. The file is not closed as a result of this call.
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.


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


12.2.32 Freemem

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

Description
Freemem releases the memory occupied by the pointer P, of size Count, and returns it to the heap. P should point to the memory allocated to a dynamical variable.
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.


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


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


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


12.2.36 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,seepVal,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.


12.2.37 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 retuned. 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.


12.2.38 High

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

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 when it gets.
  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.

Errors
None.
See also
High, 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));  
end.


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


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


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


12.2.42 IOresult

Declaration
Function IOresult : Word;

Description
IOresult contains the result of any input/output call, when the {$i-} compiler directive is active, and IO checking is disabled. When the flag is read, it is reset to zero. If IOresult is zero, the operation completed successfully. If non-zero, an error occurred. The following errors can occur: DOS errors :
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.


12.2.43 Length

Declaration
Function Length (S : String) : Byte;

Description
Length returns the length of the string S, which is limited to 255. If the strings S is empty, 0 is returned. Note: The length of the string S is stored in S[0].

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.


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


12.2.45 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

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.


12.2.46 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


12.2.47 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 when it gets.
  2. If the argument is an array type or an array type variable then Low returns the lowest possible value of it's index.

Errors
None.
See also
High, Ord, Pred, Succ
for an example, see High.


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


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


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


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


12.2.52 Mkdir

Declaration
Procedure Mkdir (const S : string);

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


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


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


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


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


12.2.57 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, Ord, 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.


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


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

Errors
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.
See also
Paramcount
For an example, see Paramcount.


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


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


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


12.2.63 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

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));  
end.


12.2.64 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. Remark 2: The returned address is simply the offset. If you recompile the RTL with -dDoMapping defined, then the compiler returns the following : ptr := pointer($e0000000+sel shl 4+off) under DOS, or ptr := pointer(sel shl 4+off) on other OSes.

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.


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


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


12.2.67 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 or String. If F is a typed file, then each of the variables must be of the type specified in the declaration of F. Untyped files are not allowed as an argument.
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.


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


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


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


12.2.71 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

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.


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

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

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.


12.2.73 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, Rmdir

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.


12.2.74 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(123.456));  { Prints 124  }
  Writeln (Round(-123.456)); { Prints -124 }
  Writeln (Round(12.3456));  { Prints 12   }
  Writeln (Round(-12.3456)); { Prints -12  }
end.


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


12.2.76 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 specified record size, 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.


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


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


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


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


12.2.81 SetLength

Declaration
Procedure SetLength(var S : String; Len : Longint);
Description
SetLength sets the lentgth 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.


12.2.82 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 1: Never assign a new buffer to an opened file. You can assign a new buffer immediately after a call to Rewrite, Reset or Append, but not after you read from/wrote to the file. This may cause loss of data. If you still want to assign a new buffer after read/write operations have been performed, flush the file first. This will ensure that the current buffer is emptied. Remark 2: Take care that the buffer you assign is always valid. If you assign a local variable as a buffer, then after your program exits the local program block, the buffer will no longer be valid, and stack problems may occur.

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.


12.2.83 Sin

Declaration
Function Sin (X : Real) : Real;

Description
Sin returns the sine of its argument X, where X is an angle in radians.
Errors
None.
See also
Cos, Pi, Exp

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.


12.2.84 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. Its 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.


12.2.85 Sptr

Declaration
Function Sptr : Pointer;

Description
Sptr returns the current stack pointer.

Errors
None.
See also

Example

Program Example64;

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

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


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


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


12.2.88 SSeg

Declaration
Function SSeg : Longint;

Description
SSeg returns the Stack Segment. This function is only supported for compatibolity 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.


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


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


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


12.2.92 Trunc

Declaration
Function Trunc (X : Real) : Longint;

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

Example

Program Example54;

{ Program to demonstrate the Trunc function. }

begin
  Writeln (Trunc(123.456));  { Prints 123  }
  Writeln (Trunc(-123.456)); { Prints -123 }
  Writeln (Trunc(12.3456));  { Prints 12   }
  Writeln (Trunc(-12.3456)); { Prints -12  }
end.


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


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


12.2.95 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 allow 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.


12.2.96 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 a space in front of it if it's positive, and a minus sign if it's negative. Real numbers are, by default, written in scientific notation.

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


12.2.97 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
1999-06-10