Subsections

20. The SYSUTILS unit.

sysutex

This chapter describes the sysutils unit. The sysutils unit was largely written by Gertjan Schouten, and completed by Michael Van Canneyt. It aims to be compatible to the Delphi sysutils unit, but in contrast with the latter, it is designed to work on multiple platforms. It is implemented on all supported platforms.

This chapter starts out with a definition of all types and constants that are defined, followed by an overview of functions grouped by functionality, and lastly the complete explanation of each function.

20.1 Constants and types

The following general-purpose types are defined:
tfilename = string;

tsyscharset = set of char;
tintegerset = set of 0..sizeof(integer)*8-1;
    
longrec = packed record
   lo,hi : word;
end;

wordrec = packed record   
   lo,hi : byte;
end;

TMethod = packed record
  Code, Data: Pointer;
end;
The use and meaning of these types should be clear, so no extra information will be provided here.

The following general-purpose constants are defined:

const
   SecsPerDay = 24 * 60 * 60; // Seconds and milliseconds per day
   MSecsPerDay = SecsPerDay * 1000;
   DateDelta = 693594;        // Days between 1/1/0001 and 12/31/1899
   Eoln = #10;
The following types are used frequently in date and time functions. They are the same on all platforms.
type
   TSystemTime = record
      Year, Month, Day: word;
      Hour, Minute, Second, MilliSecond: word;
   end ;

   TDateTime = double;

   TTimeStamp = record
      Time: integer;   { Number of milliseconds since midnight }
      Date: integer;   { One plus number of days since 1/1/0001 }
   end ;
The following type is used in the FindFirst,FindNext and FindClose functions. The win32 version differs from the other versions. If code is to be portable, that part shouldn't be used.
Type 
  THandle = Longint; 
  TSearchRec = Record
    Time,Size, Attr : Longint;
    Name : TFileName;
    ExcludeAttr : Longint;
    FindHandle : THandle;
    {$ifdef Win32}
    FindData : TWin32FindData;        
    {$endif}
    end;
The following constants are file-attributes that need to be matched in the findfirst call.
Const 
  faReadOnly  = $00000001; 
  faHidden    = $00000002;
  faSysFile   = $00000004;
  faVolumeId  = $00000008;
  faDirectory = $00000010;
  faArchive   = $00000020;
  faAnyFile   = $0000003f;
The following constants can be used in the FileOpen call.
Const
  fmOpenRead       = $0000;
  fmOpenWrite      = $0001;
  fmOpenReadWrite  = $0002;
The following constants can be used in the FileSeek call.
Const
  fsFromBeginning = 0;
  fsFromCurrent   = 1;
  fsFromEnd       = 2;
The following variables are used in the case translation routines.
type
   TCaseTranslationTable = array[0..255] of char;
var
   UpperCaseTable: TCaseTranslationTable;
   LowerCaseTable: TCaseTranslationTable;
The initialization code of the sysutils unit fills these tables with the appropriate values. For the win32 and go32v2 versions, this information is obtained from the operating system.

The following constants control the formatting of dates. For the Win32 version of the sysutils unit, these constants are set according to the internationalization settings of Windows by the initialization code of the unit.

Const 
   DateSeparator: char = '-';
   ShortDateFormat: string = 'd/m/y';
   LongDateFormat: string = 'dd" "mmmm" "yyyy';
   ShortMonthNames: array[1..12] of string[128] =
     ('Jan','Feb','Mar','Apr','May','Jun',
      'Jul','Aug','Sep','Oct','Nov','Dec');
   LongMonthNames: array[1..12] of string[128] =
     ('January','February','March','April',
      'May','June','July','August',
      'September','October','November','December');
   ShortDayNames: array[1..7] of string[128] =
     ('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
   LongDayNames: array[1..7] of string[128] =
     ('Sunday','Monday','Tuesday','Wednesday',
       'Thursday','Friday','Saturday');

The following constants control the formatting of times. For the Win32 version of the sysutils unit, these constants are set according to the internationalization settings of Windows by the initialization code of the unit.

Const
   ShortTimeFormat: string = 'hh:nn';
   LongTimeFormat: string = 'hh:nn:ss';
   TimeSeparator: char = ':';
   TimeAMString: string[7] = 'AM';
   TimePMString: string[7] = 'PM';

The following constants control the formatting of currencies and numbers. For the Win32 version of the sysutils unit, these constants are set according to the internationalization settings of Windows by the initialization code of the unit.

Const
  DecimalSeparator : Char = '.';
  ThousandSeparator : Char = ',';
  CurrencyDecimals : Byte = 2;
  CurrencyString : String[7] = '$';
  { Format to use when formatting currency :
    0 = $1        1 = 1$         2 = $ 1      3 = 1 $
    4 = Currency string replaces decimal indicator. 
        e.g. 1$50 
   }
  CurrencyFormat : Byte = 1;
  { Same as above, only for negative currencies:
    0 = ($1)
    1 = -$1
    2 = $-1
    3 = $1-
    4 = (1$)
    5 = -1$
    6 = 1-$
    7 = 1$-
    8 = -1 $
    9 = -$ 1
    10 = $ 1-
   }
  NegCurrFormat : Byte = 5;
The following types are used in various string functions.
type
   PString = ^String;
   TFloatFormat = (ffGeneral, ffExponent, ffFixed, ffNumber, ffCurrency);
The following constants are used in the file name handling routines. Do not use a slash of backslash character directly as a path separator; instead use the OsDirSeparator character.
Const
  DirSeparators : set of char = ['/','\'];  
{$ifdef Linux}
  OSDirSeparator = '/';
{$else}
  OsDirSeparator = '\';
{$endif}

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

20.2.1 String functions

Functions for handling strings. AnsiCompareStr Compare two strings]
AnsiCompareText Compare two strings, case insensitive
AnsiExtractQuotedStr Removes quotes from string
AnsiLastChar Get last character of string
AnsiLowerCase Convert string to all-lowercase
AnsiQuotedStr Qoutes a string
AnsiStrComp Compare strings case-sensitive
AnsiStrIComp Compare strings case-insensitive
AnsiStrLComp Compare L characters of strings case sensitive
AnsiStrLIComp Compare L characters of strings case insensitive
AnsiStrLastChar Get last character of string
AnsiStrLower Convert string to all-lowercase
AnsiStrUpper Convert string to all-uppercase
AnsiUpperCase Convert string to all-uppercase
AppendStr Append 2 strings
AssignStr Assign value of strings on heap
CompareStr Compare two strings case sensitive
CompareText Compare two strings case insensitive
DisposeStrSys Remove string from heap
IsValidIdent Is string a valid pascal identifier
LastDelimiter Last occurance of character in a string
LeftStr Get first N characters of a string
LoadStr Load string from resources
LowerCase Convert string to all-lowercase
NewStrSys Allocate new string on heap
RightStr Get last N characters of a string
StrAllocSys Allocate memory for string
StrBufSize Reserve memory for a string
StrDisposeSys Remove string from heap
StrPasSys Convert PChar to pascal string
StrPCopySys Copy pascal string
StrPLCopySys Copy N bytes of pascal string
UpperCase Convert string to all-uppercase

20.2.2 Formatting strings

Functions for formatting strings. AdjustLineBreaks Convert line breaks to line breaks for system]
FormatBuf Format a buffer
Format Format arguments in string
FmtStr Format buffer
QuotedStr Quote a string
StrFmt Format arguments in a string
StrLFmt Format maximum L characters in a string
TrimLeft Remove whitespace at the left of a string
TrimRight Remove whitespace at the right of a string
Trim Remove whitespace at both ends of a string

20.2.3 File input/output routines

Functions for reading/writing to file. FileCreate Create a file and return handle]
FileOpen Open file end return handle
FileRead Read from file
FileSeek Set file position
FileTruncate Truncate file length
FileWrite Write to file
FileClose Close file handle

20.2.4 File handling routines

Functions for file manipulation. AddDisk Add sisk to list of disk drives]
ChangeFileExt Change extension of file name
CreateDir Create a directory
DeleteFile Delete a file
DiskFreeSys Free space on disk
DiskSizeSys Total size of disk
ExpandFileName Create full file name
ExpandUNCFileName Create full UNC file name
ExtractFileDir Extract directory part of filename
ExtractFileDrive Extract drive part of filename
ExtractFileExt Extract extension part of filename
ExtractFileName Extract name part of filename
ExtractFilePath Extrct path part of filename
ExtractRelativePath Construct relative path between two files
FileAge Return file age
FileDateToDateTime Convert file date to system date
FileExists Determine whether a file exists on disk
FileGetAttr Get attributes of file
FileGetDate Get date of last file modification
FileSearch Search for file in path
FileSetAttr Get file attributes
FileSetDate Get file dates
FindFirst Start finding a file
FindNext Find next file
GetCurrentDir Return current working directory
RemoveDir Remove a directory from disk
RenameFile Rename a file on disk
SetCurrentDir Set current working directory
SetDirSeparators Set directory separator characters
FindCloseSys Stop searching a file
DoDirSeparators Replace directory separator characters

20.2.5 Date/time routines

Functions for date and time handling. DateTimeToFileDate Convert DateTime type to file date]
DateTimeToStr Construct string representation of DateTime
DateTimeToString Construct string representation of DateTime
DateTimeToSystemTime Convert DateTime to system time
DateTimeToTimeStamp Convert DateTime to timestamp
DateToStr Construct string representation of date
Date Get current date
DayOfWeek Get day of week
DecodeDate Decode DateTime to year month and day
DecodeTime Decode DateTime to hours, minutes and seconds
EncodeDate Encode year, day and month to DateTime
EncodeTime Encode hours, minutes and seconds to DateTime
FormatDateTime Return string representation of DateTime
IncMonth Add 1 to month
IsLeapYear Determine if year is leap year
MSecsToTimeStamp Convert nr of milliseconds to timestamp
Now Get current date and time
StrToDateTime Convert string to DateTime
StrToDate Convert string to date
StrToTime Convert string to time
SystemTimeToDateTime Convert system time to datetime
TimeStampToDateTime Convert time stamp to DateTime
TimeStampToMSecs Convert Timestamp to number of millicseconds
TimeToStr return string representation of Time
Time Get current tyme

20.3 Miscellaneous conversion routines

Functions for various conversions. BCDToInt Convert BCD number to integer]
CompareMem Compare two memory regions
FloatToStrF Convert float to formatted string
FloatToStr Convert float to string
FloatToText Convert float to string
GetDirs Split string in list of directories
IntToHex return hexadecimal representation of integer
IntToStr return decumal representation of integer
StrToIntDef Convert string to integer with default value
StrToInt Convert string to integer

20.4 Date and time functions


20.4.1 Date and time formatting characters

Various date and time formatting routines accept a format string. to format the date and or time. The following characters can be used to control the date and time formatting:

c
: shortdateformat + ' ' + shorttimeformat
d
: day of month
dd
: day of month (leading zero)
ddd
: day of week (abbreviation)
dddd
: day of week (full)
ddddd
: shortdateformat
dddddd
: longdateformat
m
: month
mm
: month (leading zero)
mmm
: month (abbreviation)
mmmm
: month (full)
y
: year (four digits)
yy
: year (two digits)
yyyy
: year (with century)
h
: hour
hh
: hour (leading zero)
n
: minute
nn
: minute (leading zero)
s
: second
ss
: second (leading zero)
t
: shorttimeformat
tt
: longtimeformat
am/pm
: use 12 hour clock and display am and pm accordingly
a/p
: use 12 hour clock and display a and p accordingly
/
: insert date seperator
:
: insert time seperator
"xx"
: literal text
'xx'
: literal text


20.4.2 TDateTime

Declaration
TDateTime = Double;
Description
Many functions return or require a TDateTime type, which contains a date and time in encoded form. The date and time are converted to a double as follows:


20.4.3 Date

Declaration
Function Date: TDateTime;
Description
Date returns the current date in TDateTime format. For more information about the TDateTime type, see TDateTime.
Errors
None.
See also
Time,Now, TDateTime.

Example
Program Example1;

{ This program demonstrates the Date function }

uses sysutils;

Var YY,MM,DD : Word;

Begin
 Writeln ('Date : ',Date);
 DeCodeDate (Date,YY,MM,DD);
 Writeln (format ('Date is (DD/MM/YY): %d/%d/%d ',[dd,mm,yy]));
End.


20.4.4 DateTimeToFileDate

Declaration
Function DateTimeToFileDate(DateTime : TDateTime) : Longint;
Description
DateTimeToFileDate function converts a date/time indication in TDateTime format to a filedate function, such as returned for instance by the FileAge function.
Errors
None.
See also
Time, Date, FileDateToDateTime, DateTimeToSystemTime, DateTimeToTimeStamp

Example
Program Example2;

{ This program demonstrates the DateTimeToFileDate function }

Uses sysutils;

Begin
  Writeln ('FileTime of now would be: ',DateTimeToFileDate (Now)); 
End.


20.4.5 DateTimeToStr

Declaration
Function DateTimeToStr(DateTime: TDateTime): string;
Description
DateTimeToStr returns a string representation of DateTime using the formatting specified in ShortDateTimeFormat. It corresponds to a call to FormatDateTime('c',DateTime) (see section formatchars).
Errors
None.
See also
FormatDateTime, TDateTime.

Example
Program Example3;

{ This program demonstrates the DateTimeToStr function }

Uses sysutils;

Begin
  Writeln ('Today is : ',DateTimeToStr(Now));
  Writeln ('Today is : ',FormatDateTime('c',Now));
End.


20.4.6 DateTimeToString

Declaration
Procedure DateTimeToString(var Result: string; const FormatStr: string; const DateTime: TDateTime);
Description
DateTimeToString returns in Result a string representation of DateTime using the formatting specified in FormatStr.

for a list of characters that can be used in the FormatStr formatting string, see section formatchars.

Errors
In case a wrong formatting character is found, an EConvertError is raised.
See also
FormatDateTime, section formatchars.

Example
Program Example4;

{ This program demonstrates the DateTimeToString function }

Uses sysutils;


Procedure today (Fmt : string);

Var S : AnsiString;

begin
  DateTimeToString (S,Fmt,Date);
  Writeln (S);
end;

Procedure Now (Fmt : string);

Var S : AnsiString;

begin
  DateTimeToString (S,Fmt,Time);
  Writeln (S);
end;

Begin
  Today ('"Today is "dddd dd mmmm y');
  Today ('"Today is "d mmm yy');
  Today ('"Today is "d/mmm/yy');
  Now ('''The time is ''am/pmh:n:s');  
  Now ('''The time is ''hh:nn:ssam/pm');  
  Now ('''The time is ''tt');  
End.


20.4.7 DateTimeToSystemTime

Declaration
Procedure DateTimeToSystemTime(DateTime: TDateTime; var SystemTime: TSystemTime);
Description
DateTimeToSystemTime converts a date/time pair in DateTime, with TDateTime format to a system time SystemTime.
Errors
None.
See also
DateTimeToFileDate, SystemTimeToDateTime, DateTimeToTimeStamp

Example
Program Example5;

{ This program demonstrates the DateTimeToSystemTime function }

Uses sysutils;

Var ST : TSystemTime;

Begin
  DateTimeToSystemTime(Now,ST);
  With St do
    begin
    Writeln ('Today is    ',year,'/',month,'/',Day);
    Writeln ('The time is ',Hour,':',minute,':',Second,'.',MilliSecond);
    end;
End.


20.4.8 DateTimeToTimeStamp

Declaration
Function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
Description
DateTimeToSystemTime converts a date/time pair in DateTime, with TDateTime format to a TTimeStamp format.
Errors
None.
See also
DateTimeToFileDate, SystemTimeToDateTime, DateTimeToSystemTime

Example
Program Example6;

{ This program demonstrates the DateTimeToTimeStamp function }

Uses sysutils;

Var TS : TTimeStamp;

Begin
  TS:=DateTimeToTimeStamp (Now);
  With TS do
    begin
    Writeln ('Now is ',time,' millisecond past midnight');
    Writeln ('Today is ' ,Date,' days past 1/1/0001');
    end;
End.


20.4.9 DateToStr

Declaration
Function DateToStr(Date: TDateTime): string;
Description
DateToStr converts Date to a string representation. It uses ShortDateFormat as it's formatting string. It is hence completely equivalent to a FormatDateTime('ddddd', Date).
Errors
None.
See also
TimeToStr, DateTimeToStr, FormatDateTime, StrToDate

Example
Program Example7;

{ This program demonstrates the DateToStr function }

Uses sysutils;

Begin
  Writeln(Format ('Today is: %s',[DateToStr(Date)]));
End.


20.4.10 DayOfWeek

Declaration
Function DayOfWeek(DateTime: TDateTime): integer;
Description
DayOfWeek returns the day of the week from DateTime. Sunday is counted as day 1, Saturday is counted as day 7. The result of DayOfWeek can serve as an index to the LongDayNames constant array, to retrieve the name of the day.
Errors
None.
See also
Date, DateToStr

Example
Program Example8;

{ This program demonstrates the DayOfWeek function }

Uses sysutils;

Begin
  Writeln ('Today''s day is ',LongDayNames[DayOfWeek(Date)]);
End.


20.4.11 DecodeDate

Declaration
Procedure DecodeDate(Date: TDateTime; var Year, Month, Day: word);
Description
DecodeDate decodes the Year, Month and Day stored in Date, and returns them in the Year, Month and Day variables.
Errors
None.
See also
EncodeDate, DecodeTime.

Example
Program Example9;

{ This program demonstrates the DecodeDate function }

Uses sysutils;

Var YY,MM,DD : Word;

Begin
  DecodeDate(Date,YY,MM,DD);
  Writeln (Format ('Today is %d/%d/%d',[dd,mm,yy]));
End.


20.4.12 DecodeTime

Declaration
Procedure DecodeTime(Time: TDateTime; var Hour, Minute, Second, MilliSecond: word);
Description
DecodeDate decodes the hours, minutes, second and milliseconds stored in Time, and returns them in the Hour, Minute and Second and MilliSecond variables.
Errors
None.
See also
EncodeTime, DecodeDate.

Example
Program Example10;

{ This program demonstrates the DecodeTime function }

Uses sysutils;

Var HH,MM,SS,MS: Word;

Begin
  DecodeTime(Time,HH,MM,SS,MS);
  Writeln (format('The time is %d:%d:%d.%d',[hh,mm,ss,ms]));
End.


20.4.13 EncodeDate

Declaration
Function EncodeDate(Year, Month, Day :word): TDateTime;
Description
EncodeDate encodes the Year, Month and Day variables to a date in TDateTime format. It does the opposite of the DecodeDate procedure.

The parameters must lie withing valid ranges (boundaries included):

Year
must be between 1 and 9999.
Month
must be within the range 1-12.
Day
msut be between 1 and 31.
Errors
In case one of the parameters is out of it's valid range, 0 is returned.
See also
EncodeTime, DecodeDate.

Example
Program Example11;

{ This program demonstrates the EncodeDate function }

Uses sysutils;

Var YY,MM,DD : Word;

Begin
  DecodeDate (Date,YY,MM,DD);
  WriteLn ('Today is : ',FormatDateTime ('dd mmmm yyyy',EnCodeDate(YY,Mm,Dd)));
End.


20.4.14 EncodeTime

Declaration
Function EncodeTime(Hour, Minute, Second, MilliSecond:word): TDateTime;
Description
EncodeTime encodes the Hour, Minute, Second, MilliSecond variables to a TDateTime format result. It does the opposite of the DecodeTime procedure.

The parameters must have a valid range (boundaries included):

Hour
must be between 0 and 23.
Minute,second
must both be between 0 and 59.
Millisecond
must be between 0 and 999.
Errors
In case one of the parameters is outside of it's valid range, 0 is returned.
See also
EncodeDate, DecodeTime.

Example
Program Example12;

{ This program demonstrates the EncodeTime function }

Uses sysutils;

Var Hh,MM,SS,MS : Word;

Begin
  DeCodeTime (Time,Hh,MM,SS,MS);
  Writeln ('Present Time is : ',FormatDateTime('hh:mm:ss',EnCodeTime (HH,MM,SS,MS)));
End.


20.4.15 FileDateToDateTime

Declaration
Function FileDateToDateTime(Filedate : Longint) : TDateTime;
Description
FileDateToDateTime converts the date/time encoded in filedate to a TDateTime encoded form. It can be used to convert date/time values returned by the FileAge or FindFirst/FindNext functions to TDateTime form.
Errors
None.
See also
DateTimeToFileDate

Example
Program Example13;

{ This program demonstrates the FileDateToDateTime function }

Uses sysutils;

Var 
  ThisAge : Longint;

Begin
 Write ('ex13.pp created on :');
 ThisAge:=FileAge('ex13.pp');
 Writeln (DateTimeToStr(FileDateToDateTime(ThisAge)));
End.


20.4.16 FormatDateTime

Declaration
Function FormatDateTime(FormatStr: string; DateTime: TDateTime):string;
Description
FormatDateTime formats the date and time encoded in DateTime according to the formatting given in FormatStr. The complete list of formatting characters can be found in section formatchars.
Errors
On error (such as an invalid character in the formatting string), and EConvertError exception is raised.
See also
DateTimeToStr, DateToStr, TimeToStr, StrToDateTime

Example
Program Example14;

{ This program demonstrates the FormatDateTime function }

Uses sysutils;

Var ThisMoment : TDateTime;

Begin
  ThisMoment:=Now;
  Writeln ('Now : ',FormatDateTime('hh:mm',ThisMoment));
  Writeln ('Now : ',FormatDateTime('DD MM YYYY',ThisMoment));
  Writeln ('Now : ',FormatDateTime('c',ThisMoment));
End.


20.4.17 IncMonth

Declaration
Function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer): TDateTime;
Description
IncMonth increases the month number in DateTime with NumberOfMonths. It wraps the result as to get a month between 1 and 12, and updates the year accordingly. NumberOfMonths can be negative, and can be larger than 12 (in absolute value).
Errors
None.
See also
Date, Time, Now

Example
Program Example15;

{ This program demonstrates the IncMonth function }

Uses sysutils;

Var ThisDay : TDateTime;

Begin
  ThisDay:=Date;
  Writeln ('ThisDay : ',DateToStr(ThisDay));
  Writeln ('6 months ago :',DateToStr(IncMonth(ThisDay,-6)));
  Writeln ('6 months from now :' ,DateToStr(IncMonth(ThisDay,6)));
  Writeln ('12 months ago :',DateToStr(IncMonth(ThisDay,-12)));
  Writeln ('12 months from now :' ,DateToStr(IncMonth(ThisDay,12)));
  Writeln ('18 months ago :',DateToStr(IncMonth(ThisDay,-18)));
  Writeln ('18 months from now :' ,DateToStr(IncMonth(ThisDay,18)));
End.


20.4.18 IsLeapYear

Declaration
Function IsLeapYear(Year: Word): boolean;
Description
IsLeapYear returns True if Year is a leap year, False otherwise.
Errors
None.
See also
IncMonth, Date

Example
Program Example16;

{ This program demonstrates the IsLeapYear function }

Uses sysutils;

Var YY,MM,dd : Word;

Procedure TestYear (Y : Word);

begin
  Writeln (Y,' is leap year : ',IsLeapYear(Y));
end;

Begin
  DeCodeDate(Date,YY,mm,dd);
  TestYear(yy);
  TestYear(2000);
  TestYear(1900);
  TestYear(1600);
  TestYear(1992);
  TestYear(1995);
End.


20.4.19 MSecsToTimeStamp

Declaration
Function MSecsToTimeStamp(MSecs: Comp): TTimeStamp;
Description
MSecsTiTimeStamp converts the given number of milliseconds to a TTimeStamp date/time notation.

Use TTimeStamp variables if you need to keep very precise track of time.

Errors
None.
See also
TimeStampToMSecs, DateTimeToTimeStamp,

Example
Program Example17;

{ This program demonstrates the MSecsToTimeStamp function }

Uses sysutils;

Var MS : Comp;
    TS : TTimeStamp;
    DT : TDateTime;
Begin
  TS:=DateTimeToTimeStamp(Now);
  Writeln ('Now in days since 1/1/0001      : ',TS.Date);
  Writeln ('Now in millisecs since midnight : ',TS.Time);
  MS:=TimeStampToMSecs(TS);
  Writeln ('Now in millisecs since 1/1/0001 : ',MS);
  MS:=MS-1000*3600*2;
  TS:=MSecsToTimeStamp(MS);
  DT:=TimeStampToDateTime(TS);
  Writeln ('Now minus 1 day : ',DateTimeToStr(DT));
End.


20.4.20 Now

Declaration
Function Now: TDateTime;
Description
Now returns the current date and time. It is equivalent to Date+Time.
Errors
None.
See also
Date, Time

Example
Program Example18;

{ This program demonstrates the Now function }

Uses sysutils;

Begin
  Writeln ('Now : ',DateTimeToStr(Now));
End.


20.4.21 StrToDate

Declaration
Function StrToDate(const S: string): TDateTime;
Description
StrToDate converts the string S to a TDateTime date value. The Date must consist of 1 to three digits, separated by the DateSeparator character. If two numbers are given, they are supposed to form the day and month of the current year. If only one number is given, it is supposed to represent the day of the current month. (This is not supported in Delphi)

The order of the digits (y/m/d, m/d/y, d/m/y) is determined from the ShortDateFormat variable.

Errors
On error (e.g. an invalid date or invalid character), an EConvertError exception is raised.
See also
StrToTime, DateToStrn TimeToStr.

Example
Program Example19;

{ This program demonstrates the StrToDate function }

Uses sysutils;

Procedure TestStr (S : String);

begin
  Writeln (S,' : ',DateToStr(StrToDate(S)));
end;

Begin
  
  Writeln ('ShortDateFormat ',ShortDateFormat);
  TestStr(DateTimeToStr(Date));
  TestStr('05/05/1999');
  TestStr('5/5');
  TestStr('5');
End.


20.4.22 StrToDateTime

Declaration
Function StrToDateTime(const S: string): TDateTime;
Description
StrToDateTime converts the string S to a TDateTime date and time value. The Date must consist of 1 to three digits, separated by the DateSeparator character. If two numbers are given, they are supposed to form the day and month of the current year. If only one number is given, it is supposed to represent the day of the current month. (This is not supported in Delphi)

The order of the digits (y/m/d, m/d/y, d/m/y) is determined from the ShortDateFormat variable.

Errors
On error (e.g. an invalid date or invalid character), an EConvertError exception is raised.
See also
StrToDate, StrToTime, DateTimeToStr

Example
Program Example20;

{ This program demonstrates the StrToDateTime function }

Uses sysutils;

Procedure TestStr (S : String);

begin
  Writeln (S,' : ',DateTimeToStr(StrToDateTime(S)));
end;

Begin
  
  Writeln ('ShortDateFormat ',ShortDateFormat);
  TestStr(DateTimeToStr(Now));
  TestStr('05-05-1999 15:50');
  TestStr('5-5 13:30');
  TestStr('5 1:30PM');
End.


20.4.23 StrToTime

Declaration
Function StrToTime(const S: string): TDateTime;
Description
StrToTime converts the string S to a TDateTime time value. The time must consist of 1 to 4 digits, separated by the TimeSeparator character. If two numbers are given, they are supposed to form the hour and minutes.
Errors
On error (e.g. an invalid date or invalid character), an EConvertError exception is raised.
See also
StrToDate, StrToDateTime, TimeToStr

Example
Program Example21;

{ This program demonstrates the StrToTime function }

Uses sysutils;

Procedure TestStr (S : String);

begin
  Writeln (S,' : ',TimeToStr(StrToTime(S)));
end;

Begin
  teststr (TimeToStr(Time));
  teststr ('12:00');
  teststr ('15:30');
  teststr ('3:30PM');
End.


20.4.24 SystemTimeToDateTime

Declaration
Function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
Description
SystemTimeToDateTime converts a TSystemTime record to a TDateTime style date/time indication.
Errors
None.
See also
DateTimeToSystemTime

Example
Program Example22;

{ This program demonstrates the SystemTimeToDateTime function }

Uses sysutils;

Var ST : TSystemTime;

Begin
  DateTimeToSystemTime(Now,ST);
  With St do
    begin
    Writeln ('Today is    ',year,'/',month,'/',Day);
    Writeln ('The time is ',Hour,':',minute,':',Second,'.',MilliSecond);
    end;
  Writeln ('Converted : ',DateTimeToStr(SystemTimeToDateTime(ST)));
End.


20.4.25 Time

Declaration
Function Time: TDateTime;
Description
Time returns the current time in TDateTime format. The date part of the TDateTimeValue is set to zero.
Errors
None.
See also
Now, Date

Example
Program Example23;

{ This program demonstrates the Time function }

Uses sysutils;

Begin
  Writeln ('The time is : ',TimeToStr(Time));
End.


20.4.26 TimeStampToDateTime

Declaration
Function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
Description
TimeStampToDateTime converts TimeStamp to a TDateTime format variable. It is the inverse operation of DateTimeToTimeStamp.
Errors
None.
See also
DateTimeToTimeStamp, TimeStampToMSecs

Example
Program Example24;

{ This program demonstrates the TimeStampToDateTime function }

Uses sysutils;

Var TS : TTimeStamp;
    DT : TDateTime;
    
Begin
  TS:=DateTimeToTimeStamp (Now);
  With TS do
    begin
    Writeln ('Now is ',time,' millisecond past midnight');
    Writeln ('Today is ' ,Date,' days past 1/1/0001');
    end;
  DT:=TimeStampToDateTime(TS);
  Writeln ('Together this is : ',DateTimeToStr(DT));
End.


20.4.27 TimeStampToMSecs

Declaration
Function TimeStampToMSecs(const TimeStamp: TTimeStamp): comp;
Description
TimeStampToMSecs converts TimeStamp to the number of seconds since 1/1/0001.

Use TTimeStamp variables if you need to keep very precise track of time.

Errors
None.
See also
MSecsToTimeStamp, TimeStampToDateTime

For an example, see MSecsToTimeStamp.


20.4.28 TimeToStr

Declaration
Function TimeToStr(Time: TDateTime): string;
Description
TimeToStr converts the time in Time to a string. It uses the ShortTimeFormat variable to see what formatting needs to be applied. It is therefor entirely equivalent to a FormatDateTime('t',Time) call.
Errors
None.
See also

Example
Program Example25;

{ This program demonstrates the TimeToStr function }

Uses sysutils;

Begin
  Writeln ('The current time is : ',TimeToStr(Time));
End.

20.5 Disk functions


20.5.1 AddDisk (Linux only)

Declaration
Function AddDisk (Const PAth : String) : Longint;
Description
On Linux both the DiskFree and DiskSize functions need a file on the specified drive, since is required for the statfs system call.

These filenames are set in drivestr[0..26], and the first 4 have been preset to :

Disk 0
'.' default drive - hence current directory is used.
Disk 1
'/fd0/.' floppy drive 1.
Disk 2
'/fd1/.' floppy drive 2.
Disk 3
'/' C: equivalent of DOS is the root partition.
Drives 4..26 can be set by your own applications with the AddDisk call.

The AddDisk call adds Path to the names of drive files, and returns the number of the disk that corresponds to this drive. If you add more than 21 drives, the count is wrapped to 4.

Errors
None.
See also
DiskFree, DiskSize


20.5.2 CreateDir

Declaration
Function CreateDir(Const NewDir : String) : Boolean;
Description
CreateDir creates a new directory with name NewDir. If the directory doesn't contain an absolute path, then the directory is created below the current working directory.

The function returns True if the directory was successfully created, False otherwise.

Errors
In case of an error, the function returns False.
See also
RemoveDir

Example
Program Example26;

{ This program demonstrates the CreateDir and RemoveDir functions }
{ Run this program twice in the same directory }

Uses sysutils;

Begin
  If Not FileExists('NewDir') then
    If Not CreateDir ('NewDir') Then
      Writeln ('Failed to create directory !')
    else
      Writeln ('Created "NewDir" directory')
  Else
    If Not RemoveDir ('NewDir') Then
      Writeln ('Failed to remove directory !')
    else
      Writeln ('Removed "NewDir" directory');
End.


20.5.3 DiskFree

Declaration
Function DiskFree(Drive : Byte) : Longint;
Description
DiskFree returns the free space (in bytes) on disk Drive. Drive is the number of the disk drive:
0
for the current drive.
1
for the first floppy drive.
2
for the second floppy drive.
3
for the first hard-disk parttion.
4-26
for all other drives and partitions.

Remark Under LINUX, and Unix in general, the concept of disk is different than the DOS one, since the filesystem is seen as one big directory tree. For this reason, the DiskFree and DiskSize functions must be mimicked using filenames that reside on the partitions. For more information, see AddDisk

Errors
On error, -1 is returned.
See also
DiskSize, AddDisk

Example
Program Example27;

{ This program demonstrates the DiskFree function }

Uses sysutils;

Begin
  Write ('Size of current disk       : ',DiskSize(0));
  Writeln (' (= ',DiskSize(0) div 1024,'k)');
  Write ('Free space of current disk : ',Diskfree(0));
  Writeln (' (= ',Diskfree(0) div 1024,'k)');
End.


20.5.4 DiskSize

Declaration
Function DiskSize(Drive : Byte) : Longint;
Description
DiskSize returns the size (in bytes) of disk Drive. Drive is the number of the disk drive:
0
for the current drive.
1
for the first floppy drive.
2
for the second floppy drive.
3
for the first hard-disk parttion.
4-26
for all other drives and partitions.

Remark Under LINUX, and Unix in general, the concept of disk is different than the DOS one, since the filesystem is seen as one big directory tree. For this reason, the DiskFree and DiskSize functions must be mimicked using filenames that reside on the partitions. For more information, see AddDisk

Errors
On error, -1 is returned.
See also
DiskFree, AddDisk

For an example, see DiskFree.


20.5.5 GetCurrentDir

Declaration
Function GetCurrentDir : String;
Description
GetCurrentDir returns the current working directory.
Errors
None.
See also
SetCurrentDir, DiskFree, DiskSize

Example
Program Example28;

{ This program demonstrates the GetCurrentDir function }

Uses sysutils;

Begin
  Writeln ('Current Directory is : ',GetCurrentDir); 
End.


20.5.6 RemoveDir

Declaration
Function RemoveDir(Const Dir : String) : Boolean;
Description
RemoveDir removes directory Dir from the disk. If the directory is not absolue, it is appended to the current working directory.
Errors
In case of error (e.g. the directory isn't empty) the function returns False. If successful, True is returned.
See also

For an example, see CreateDir.


20.5.7 SetCurrentDir

Declaration
Function SetCurrentDir(Const NewDir : String) : Boolean;
Description
SetCurrentDir sets the current working directory of your program to NewDir. It returns True if the function was successfull, False otherwise.
Errors
In case of error, False is returned.
See also
GetCurrentDir

Example
Program Example29;

{ This program demonstrates the SetCurrentDir function }

Uses sysutils;

Begin
  If SetCurrentDir ('..') Then
    Writeln ('Now in directory ',GetCurrentDir)
  else 
    Writeln ('Change directory to .. failed.');
End.

20.6 File handling functions


20.6.1 ChangeFileExt

Declaration
Function ChangeFileExt(const FileName, Extension: string): string;
Description
ChangeFileExt changes the file extension in FileName to Extension. The extension Extension includes the starting . (dot). The previous extension of FileName are all characters after the last ., the . character included.

If FileName doesn't have an extension, Extension is just appended.

Errors
None.
See also
ExtractFileName, ExtractFilePath, ExpandFileName


20.6.2 DeleteFile

Declaration
Function DeleteFile(Const FileName : String) : Boolean;
Description
DeleteFile deletes file FileName from disk. The function returns True if the file was successfully removed, False otherwise.
Errors
On error, False is returned.
See also
FileCreate, FileExists

Example
Program Example31;

{ This program demonstrates the DeleteFile function }

Uses sysutils;

Var
  Line : String;
  F,I : Longint;

Begin
  F:=FileCreate('test.txt');
  Line:='Some string line.'#10;
  For I:=1 to 10 do
    FileWrite (F,Line[1],Length(Line));
  FileClose(F);  
  DeleteFile('test.txt');
End.


20.6.3 DoDirSeparators

Declaration
Procedure DoDirSeparators(Var FileName : String);
Description
This function replaces all directory separators 'ánd '/' to the directory separator character for the current system.
Errors
None.
See also
ExtractFileName, ExtractFilePath

Example
Program Example32;

{ This program demonstrates the DoDirSeparators function }
{$H+}

Uses sysutils;

Procedure Testit (F : String);

begin
  Writeln ('Before : ',F);
  DoDirSeparators (F);
  Writeln ('After  : ',F);
end;

Begin
  Testit (GetCurrentDir);
  Testit ('c:\pp\bin\win32');
  Testit ('/usr/lib/fpc');
  Testit ('\usr\lib\fpc');
End.


20.6.4 ExpandFileName

Declaration
Function ExpandFileName(Const FileName : string): String;
Description
ExpandFileName expands the filename to an absolute filename. It changes all directory separator characters to the one appropriate for the system first.
Errors
None.
See also
ExtractFileName, ExtractFilePath, ExtractFileDir, ExtractFileDrive, ExtractFileExt, ExtractRelativePath

Example
Program Example33;

{ This program demonstrates the ExpandFileName function }

Uses sysutils;

Procedure Testit (F : String);

begin
  Writeln (F,' expands to : ',ExpandFileName(F));
end;

Begin
  Testit('ex33.pp');
  Testit(ParamStr(0));
  Testit('/pp/bin/win32/ppc386');
  Testit('\pp\bin\win32\ppc386');
  Testit('.');
End.


20.6.5 ExpandUNCFileName

Declaration
Function ExpandUNCFileName(Const FileName : string): String;
Description
ExpandUNCFileName runs ExpandFileName on FileName and then attempts to replace the driveletter by the name of a shared disk.
Errors
See also
ExtractFileName, ExtractFilePath, ExtractFileDir, ExtractFileDrive, ExtractFileExt, ExtractRelativePath


20.6.6 ExtractFileDir

Declaration
Function ExtractFileDir(Const FileName : string): string;
Description
ExtractFileDir returns only the directory part of FileName, not including a driveletter. The directory name has NO ending directory separator, in difference with ExtractFilePath.
Errors
None.
See also
ExtractFileName, ExtractFilePath, ExtractFileDir, ExtractFileDrive, ExtractFileExt, ExtractRelativePath

Example
Program Example34;

{ This program demonstrates the ExtractFileName function }
{$H+}
Uses sysutils;

Procedure Testit(F : String);

begin
 Writeln ('FileName      : ',F);
 Writeln ('Has Name      : ',ExtractFileName(F));
 Writeln ('Has Path      : ',ExtractFilePath(F));
 Writeln ('Has Extension : ',ExtractFileExt(F));
 Writeln ('Has Directory : ',ExtractFileDir(F));
 Writeln ('Has Drive     : ',ExtractFileDrive(F));
end;

Begin
  Testit (Paramstr(0));
  Testit ('/usr/local/bin/mysqld');
  Testit ('c:\pp\bin\win32\ppc386.exe');
  Testit ('/pp/bin/win32/ppc386.exe');
End.


20.6.7 ExtractFileDrive

Declaration
Function ExtractFileDrive(const FileName: string): string;
Description
Extract
Errors
See also
ExtractFileName, ExtractFilePath, ExtractFileDir, ExtractFileDrive, ExtractFileExt, ExtractRelativePath

For an example, see ExtractFileDir.


20.6.8 ExtractFileExt

Declaration
Function ExtractFileExt(const FileName: string): string;
Description
ExtractFileExt returns the extension (including the .(dot) character) of FileName.
Errors
None.
See also
ExtractFileName, ExtractFilePath, ExtractFileDir, ExtractFileDrive, ExtractFileExt, ExtractRelativePath

For an example, see ExtractFileDir.


20.6.9 ExtractFileName

Declaration
Function ExtractFileName(const FileName: string): string;
Description
ExtractFileName returns the filename part from FileName. The filename consists of all characters after the last directory separator character ('/' or ') or drive letter.

The full filename can always be reconstucted by concatenating the result of ExtractFilePath and ExtractFileName.

Errors
None.
See also
ExtractFileName, ExtractFilePath, ExtractFileDir, ExtractFileDrive, ExtractFileExt,ExtractRelativePath

For an example, see ExtractFileDir.


20.6.10 ExtractFilePath

Declaration
Function ExtractFilePath(const FileName: string): string;
Description
ExtractFilePath returns the path part (including driveletter) from FileName. The path consists of all characters before the last directory separator character ('/' or '), including the directory separator itself. In case there is only a drive letter, that will be returned.

The full filename can always be reconstucted by concatenating the result of ExtractFilePath and ExtractFileName.

Errors
None.
See also
ExtractFileName, ExtractFilePath, ExtractFileDir, ExtractFileDrive, ExtractFileExt, ExtractRelativePath

For an example, see ExtractFileDir.


20.6.11 ExtractRelativePath

Declaration
Function ExtractRelativePath(Const BaseName,DestNAme : String): String;
Description
ExtractRelativePath constructs a relative path to go from BaseName to DestName. If DestName is on another drive (Not on Linux) then the whole Destname is returned.

Note: This function does not exist in the Delphi unit.

Errors
None.
See also
ExtractFileName, ExtractFilePath, ExtractFileDir, ExtractFileDrive, ExtractFileExt,

Example
Program Example35;

{ This program demonstrates the ExtractRelativePath function }

Uses sysutils;

Procedure Testit (FromDir,ToDir : String);

begin
  Write ('From "',FromDir,'" to "',ToDir,'" via "');
  Writeln (ExtractRelativePath(FromDir,ToDir),'"');
end;

Begin
 Testit ('/pp/src/compiler','/pp/bin/win32/ppc386');
 Testit ('/pp/bin/win32/ppc386','/pp/src/compiler');
 Testit ('e:/pp/bin/win32/ppc386','d:/pp/src/compiler');
 Testit ('e:\pp\bin\win32\ppc386','d:\pp\src\compiler');
End.


20.6.12 FileAge

Declaration
Function FileAge(Const FileName : String): Longint;
Description
FileAge returns the last modification time of file FileName. The FileDate format can be transformed to TDateTime format with the FileDateToDateTime function.
Errors
In case of errors, -1 is returned.
See also
FileDateToDateTime, FileExists, FileGetAttr

Example
Program Example36;

{ This program demonstrates the FileAge function }

Uses sysutils;

Var S : TDateTime;
    fa : Longint;
Begin
  fa:=FileAge('ex36.pp');
  If Fa<>-1 then
    begin
    S:=FileDateTodateTime(fa);
    Writeln ('I''m from ',DateTimeToStr(S))
    end;
End.


20.6.13 FileClose

Declaration
Procedure FileClose(Handle : Longint);
Description
FileClose closes the file handle Handle. After this call, attempting to read or write from the handle will result in an error.
Errors
None.
See also
FileCreate, FileWrite, FileOpen, FileRead, FileTruncate, FileSeek

For an example, see FileCreate


20.6.14 FileCreate

Declaration
Function FileCreate(Const FileName : String) : Longint;
Description
FileCreate creates a new file with name FileName on the disk and returns a file handle which can be used to read or write from the file with the FileRead and FileWrite functions.

If a file with name FileName already existed on the disk, it is overwritten.

Errors
If an error occurs (e.g. disk full or non-existent path), the function returns -1.
See also
FileClose, FileWrite, FileOpen, FileRead, FileTruncate, FileSeek

Example
Program Example37;

{ This program demonstrates the FileCreate function }

Uses sysutils;

Var I,J,F : Longint;

Begin
  F:=FileCreate ('test.dat');
  If F=-1 then 
    Halt(1);
  For I:=0 to 100 do
    FileWrite(F,I,SizeOf(i));
  FileClose(f);
  F:=FileOpen ('test.dat',fmOpenRead);
  For I:=0 to 100 do
    begin
    FileRead (F,J,SizeOF(J));
    If J<>I then
      Writeln ('Mismatch at file position ',I)
    end;
  FileSeek(F,0,fsFromBeginning);
  Randomize;
  Repeat
    FileSeek(F,Random(100)*4,fsFromBeginning);
    FileRead (F,J,SizeOf(J));
    Writeln ('Random read : ',j);
  Until J>80;
  FileClose(F);
  F:=FileOpen('test.dat',fmOpenWrite);
  I:=50*SizeOf(Longint);
  If FileTruncate(F,I) then
    Writeln('SuccessFully truncated file to ',I,' bytes.');
  FileClose(F);
End.


20.6.15 FileExists

Declaration
Function FileExists(Const FileName : String) : Boolean;
Description
FileExists returns True if a file with name FileName exists on the disk, False otherwise.
Errors
None.
See also
FileAge, FileGetAttr, FileSetAttr

Example
Program Example38;

{ This program demonstrates the FileExists function }

Uses sysutils;

Begin
  If FileExists(ParamStr(0)) Then
    Writeln ('All is well, I seem to exist.');
End.


20.6.16 FileGetAttr

Declaration
Function FileGetAttr(Const FileName : String) : Longint;
Description
FileGetAttr returns the attribute settings of file FileName. The attribute is a OR-ed combination of the following constants:
faReadOnly
The file is read-only.
faHidden
The file is hidden. (On LINUX, this means that the filename starts with a dot)
faSysFile
The file is a system file (On LINUX, this means that the file is a character, block or FIFO file).
faVolumeId
Volume Label. Not possible under LINUX.
faDirectory
File is a directory.
faArchive
file is an archive. Not possible on LINUX.
Errors
In case of error, -1 is returned.
See also
FileSetAttr, FileAge, FileGetDate.

Example
Program Example40;

{ This program demonstrates the FileGetAttr function }

Uses sysutils;

Procedure Testit (Name : String);

Var F : Longint;

Begin
  F:=FileGetAttr(Name);
  If F<>-1 then
    begin
    Writeln ('Testing : ',Name);
    If (F and faReadOnly)<>0 then 
      Writeln ('File is ReadOnly');
    If (F and faHidden)<>0 then 
      Writeln ('File is hidden');
    If (F and faSysFile)<>0 then 
      Writeln ('File is a system file');
    If (F and faVolumeID)<>0 then
      Writeln ('File is a disk label');
    If (F and faArchive)<>0 then 
      Writeln ('File is artchive file');
    If (F and faDirectory)<>0 then
      Writeln ('File is a directory');
    end
  else
   Writeln ('Error reading attribites of ',Name);
end;

begin
  testit ('ex40.pp');
  testit (ParamStr(0));
  testit ('.');
  testit ('/');
End.


20.6.17 FileGetDate

Declaration
Function FileGetDate(Handle : Longint) : Longint;
Description
FileGetdate returns the filetime of the opened file with filehandle Handle. It is the same as FileAge, with this difference that FileAge only needs the file name, while FilegetDate needs an open file handle.
Errors
On error, -1 is returned.
See also
FileAge

Example
Program Example39;

{ This program demonstrates the FileGetDate function }

Uses sysutils;

Var F,D : Longint;

Begin
  F:=FileCreate('test.dat');
  D:=FileGetDate(D);
  Writeln ('File crerated on ',DateTimeToStr(FileDateToDateTime(D)));
  FileClose(F);
  DeleteFile('test.dat');
End.


20.6.18 FileOpen

Declaration
Function FileOpen(Const FileName : string; Mode : Integer) : Longint;
Description
FileOpen opens a file with name FileName with mode Mode. Mode can be one of the following constants:
fmOpenRead
The file is opened for reading.
fmOpenWrite
The file is opened for writing.
fmOpenReadWrite
The file is opened for reading and writing.
If the file has been successfully opened, it can be read from or written to (depending on the Mode parameter) with the FileRead and FileWrite functions.

Remark that you cannot open a file if it doesn't exist yet, i.e. it will not be created for you. If you want tp create a new file, or overwrite an old one, use the FileCreate function.

Errors
On Error, -1 is returned.
See also
FileClose, FileWrite, FileCreate, FileRead, FileTruncate, FileSeek

For an example, see FileRead


20.6.19 FileRead

Declaration
Function FileRead(Handle : Longint; Var Buffer; Count : longint) : Longint;
Description
FileRead reads Count bytes from file-handle Handle and stores them into Buffer. Buffer must be at least Count bytes long. No checking on this is performed, so be careful not to overwrite any memory. Handle must be the result of a FileOpen call.
Errors
On error, -1 is returned.
See also
FileClose, FileWrite, FileCreate, FileOpen, FileTruncate, FileSeek

For an example, see FileOpen


20.6.20 FileSearch

Declaration
Function FileSearch(Const Name, DirList : String) : String;
Description
FileSearch looks for the file Name in DirList, where dirlist is a list of directories, separated by semicolons or colons. It returns the full filename of the first match found.
Errors
On error, an empty string is returned.
See also
ExpandFileName, FindFirst

Example
Program Example41;

{ Program to demonstrate the FileSearch function. }

Uses Sysutils;

Const
{$ifdef linux}
  FN = 'find';
  P = '.:/bin:/usr/bin';  
{$else}
  FN = 'find.exe';
  P = 'c:\dos;c:\windows;c:\windows\system;c:\windows\system32';
{$endif}

begin
  Writeln ('find is in : ',FileSearch (FN,P));
end.


20.6.21 FileSeek

Declaration
Function FileSeek(Handle,Offset,Origin : Longint) : Longint;
Description
FileSeek sets the file pointer on position Offset, starting from Origin. Origin can be one of the following values:
fsFromBeginning
Offset is relative to the first byte of the file. This position is zero-based. i.e. the first byte is at offset 0.
fsFromCurrent
Offset is relative to the current position.
fsFromEnd
Offset is relative to the end of the file. This means that Offset can only be zero or negative in this case.
If successfull, the function returns the new file position, relative to the beginning of the file.

Remark: The abovementioned constants do not exist in Delphi.

Errors
On error, -1 is returned.
See also
FileClose, FileWrite, FileCreate, FileOpen FileRead, FileTruncate

Example
Program Example42;

{ This program demonstrates the FileSetAttr function }

Uses sysutils;

Begin
  If FileSetAttr ('ex40.pp',faReadOnly or faHidden)=0 then
    Writeln ('Successfully made file hidden and read-only.')
  else
    Writeln ('Coulnd''t make file hidden and read-only.');
End.

For an example, see FileCreate


20.6.22 FileSetAttr (Not on Linux)

Declaration
Function FileSetAttr(Const Filename : String; Attr: longint) : Longint;
Description
FileSetAttr sets the attributes of FileName to Attr. If the function was successful, 0 is returned, -1 otherwise.

Attr can be set to an OR-ed combination of the pre-defined faXXX constants.

Errors
On error, -1 is returned (always on linux).
See also
FileGetAttr, FileGetDate, FileSetDate.


20.6.23 FileSetDate (Not on Linux)

Declaration
Function FileSetDate(Handle,Age : Longint) : Longint;
Description
FileSetDate sets the file date of the file with handle Handle to Age, where Age is a DOS date-and-time stamp value.

The function returns zero of successfull.

Errors
On Linux, -1 is always returned, since this is impossible to implement. On Windows and DOS, a negative error code is returned.
See also


20.6.24 FileTruncate

Declaration
Function FileTruncate(Handle,Size: Longint) : boolean;
Description
FileTruncate truncates the file with handle Handle to Size bytes. The file must have been opened for writing prior to this call. The function returns True is successful, False otherwise.
Errors
On error, the function returns False.
See also
FileClose, FileWrite, FileCreate, FileOpen FileRead, FileSeek

For an example, see FileCreate.


20.6.25 FileWrite

Declaration
Function FileWrite(Handle : Longint; Var Buffer; Count : Longint) : Longint;
Description
FileWrite writes Count bytes from Buffer to the file with handle Handle. Prior to this call, the file must have been opened for writing. Buffer must be at least Count bytes large, or a memory access error may occur.

The function returns the number of bytes written, or -1 in case of an error.

Errors
In case of error, -1 is returned.
See also
FileClose, FileCreate, FileOpen FileRead, FileTruncate, FileSeek

For an example, see FileCreate.


20.6.26 FindClose

Declaration
Procedure FindClose(Var F : TSearchrec);
Description
FindClose ends a series of FindFirst/FindNext calls, and frees any memory used by these calls. It is absolutely necessary to do this call, or huge memory losses may occur.
Errors
None.
See also
FindFirst, FindNext.

For an example, see FindFirst.


20.6.27 FindFirst

Declaration
Function FindFirst(Const Path : String; Attr : Longint; Var Rslt : TSearchRec) : Longint;
Description
FindFirst looks for files that match the name (possibly with wildcards) in Path and attributes Attr. It then fills up the Rslt record with data gathered about the file. It returns 0 if a file matching the specified criteria is found, a nonzero value (-1 on linux) otherwise.

The Rslt record can be fed to subsequent calls to FindNext, in order to find other files matching the specifications.

remark: A FindFirst call must always be followed by a FindClose call with the same Rslt record. Failure to do so will result in memory loss.

Errors
On error the function returns -1 on linux, a nonzero error code on Windows.
See also
FindCloseFindCloseSys, FindNext.

Example
Program Example43;

{ This program demonstrates the FindFirst function }

Uses sysutils;

Var Info : TSearchRec;
    Count : Longint;

Begin
  Count:=0;
  If FindFirst ('*.pp',faAnyFile,Info)=0 then
    begin
    Repeat
      Inc(Count);
      With Info do 
        Writeln (Name:40,Size:15);
    Until FindNext(info)<>0;
    end;
  FindClose(Info);
  Writeln ('Finished search. Found ',Count,' matches');
  
End.


20.6.28 FindNext

Declaration
Function FindNext(Var Rslt : TSearchRec) : Longint;
Description
FindNext finds a next occurrence of a search sequence initiated by FindFirst. If another record matching the criteria in Rslt is found, 0 is returned, a nonzero constant is returned otherwise.

remark: The last FindNext call must always be followed by a FindClose call with the same Rslt record. Failure to do so will result in memory loss.

Errors
On error (no more file is found), a nonzero constant is returned.
See also
FindFirst, FindClose

For an example, see FindFirst


20.6.29 GetDirs

Declaration
Function GetDirs(Var DirName : String; Var Dirs : Array of pchar) : Longint;
Description
GetDirs splits DirName in a null-byte separated list of directory names, Dirs is an array of PChars, pointing to these directory names. The function returns the number of directories found, or -1 if none were found. DirName must contain only OSDirSeparator as Directory separator chars.
Errors
None.
See also
ExtractRelativePath

Example
Program Example45;

{ This program demonstrates the GetDirs function }
{$H+}

Uses sysutils;

Var Dirs : Array[0..127] of pchar;
    I,Count : longint;
    Dir,NewDir : String;
 
Begin
  Dir:=GetCurrentDir;
  Writeln ('Dir : ',Dir);
  NewDir:='';
  count:=GetDirs(Dir,Dirs);
  For I:=0 to Count do
    begin
    NewDir:=NewDir+'/'+StrPas(Dirs[I]);
    Writeln (NewDir);
    end;
End.


20.6.30 RenameFile

Declaration
Function RenameFile(Const OldName, NewName : String) : Boolean;
Description
RenameFile renames a file from OldName to NewName. The function returns True if successful, False otherwise.

Remark: you cannot rename across disks or partitions.

Errors
On Error, False is returned.
See also
DeleteFile

Example
Program Example44;

{ This program demonstrates the RenameFile function }

Uses sysutils;

Var F : Longint;
    S : String;
    
Begin
  S:='Some short file.';
  F:=FileCreate ('test.dap');
  FileWrite(F,S[1],Length(S));
  FileClose(F);
  If RenameFile ('test.dap','test.dat') then
    Writeln ('Successfully renamed files.');
End.


20.6.31 SetDirSeparators

Declaration
Function SetDirSeparators(Const FileName : String) : String;
Description
SetDirSeparators returns FileName with all possible DirSeparators replaced by OSDirSeparator.
Errors
None.
See also
ExpandFileName, ExtractFilePath, ExtractFileDir

Example
Program Example47;

{ This program demonstrates the SetDirSeparators function }

Uses sysutils;

Begin
  Writeln (SetDirSeparators('/pp\bin/win32\ppc386'));
End.

20.7 PChar functions

20.7.1 Introduction

Most PChar functions are the same as their counterparts in the STRINGS unit. The following functions are the same :

  1. StrCat : Concatenates two PChar strings.
  2. StrComp : Compares two PChar strings.
  3. StrCopy : Copies a PChar string.
  4. StrECopy : Copies a PChar string and returns a pointer to the terminating null byte.
  5. StrEnd : Returns a pointer to the terminating null byte.
  6. StrIComp : Case insensitive compare of 2 PChar strings.
  7. StrLCat : Appends at most L characters from one PChar to another PChar.
  8. StrLComp : Case sensitive compare of at most L characters of 2 PChar strings.
  9. StrLCopy : Copies at most L characters from one PChar to another.
  10. StrLen : Returns the length (exclusive terminating null byte) of a PChar string.
  11. StrLIComp : Case insensitive compare of at most L characters of 2 PChar strings.
  12. StrLower : Converts a PChar to all lowercase letters.
  13. StrMove : Moves one PChar to another.
  14. StrNew : Makes a copy of a PChar on the heap, and returns a pointer to this copy.
  15. StrPos : Returns the position of one PChar string in another?
  16. StrRScan : returns a pointer to the last occurrence of on PChar string in another one.
  17. StrScan : returns a pointer to the first occurrence of on PChar string in another one.
  18. StrUpper : Converts a PChar to all uppercase letters.
The subsequent functions are different from their counterparts in STRINGS, although the same examples can be used.


20.7.2 StrAlloc

Declaration
Function StrAlloc(Size: cardinal): PChar;
Description
StrAlloc reserves memory on the heap for a string with length Len, terminating #0 included, and returns a pointer to it.

Additionally, StrAlloc allocates 4 extra bytes to store the size of the allocated memory. Therefore this function is NOT compatible with the StrAlloc function of the Strings unit.

Errors
None.
See also
StrBufSize, StrDispose, StrAlloc

For an example, see StrBufSize.


20.7.3 StrBufSize

Declaration
Function StrBufSize(var Str: PChar): cardinal;
Description
StrBufSize returns the memory allocated for Str. This function ONLY gives the correct result if Str was allocated using StrAlloc.
Errors
If no more memory is available, a runtime error occurs.
See also
StrAlloc.StrDispose.

Example
Program Example46;

{ This program demonstrates the StrBufSize function }
{$H+}

Uses sysutils;

Const S  = 'Some nice string';

Var P : Pchar;
    
Begin
   P:=StrAlloc(Length(S)+1);
   StrPCopy(P,S);
   Write (P, ' has length ',length(S));
   Writeln (' and  buffer size ',StrBufSize(P));
   StrDispose(P);
End.


20.7.4 StrDispose

Declaration
Procedure StrDispose(var Str: PChar);
Description
StrDispose frees any memory allocated for Str. This function will only function correctly if Str has been allocated using StrAlloc from the SYSUTILS unit.
Errors
If an invalid pointer is passed, or a pointer not allocated with StrAlloc, an error may occur.
See also
StrBufSize, StrAlloc, StrDispose

For an example, see StrBufSize.


20.7.5 StrPCopy

Declaration
Function StrPCopy(Dest: PChar; Source: string): PChar;
Description
StrPCopy Converts the Ansistring in Source to a Null-terminated string, and copies it to Dest. Dest needs enough room to contain the string Source, i.e. Length(Source)+1 bytes.
Errors
No checking is performed to see whether Dest points to enough memory to contain Source.
See also
StrPLCopy, StrPCopy

For an example, see StrPCopy.


20.7.6 StrPLCopy

Declaration
Function StrPLCopy(Dest: PChar; Source: string; MaxLen: cardinal): PChar;
Description
StrPLCopy Converts maximally MaxLen characters of the Ansistring in Source to a Null-terminated string, and copies it to Dest. Dest needs enough room to contain the characters.
Errors
No checking is performed to see whether Dest points to enough memory to contain L characters of Source.
Errors
See also
StrPCopy.


20.7.7 StrPas

Declaration
Function StrPas(Str: PChar): string;
Description
Converts a null terminated string in Str to an Ansitring, and returns this string. This string is NOT truncated at 255 characters as is the
Errors
None.
See also
StrPas.

For an example, see StrPas.

20.8 String handling functions


20.8.1 AdjustLineBreaks

Declaration
Function AdjustLineBreaks(const S: string): string;
Description
AdjustLineBreaks will change all #13 characters with #13#10 on WINDOWS NT and DOS. On LINUX, all #13#10 character pairs are converted to #10 and single #13 characters also.
Errors
None.
See also
AnsiCompareStr, AnsiCompareText

Example
Program Example48;

{ This program demonstrates the AdjustLineBreaks function }

Uses sysutils;

Const 
  S = 'This is a string'#13'with embedded'#10'linefeed and'+
       #13'CR characters';

Begin
  Writeln (AdjustLineBreaks(S));
End.


20.8.2 AnsiCompareStr

Declaration
Function AnsiCompareStr(const S1, S2: string): integer;
Description
AnsiCompareStr compares two strings and returns the following result:
<0
if S1<S2.
0
if S1=S2.
>0
if S1>S2.
the comparision takes into account Ansi characters, i.e. it takes care of strange accented characters. Contrary to AnsiCompareText, the comparision is case sensitive.
Errors
None.
See also
AdjustLineBreaks, AnsiCompareText

Example
Program Example49;

{ This program demonstrates the AnsiCompareStr function }
{$H+}

Uses sysutils;

Procedure TestIt (S1,S2 : String);

Var R : Longint;

begin
  R:=AnsiCompareStr(S1,S2);
  Write ('"',S1,'" is ');
  If R<0 then 
    write ('less than ')
  else If R=0 then
    Write ('equal to ')
  else
    Write ('larger than ');
  Writeln ('"',S2,'"');
end;

Begin
  Testit('One string','One smaller string');
  Testit('One string','one string');
  Testit('One string','One string');  
  Testit('One string','One tall string');
End.


20.8.3 AnsiCompareText

Declaration
Function AnsiCompareText(const S1, S2: string): integer;
Description
Description
AnsiCompareText compares two strings and returns the following result:
<0
if S1<S2.
0
if S1=S2.
>0
if S1>S2.
the comparision takes into account Ansi characters, i.e. it takes care of strange accented characters. Contrary to AnsiCompareStr, the comparision is case insensitive.
Errors
None.
See also
AdjustLineBreaks, AnsiCompareText

Example
Program Example49;

{ This program demonstrates the AnsiCompareText function }
{$H+}

Uses sysutils;

Procedure TestIt (S1,S2 : String);

Var R : Longint;

begin
  R:=AnsiCompareText(S1,S2);
  Write ('"',S1,'" is ');
  If R<0 then 
    write ('less than ')
  else If R=0 then
    Write ('equal to ')
  else
    Write ('larger than ');
  Writeln ('"',S2,'"');
end;

Begin
  Testit('One string','One smaller string');
  Testit('One string','one string');
  Testit('One string','One string');  
  Testit('One string','One tall string');
End.


20.8.4 AnsiExtractQuotedStr

Declaration
Function AnsiExtractQuotedStr(var Src: PChar; Quote: Char): string;
Description
AnsiExtractQuotedStr Returns Src as a string,, with Quute characters removed from the beginning and end of the string, and double Quote characters replaced by a single Quote characters. As such, it revereses the action of AnsiQuotedStr.
Errors
None.
See also
AnsiQuotedStr

Example
Program Example51;

{ This program demonstrates the AnsiQuotedStr function }

Uses sysutils;

Var S : AnsiString;

Begin
  S:='He said "Hello" and walked on';
  S:=AnsiQuotedStr(Pchar(S),'"');
  Writeln (S);
  Writeln(AnsiExtractQuotedStr(Pchar(S),'"'));
End.


20.8.5 AnsiLastChar

Declaration
Function AnsiLastChar(const S: string): PChar;
Description
This function returns a pointer to the last character of S. Since multibyte characters are not yet supported, this is the same as @S[Length(S)]).
Errors
None.
See also
AnsiStrLastChar

Example
Program Example52;

{ This program demonstrates the AnsiLastChar function }

Uses sysutils;

Var S : AnsiString;
    L : Longint;
    
Begin
  S:='This is an ansistring.';
  Writeln ('Last character of S is : ',AnsiLastChar(S));
  L:=Longint(AnsiLastChar(S))-Longint(@S[1])+1;
  Writeln ('Length of S is : ',L);
End.


20.8.6 AnsiLowerCase

Declaration
Function AnsiLowerCase(const s: string): string;
Description
AnsiLowerCase converts the string S to lowercase characters and returns the resulting string. It takes into account the operating system language settings when doing this, so spcial characters are converted correctly as well.

Remark On linux, no language setting is taken in account yet.

Errors
None.
See also
AnsiUpperCase, AnsiStrLower, AnsiStrUpper

Example
Program Example53;

{ This program demonstrates the AnsiLowerCase function }

Uses sysutils;

Procedure Testit (S : String);

begin
 Writeln (S,' -> ',AnsiLowerCase(S))
end;

Begin
  Testit('AN UPPERCASE STRING');
  Testit('Some mixed STring');
  Testit('a lowercase string');
End.


20.8.7 AnsiQuotedStr

Declaration
Function AnsiQuotedStr(const S: string; Quote: char): string;
Description
AnsiQuotedString quotes the string S and returns the result. This means that it puts the Quote character at both the beginning and end of the string and replaces any occurrence of Quote in S with 2 Quote characters. The action of AnsiQuotedString can be reversed by AnsiExtractQuotedStr.
Errors
None.
See also
AnsiExtractQuotedStr

For an example, see AnsiExtractQuotedStr


20.8.8 AnsiStrComp

Declaration
Function AnsiStrComp(S1, S2: PChar): integer;
Description
AnsiStrComp compares 2 PChar strings, and returns the following result:
<0
if S1<S2.
0
if S1=S2.
>0
if S1>S2.
The comparision of the two strings is case-sensitive. The function does not yet take internationalization settings into account.
Errors
None.
See also
AnsiCompareText, AnsiCompareStr

Example
Program Example54;

{ This program demonstrates the AnsiStrComp function }

Uses sysutils;

Procedure TestIt (S1,S2 : Pchar);

Var R : Longint;

begin
  R:=AnsiStrComp(S1,S2);
  Write ('"',S1,'" is ');
  If R<0 then 
    write ('less than ')
  else If R=0 then
    Write ('equal to ')
  else
    Write ('larger than ');
  Writeln ('"',S2,'"');
end;

Begin
  Testit('One string','One smaller string');
  Testit('One string','one string');
  Testit('One string','One string');  
  Testit('One string','One tall string');
End.


20.8.9 AnsiStrIComp

Declaration
Function AnsiStrIComp(S1, S2: PChar): integer;
Description
AnsiStrIComp compares 2 PChar strings, and returns the following result:
<0
if S1<S2.
0
if S1=S2.
>0
if S1>S2.
The comparision of the two strings is case-insensitive. The function does not yet take internationalization settings into account.
Errors
None.
See also
AnsiCompareText, AnsiCompareStr

Example
Program Example55;

{ This program demonstrates the AnsiStrIComp function }

Uses sysutils;

Procedure TestIt (S1,S2 : Pchar);

Var R : Longint;

begin
  R:=AnsiStrIComp(S1,S2);
  Write ('"',S1,'" is ');
  If R<0 then 
    write ('less than ')
  else If R=0 then
    Write ('equal to ')
  else
    Write ('larger than ');
  Writeln ('"',S2,'"');
end;

Begin
  Testit('One string','One smaller string');
  Testit('One string','one string');
  Testit('One string','One string');  
  Testit('One string','One tall string');
End.


20.8.10 AnsiStrLastChar

Declaration
function AnsiStrLastChar(Str: PChar): PChar;
Declaration
AnsiStrLastChar returns a pointer to the last character of Str. Since multibyte characters are not yet supported, this is the same as StrEnd(Str)-1.
Errors
None.
See also
AnsiLastChar

Example
Program Example58;

{ This program demonstrates the AnsiStrLastChar function }

Uses sysutils;

Var P : Pchar;
    L : Longint;
    
Begin
  P:='This is an PChar string.';
  Writeln ('Last character of P is : ',AnsiStrLastChar(P));
  L:=Longint(AnsiStrLastChar(P))-Longint(P)+1;
  Writeln ('Length of P (',P,') is : ',L);
End.


20.8.11 AnsiStrLComp

Declaration
Function AnsiStrLComp(S1, S2: PChar; MaxLen: cardinal): integer;
Description
AnsiStrLComp compares the first Maxlen characters of 2 PChar strings, S1 and S2, and returns the following result:
<0
if S1<S2.
0
if S1=S2.
>0
if S1>S2.
The comparision of the two strings is case-sensitive. The function does not yet take internationalization settings into account.
Errors
None.
See also
AnsiCompareText, AnsiCompareStr

Example
Program Example56;

{ This program demonstrates the AnsiStrLComp function }

Uses sysutils;

Procedure TestIt (S1,S2 : Pchar; L : longint);

Var R : Longint;

begin
  R:=AnsiStrLComp(S1,S2,L);
  Write ('First ',L,' characters of "',S1,'" are ');
  If R<0 then 
    write ('less than ')
  else If R=0 then
    Write ('equal to ')
  else
    Write ('larger than ');
  Writeln ('those of "',S2,'"');
end;

Begin
  Testit('One string','One smaller string',255);
  Testit('One string','One String',4);
  Testit('One string','1 string',0);  
  Testit('One string','One string.',9);
End.


20.8.12 AnsiStrLIComp

Declaration
Function AnsiStrLIComp(S1, S2: PChar; MaxLen: cardinal): integer;
Description
AnsiStrLIComp compares the first Maxlen characters of 2 PChar strings, S1 and S2, and returns the following result:
<0
if S1<S2.
0
if S1=S2.
>0
if S1>S2.
The comparision of the two strings is case-insensitive. The function does not yet take internationalization settings into account.
Errors
None.
See also
AnsiCompareText, AnsiCompareStr

Example
Program Example57;

{ This program demonstrates the AnsiStrLIComp function }

Uses sysutils;

Procedure TestIt (S1,S2 : Pchar; L : longint);

Var R : Longint;

begin
  R:=AnsiStrLIComp(S1,S2,L);
  Write ('First ',L,' characters of "',S1,'" are ');
  If R<0 then 
    write ('less than ')
  else If R=0 then
    Write ('equal to ')
  else
    Write ('larger than ');
  Writeln ('those of "',S2,'"');
end;

Begin
  Testit('One string','One smaller string',255);
  Testit('ONE STRING','one String',4);
  Testit('One string','1 STRING',0);  
  Testit('One STRING','one string.',9);
End.


20.8.13 AnsiStrLower

Declaration
Function AnsiStrLower(Str: PChar): PChar;
Description
AnsiStrLower converts the PChar Str to lowercase characters and returns the resulting pchar. Note that Str itself is modified, not a copy, as in the case of AnsiLowerCase. It takes into account the operating system language settings when doing this, so spcial characters are converted correctly as well.

Remark On linux, no language setting is taken in account yet.

Errors
None.
See also
AnsiStrUpper, AnsiLowerCase

Example
Program Example59;

{ This program demonstrates the AnsiStrLower function }

Uses sysutils;

Procedure Testit (S : Pchar);

begin
 Writeln (S,' -> ',AnsiStrLower(S))
end;

Begin
  Testit('AN UPPERCASE STRING');
  Testit('Some mixed STring');
  Testit('a lowercase string');
End.


20.8.14 AnsiStrUpper

Declaration
Function AnsiStrUpper(Str: PChar): PChar;
Description
AnsiStrUpper converts the PChar Str to uppercase characters and returns the resulting string. Note that Str itself is modified, not a copy, as in the case of AnsiUpperCase. It takes into account the operating system language settings when doing this, so spcial characters are converted correctly as well.

Remark On linux, no language setting is taken in account yet.

Errors
None.
See also
AnsiUpperCase, AnsiStrLower, AnsiLowerCase

Example
Program Example60;

{ This program demonstrates the AnsiStrUpper function }

Uses sysutils;

Procedure Testit (S : Pchar);

begin
 Writeln (S,' -> ',AnsiStrUpper(S))
end;

Begin
  Testit('AN UPPERCASE STRING');
  Testit('Some mixed STring');
  Testit('a lowercase string');
End.


20.8.15 AnsiUpperCase

Declaration
Function AnsiUpperCase(const s: string): string;
Description
AnsiUpperCase converts the string S to uppercase characters and returns the resulting string. It takes into account the operating system language settings when doing this, so spcial characters are converted correctly as well.

Remark On linux, no language setting is taken in account yet.

Errors
None.
See also
AnsiStrUpper, AnsiStrLower, AnsiLowerCase

Example
Program Example60;

{ This program demonstrates the AnsiUpperCase function }

Uses sysutils;

Procedure Testit (S : String);

begin
 Writeln (S,' -> ',AnsiUpperCase(S))
end;

Begin
  Testit('AN UPPERCASE STRING');
  Testit('Some mixed STring');
  Testit('a lowercase string');
End.


20.8.16 AppendStr

Declaration
Procedure AppendStr(var Dest: String; const S: string);
Description
AppendStr appends S to Dest.

This function is provided for Delphi compatibility only, since it is completely equivalent to Dest:=Dest+S.

Errors
None.
See also
AssignStr,NewStr, DisposeStr

Example
Program Example62;

{ This program demonstrates the AppendStr function }

Uses sysutils;

Var S : AnsiString;

Begin
  S:='This is an ';
  AppendStr(S,'AnsiString');
  Writeln ('S = "',S,'"');
End.


20.8.17 AssignStr

Declaration
Procedure AssignStr(var P: PString; const S: string);
Description
AssignStr allocates S to P. The old value of P is disposed of.

This function is provided for Delphi compatibility only. AnsiStrings are managed on the heap and should be preferred to the mechanism of dynamically allocated strings.

Errors
None.
See also
NewStr, AppendStr, DisposeStr

Example
Program Example63;

{ This program demonstrates the AssignStr function }
{$H+}

Uses sysutils;

Var P : PString;

Begin
 P:=NewStr('A first AnsiString');
 Writeln ('Before: P = "',P^,'"');
 AssignStr(P,'A Second ansistring');
 Writeln ('After : P = "',P^,'"');
 DisposeStr(P);
End.


20.8.18 BCDToInt

Declaration
Function BCDToInt(Value: integer): integer;
Description
BCDToInt converts a BCD coded integer to a normal integer.
Errors
None.
See also
StrToInt, IntToStr

Example
Program Example64;

{ This program demonstrates the BCDToInt function }

Uses sysutils;

Procedure Testit ( L : longint);
begin
  Writeln (L,' -> ',BCDToInt(L));
end;

Begin
  Testit(10);
  Testit(100);
  Testit(1000);
End.


20.8.19 CompareMem

Declaration
Function CompareMem(P1, P2: Pointer; Length: cardinal): integer;
Description
CompareMem compares, byte by byte, 2 memory areas pointed to by P1 and P2, for a length of L bytes.

It returns the following values:

<0
if at some position the byte at P1 is less than the byte at the same postion at P2.
0
if all L bytes are the same.
3
Errors
See also


20.8.20 CompareStr

Declaration
Function CompareStr(const S1, S2: string): Integer;
Description
CompareStr compares two strings, S1 and S2, and returns the following result:
<0
if S1<S2.
0
if S1=S2.
>0
if S1>S2.
The comparision of the two strings is case-sensitive. The function does not take internationalization settings into account, it simply compares ASCII values.
Errors
None.
See also
AnsiCompareText, AnsiCompareStr, CompareText

Example
Program Example65;

{ This program demonstrates the CompareStr function }
{$H+}

Uses sysutils;

Procedure TestIt (S1,S2 : String);

Var R : Longint;

begin
  R:=CompareStr(S1,S2);
  Write ('"',S1,'" is ');
  If R<0 then 
    write ('less than ')
  else If R=0 then
    Write ('equal to ')
  else
    Write ('larger than ');
  Writeln ('"',S2,'"');
end;

Begin
  Testit('One string','One smaller string');
  Testit('One string','one string');
  Testit('One string','One string');  
  Testit('One string','One tall string');
End.


20.8.21 CompareText

Declaration
Function CompareText(const S1, S2: string): integer;
Description
CompareText compares two strings, S1 and S2, and returns the following result:
<0
if S1<S2.
0
if S1=S2.
>0
if S1>S2.
The comparision of the two strings is case-insensitive. The function does not take internationalization settings into account, it simply compares ASCII values.
Errors
None.
See also
AnsiCompareText, AnsiCompareStr, CompareStr

Example
Program Example66;

{ This program demonstrates the CompareText function }
{$H+}

Uses sysutils;

Procedure TestIt (S1,S2 : String);

Var R : Longint;

begin
  R:=CompareText(S1,S2);
  Write ('"',S1,'" is ');
  If R<0 then 
    write ('less than ')
  else If R=0 then
    Write ('equal to ')
  else
    Write ('larger than ');
  Writeln ('"',S2,'"');
end;

Begin
  Testit('One string','One smaller string');
  Testit('One string','one string');
  Testit('One string','One string');  
  Testit('One string','One tall string');
End.


20.8.22 DisposeStr

Declaration
Procedure DisposeStr(S: PString);
Description
DisposeStr removes the dynamically allocated string S from the heap, and releases the occupied memory.

This function is provided for Delphi compatibility only. AnsiStrings are managed on the heap and should be preferred to the mechanism of dynamically allocated strings.

Errors
None.
See also
NewStr, AppendStr, AssignStr

For an example, see DisposeStr.


20.8.23 FloatToStr

Declaration
Function FloatToStr(Value: Extended): String;
Description
FloatToStr converts the floating point variable Value to a string representation. It will choose the shortest possible notation of the two following formats:
Fixed format
will represent the string in fixed notation,
Decimal format
will represent the string in scientific notation.
(more information on these formats can be found in FloatToStrF) FloatToStr is completely equivalent to a FloatToStrF(Value, ffGeneral, 15, 0); call.
Errors
None.
See also
FloatToStrF

Example
Program Example67;

{ This program demonstrates the FloatToStr function }

Uses sysutils;

Procedure Testit (Value : Extended);

begin
  Writeln (Value,' -> ',FloatToStr(Value));
  Writeln (-Value,' -> ',FloatToStr(-Value));
end;

Begin
  Testit (0.0);
  Testit (1.1);
  Testit (1.1e-3);
  Testit (1.1e-20);
  Testit (1.1e-200);
  Testit (1.1e+3);
  Testit (1.1e+20);
  Testit (1.1e+200);
End.


20.8.24 FloatToStrF

Declaration
Function FloatToStrF(Value: Extended; format: TFloatFormat; Precision, Digits: Integer): String;
Description
FloatToStrF converts the floating point number value to a string representation, according to the settings of the parameters Format, Precision and Digits.

The meaning of the Precision and Digits parameter depends on the Format parameter. The format is controlled mainly by the Format parameter. It can have one of the following values:

ffcurrency
Money format. Value is converted to a string using the global variables CurrencyString, CurrencyFormat and NegCurrencyFormat. The Digits paramater specifies the number of digits following the decimal point and should be in the range -1 to 18. If Digits equals -1, CurrencyDecimals is assumed. The Precision parameter is ignored.
ffExponent
Scientific format. Value is converted to a string using scientific notation: 1 digit before the decimal point, possibly preceded by a minus sign if Value is negative. The number of digits after the decimal point is controlled by Precision and must lie in the range 0 to 15.
ffFixed
Fixed point format. Value is converted to a string using fixed point notation. The result is composed of all digits of the integer part of Value, preceded by a minus sign if Value is negative. Following the integer part is DecimalSeparator and then the fractional part of Value, rounded off to Digits numbers. If the number is too large then the result will be in scientific notation.
ffGeneral
General number format. The argument is converted to a string using ffExponent or ffFixed format, depending on wich one gives the shortest string. There will be no trailing zeroes. If Value is less than 0.00001 or if the number of decimals left of the decimal point is larger than Precision then scientific notation is used, and Digits is the minimum number of digits in the exponent. Otherwise Digits is ignored.
ffnumber
Is the same as ffFixed, except that thousand separators are inserted in the resultig string.
Errors
None.
See also
FloatToStr, FloatToText

Example
Program Example68;

{ This program demonstrates the FloatToStrF function }

Uses sysutils;

Const Fmt : Array [TFloatFormat] of string[10] = 
         ('general','exponent','fixed','number','Currency');

Procedure Testit (Value :  Extended);

Var I,J : longint;
    FF : TFloatFormat;
    
begin
  For I:=5 to 15 do
    For J:=1 to 4 do
      For FF:=ffgeneral to ffcurrency do
        begin
        Write (Value,'(Prec: ',I:2,', Dig: ',J,', fmt : ',Fmt[ff],') : ');
        Writeln (FloatToStrf(Value,FF,I,J));
        Write (-Value,'(Prec: ',I:2,', Dig: ',J,', fmt : ',Fmt[ff],') : ');
        Writeln (FloatToStrf(-Value,FF,I,J));
        end;
end;

Begin
  Testit (1.1);
  Testit (1.1E1);
  Testit (1.1E-1);
  Testit (1.1E5);
  Testit (1.1E-5);
  Testit (1.1E10);
  Testit (1.1E-10);
  Testit (1.1E15);
  Testit (1.1E-15);
  Testit (1.1E100);
  Testit (1.1E-100);
End.


20.8.25 FloatToText

Declaration
Function FloatToText(Buffer : Pchar;Value: Extended; Format: TFloatFormat; Precision, Digits: Integer): Longint;
Description
FloatToText converts the floating point variable Value to a string representation and stores it in Buffer. The conversion is giverned by format, Precisison and Digits. more information on these parameters can be found in FloatToStrF. Buffer should point to enough space to hold the result. No checking on this is performed.

The result is the number of characters that was copied in Buffer.

Errors
None.
See also
FloatToStr, FloatToStrF

Example
Program Example68;

{ This program demonstrates the FloatToStrF function }

Uses sysutils;

Const Fmt : Array [TFloatFormat] of string[10] = 
         ('general','exponent','fixed','number','Currency');

Procedure Testit (Value :  Extended);

Var I,J : longint;
    FF : TFloatFormat;
    S : ShortString;
    
begin
  For I:=5 to 15 do
    For J:=1 to 4 do
      For FF:=ffgeneral to ffcurrency do
        begin
        Write (Value,'(Prec: ',I:2,', Dig: ',J,', fmt : ',Fmt[ff],') : ');
        SetLength(S,FloatToText (@S[1],Value,FF,I,J));
        Writeln (S);
        Write (-Value,'(Prec: ',I:2,', Dig: ',J,', fmt : ',Fmt[ff],') : ');
        SetLength(S,FloatToText (@S[1],-Value,FF,I,J));
        Writeln (S);
        end;
end;

Begin
  Testit (1.1);
  Testit (1.1E1);
  Testit (1.1E-1);
  Testit (1.1E5);
  Testit (1.1E-5);
  Testit (1.1E10);
  Testit (1.1E-10);
  Testit (1.1E15);
  Testit (1.1E-15);
  Testit (1.1E100);
  Testit (1.1E-100);
End.


20.8.26 FmtStr

Declaration
Procedure (Var Res: String; Const Fmt : String; Const args: Array of const);
Description
FmtStr calls Format with Fmt and Args as arguments, and stores the result in Res. For more information on how the resulting string is composed, see Format.
Errors
In case of error, a EConvertError exception is raised.
See also
Format, FormatBuf.

Example
Program Example70;

{ This program demonstrates the FmtStr function }

Uses sysutils;

Var S : AnsiString;

Begin
  S:='';
  FmtStr (S,'For some nice examples of fomatting see %s.',['Format']);
  Writeln (S);
End.


20.8.27 Format

Declaration
Function Format(Const Fmt : String; const Args : Array of const) : String;
Description
Format replaces all placeholders inFmt with the arguments passed in Args and returns the resulting string. A placeholder looks as follows:
'%' [Index':'] ['-'] [Width] ['.' Precision] ArgType
elements between single quotes must be typed as shown without the quotes, and elements between square brackets [ ] are optional. The meaning of the different elements is shown below:
'%'
starts the placeholder. If you want to insert a literal % character, then you must insert two of them : %%.
Index ':'
takes the Index-th element in the argument array as the element to insert.
'-'
tells Format to left-align the inserted text. The default behaviour is to right-align inserted text. This can only take effect if the Width element is also specified.
Width
the inserted string must have at least have Width characters. If not, the inserted string will be padded with spaces. By default, the string is left-padded, resulting in a right-aligned string. This behaviour can be changed by the '-' character.
'.' Precision
Indicates the precision to be used when converting the argument. The exact meaning of this parameter depends on ArgType.
The Index, Width and Precision parameters can be replaced by *, in which case their value will be read from the next element in the Args array. This value must be an integer, or an EConvertError exception will be raised.

The argument type is determined from ArgType. It can have one of the following values (case insensitive):

D
Decimal format. The next argument in the Args array should be an integer. The argument is converted to a decimal string,. If precision is specified, then the string will have at least Precision digits in it. If needed, the string is (left) padded with zeroes.
E
scientific format. The next argument in the Args array should be a Floating point value. The argument is converted to a decimal string using scientific notation, using FloatToStrF, where the optional precision is used to specify the total number of decimals. (defalt a valueof 15 is used). The exponent is formatted using maximally 3 digits.

In short, the E specifier formats it's arguument as follows:

FloatToStrF(Argument,ffexponent,Precision,3)

F
fixed point format. The next argument in the Args array should be a floating point value. The argument is converted to a decimal string, using fixed notation (see FloatToStrF). Precision indicates the number of digits following the decimal point.

In short, the F specifier formats it's arguument as follows:

FloatToStrF(Argument,ffFixed,ffixed,9999,Precision)

G
General number format. The next argument in the Args array should be a floating point value. The argument is converted to a decimal string using fixed point notation or scientific notation, depending on which gives the shortest result. Precision is used to determine the number of digits after the decimal point.

In short, the G specifier formats it's arguument as follows:

FloatToStrF(Argument,ffGeneral,Precision,3)

M
Currency format. the next argument in the varArgs array must be a floating point value. The argument is converted to a decimal string using currency notation. This means that fixed-point notation is used, but that the currency symbol is appended. If precision is specified, then then it overrides the CurrencyDecimals global variable used in the FloatToStrF

In short, the M specifier formats it's arguument as follows:

FloatToStrF(Argument,ffCurrency,9999,Precision)

N
Number format. This is the same as fixed point format, except that thousand separators are inserted in the resulting string.

P
Pointer format. The next argument in the Args array must be a pointer (typed or untyped). The pointer value is converted to a string of length 8, representing the hexadecimal value of the pointer.

S
String format. The next argument in the Args array must be a string. The argument is simply copied to the result string. If Precision is specified, then only Precision characters are copied to the result string.

X
hexadecimal format. The next argument in the Args array must be an integer. The argument is converted to a hexadecimal string with just enough characters to contain the value of the integer. If Precision is specified then the resulting hexadecimal representation will have at least Precision characters in it (with a maximum value of 32).
Errors
In case of error, an EConversionError exception is raised. Possible errors are:
  1. Errors in the format specifiers.
  2. The next argument is not of the type needed by a specifier.
  3. The number of arguments is not sufficient for all format specifiers.
See also
FormatBuf

Example
Program example71;

{$mode objfpc}

{ This program demonstrates the Format function }

Uses sysutils;

Var P : Pointer;
    fmt,S : string;

Procedure TestInteger;

begin
  Try
    Fmt:='[%d]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%%]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%10d]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    fmt:='[%.4d]';S:=Format (fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%10.4d]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:d]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:10d]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:10.4d]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:-10d]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:-10.4d]';S:=Format (fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%-*.*d]';S:=Format (fmt,[4,5,10]);writeln(Fmt:12,' => ',s);
  except
    On E : Exception do
      begin
      Writeln ('Exception caught : ',E.Message);
      end;
  end;
  writeln ('Press enter');
  readln;
end;

Procedure TestHexaDecimal;

begin
  try
    Fmt:='[%x]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%10x]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%10.4x]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:x]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:10x]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:10.4x]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:-10x]';S:=Format (Fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:-10.4x]';S:=Format (fmt,[10]);writeln(Fmt:12,' => ',s);
    Fmt:='[%-*.*x]';S:=Format (fmt,[4,5,10]);writeln(Fmt:12,' => ',s);
  except
    On E : Exception do
      begin
      Writeln ('Exception caught : ',E.Message);
      end;
  end;
  writeln ('Press enter');
  readln;
end;

Procedure TestPointer;
     
begin
  P:=Pointer(1234567);
  try
    Fmt:='[0x%p]';S:=Format (Fmt,[P]);writeln(Fmt:12,' => ',s);
    Fmt:='[0x%10p]';S:=Format (Fmt,[P]);writeln(Fmt:12,' => ',s);
    Fmt:='[0x%10.4p]';S:=Format (Fmt,[P]);writeln(Fmt:12,' => ',s);
    Fmt:='[0x%0:p]';S:=Format (Fmt,[P]);writeln(Fmt:12,' => ',s);
    Fmt:='[0x%0:10p]';S:=Format (Fmt,[P]);writeln(Fmt:12,' => ',s);
    Fmt:='[0x%0:10.4p]';S:=Format (Fmt,[P]);writeln(Fmt:12,' => ',s);
    Fmt:='[0x%0:-10p]';S:=Format (Fmt,[P]);writeln(Fmt:12,' => ',s);
    Fmt:='[0x%0:-10.4p]';S:=Format (fmt,[P]);writeln(Fmt:12,' => ',s);
    Fmt:='[%-*.*p]';S:=Format (fmt,[4,5,P]);writeln(Fmt:12,' => ',s);
  except
    On E : Exception do
      begin
      Writeln ('Exception caught : ',E.Message);
      end;
  end;
  writeln ('Press enter');
  readln;
end;

Procedure TestString;

begin
  try
    Fmt:='[%s]';S:=Format(fmt,['This is a string']);Writeln(fmt:12,'=> ',s);
    fmt:='[%0:s]';s:=Format(fmt,['This is a string']);Writeln(fmt:12,'=> ',s);
    fmt:='[%0:18s]';s:=Format(fmt,['This is a string']);Writeln(fmt:12,'=> ',s);
    fmt:='[%0:-18s]';s:=Format(fmt,['This is a string']);Writeln(fmt:12,'=> ',s);
    fmt:='[%0:18.12s]';s:=Format(fmt,['This is a string']);Writeln(fmt:12,'=> ',s);
    fmt:='[%-*.*s]';s:=Format(fmt,[18,12,'This is a string']);Writeln(fmt:12,'=> ',s);
  except
    On E : Exception do
      begin
      Writeln ('Exception caught : ',E.Message);
      end;
  end;
  writeln ('Press enter');
  readln;
end;

Procedure TestExponential;

begin
  Try
    Fmt:='[%e]';S:=Format (Fmt,[1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%10e]';S:=Format (Fmt,[1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%10.4e]';S:=Format (Fmt,[1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:e]';S:=Format (Fmt,[1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:10e]';S:=Format (Fmt,[1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:10.4e]';S:=Format (Fmt,[1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:-10e]';S:=Format (Fmt,[1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:-10.4e]';S:=Format (fmt,[1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%-*.*e]';S:=Format (fmt,[4,5,1.234]);writeln(Fmt:12,' => ',s);
  except
    On E : Exception do
      begin
      Writeln ('Exception caught : ',E.Message);
      end;
  end;
  writeln ('Press enter');
  readln;
end;

Procedure TestNegativeExponential;

begin
  Try
    Fmt:='[%e]';S:=Format (Fmt,[-1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%10e]';S:=Format (Fmt,[-1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%10.4e]';S:=Format (Fmt,[-1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:e]';S:=Format (Fmt,[-1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:10e]';S:=Format (Fmt,[-1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:10.4e]';S:=Format (Fmt,[-1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:-10e]';S:=Format (Fmt,[-1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:-10.4e]';S:=Format (fmt,[-1.234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%-*.*e]';S:=Format (fmt,[4,5,-1.234]);writeln(Fmt:12,' => ',s);
  except
    On E : Exception do
      begin
      Writeln ('Exception caught : ',E.Message);
      end;
  end;
  writeln ('Press enter');
  readln;
end;

Procedure TestSmallExponential;

begin
  Try
    Fmt:='[%e]';S:=Format (Fmt,[0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%10e]';S:=Format (Fmt,[0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%10.4e]';S:=Format (Fmt,[0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:e]';S:=Format (Fmt,[0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:10e]';S:=Format (Fmt,[0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:10.4e]';S:=Format (Fmt,[0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:-10e]';S:=Format (Fmt,[0.0123]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:-10.4e]';S:=Format (fmt,[0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%-*.*e]';S:=Format (fmt,[4,5,0.01234]);writeln(Fmt:12,' => ',s);
  except
    On E : Exception do
      begin
      Writeln ('Exception caught : ',E.Message);
      end;
  end;
  writeln ('Press enter');
  readln;
end;

Procedure TestSmallNegExponential;

begin
  Try
    Fmt:='[%e]';S:=Format (Fmt,[-0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%10e]';S:=Format (Fmt,[-0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%10.4e]';S:=Format (Fmt,[-0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:e]';S:=Format (Fmt,[-0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:10e]';S:=Format (Fmt,[-0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:10.4e]';S:=Format (Fmt,[-0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:-10e]';S:=Format (Fmt,[-0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%0:-10.4e]';S:=Format (fmt,[-0.01234]);writeln(Fmt:12,' => ',s);
    Fmt:='[%-*.*e]';S:=Format (fmt,[4,5,-0.01234]);writeln(Fmt:12,' => ',s);
  except
    On E : Exception do
      begin
      Writeln ('Exception caught : ',E.Message);
      end;
  end;
  writeln ('Press enter');
  readln;
end;

begin
  TestInteger;
  TestHexadecimal;
  TestPointer;
  TestExponential;
  TestNegativeExponential;
  TestSmallExponential;  
  TestSmallNegExponential;  
end.


20.8.28 FormatBuf

Declaration
Function FormatBuf(Var Buffer; BufLen : Cardinal; Const Fmt; fmtLen : Cardinal; Const Args : Array of const) : Cardinal;
Description
Format
Errors
See also

Example
Program Example72;

{ This program demonstrates the FormatBuf function }

Uses sysutils;

Var 
  S : ShortString;

Const 
  Fmt : ShortString =  'For some nice examples of fomatting see %s.';
    
Begin
  S:='';
  SetLength(S,FormatBuf (S[1],255,Fmt[1],Length(Fmt),['Format']));
  Writeln (S);
End.


20.8.29 IntToHex

Declaration
Function IntToHex(Value: integer; Digits: integer): string;
Description
IntToHex converts Value to a hexadecimal string representation. The result will contain at least Digits characters. If Digits is less than the needed number of characters, the string will NOT be truncated. If Digits is larger than the needed number of characters, the result is padded with zeroes.
Errors
None.
See also
IntToStr, StrToInt

Example
Program Example73;

{ This program demonstrates the IntToHex function }

Uses sysutils;

Var I : longint;

Begin
  For I:=0 to 31 do
      begin
      Writeln (IntToHex(1 shl I,8));
      Writeln (IntToHex(15 shl I,8))
      end;
End.


20.8.30 IntToStr

Declaration
Function IntToStr(Value: integer): string;
Description
IntToStr coverts Value to it's string representation. The resulting string has only as much characters as needed to represent the value. If the value is negative a minus sign is prepended to the string.
Errors
None.
See also
IntToHex, StrToInt

Example
Program Example74;

{ This program demonstrates the IntToStr function }

Uses sysutils;

Var I : longint;

Begin
  For I:=0 to 31 do
      begin
      Writeln (IntToStr(1 shl I));
      Writeln (IntToStr(15 shl I));
      end;
End.


20.8.31 IsValidIdent

Declaration
Function IsValidIdent(const Ident: string): boolean;
Description
IsValidIdent returns True if Ident can be used as a compoent name. It returns False otherwise. Ident must consist of a letter or underscore, followed by a combination of letters, numbers or underscores to be a valid identifier.
Errors
None.
See also

Example
Program Example75;

{ This program demonstrates the IsValidIdent function }

Uses sysutils;

Procedure Testit (S : String);

begin
  Write ('"',S,'" is ');
  If not IsVAlidIdent(S) then 
    Write('NOT ');
  Writeln ('a valid identifier');
end;

Begin
  Testit ('_MyObj');
  Testit ('My__Obj1');
  Testit ('My_1_Obj');
  Testit ('1MyObject');
  Testit ('My@Object');
  Testit ('M123');
End.


20.8.32 LastDelimiter

Declaration
Function LastDelimiter(const Delimiters, S: string): Integer;
Description
LastDelimiter returns the last occurrence of any character in the set Delimiters in the string S.
Errors
See also

Example
Program example88;

{ This program demonstrates the LastDelimiter function }

uses SysUtils;

begin
  Writeln(LastDelimiter('\.:','c:\filename.ext'));
end.


20.8.33 LeftStr

Declaration
Function LeftStr(const S: string; Count: integer): string;
Description
LeftStr returns the Count leftmost characters of S. It is equivalent to a call to Copy(S,1,Count).
Errors
None.
See also
RightStr, TrimLeft, TrimRight, Trim

Example
Program Example76;

{ This program demonstrates the LeftStr function }

Uses sysutils;

Begin
  Writeln (LeftStr('abcdefghijklmnopqrstuvwxyz',20));
  Writeln (LeftStr('abcdefghijklmnopqrstuvwxyz',15));
  Writeln (LeftStr('abcdefghijklmnopqrstuvwxyz',1));
  Writeln (LeftStr('abcdefghijklmnopqrstuvwxyz',200));
End.


20.8.34 LoadStr

Declaration
Function LoadStr(Ident: integer): string;
Description
This function is not yet implemented. resources are not yet supported.
Errors
See also


20.8.35 LowerCase

Declaration
Function LowerCase(const s: string): string;
Description
LowerCase returns the lowercase equivalent of S. Ansi characters are not taken into account, only ASCII codes below 127 are converted. It is completely equivalent to the lowercase function of the system unit, and is provided for compatiibility only.
Errors
None.
See also
AnsiLowerCase, UpperCase, AnsiUpperCase

Example
Program Example77;

{ This program demonstrates the LowerCase function }

Uses sysutils;

Begin
  Writeln (LowerCase('THIS WILL COME out all LoWeRcAsE !'));
End.


20.8.36 NewStr

Declaration
Function NewStr(const S: string): PString;
Description
NewStr assigns a new dynamic string on the heap, copies S into it, and returns a pointer to the newly assigned string.

This function is obsolete, and shouldn't be used any more. The AnsiString mechanism also allocates ansistrings on the heap, and should be preferred over this mechanism.

Errors
If not enough memory is present, an EOutOfMemory exception will be raised.
See also
AssignStr, DisposeStr

For an example, see AssignStr.


20.8.37 QuotedStr

Declaration
Function QuotedStr(const S: string): string;
Description
QuotedStr returns the string S, quoted with single quotes. This means that S is enclosed in single quotes, and every single quote in S is doubled. It is equivalent to a call to AnsiQuotedStr(s, '''').
Errors
None.
See also
AnsiQuotedStr, AnsiExtractQuotedStr.

Example
Program Example78;

{ This program demonstrates the QuotedStr function }

Uses sysutils;

Var S : AnsiString;

Begin
  S:='He said ''Hello'' and walked on';
  Writeln (S);
  Writeln ('  becomes');
  Writeln (QuotedStr(S));
End.


20.8.38 RightStr

Declaration
Function RightStr(const S: string; Count: integer): string;
Description
RightStr returns the Count rightmost characters of S. It is equivalent to a call to Copy(S,Length(S)+1-Count,Count).

If Count is larger than the actual length of S only the real length will be used.

Errors
None.
See also
LeftStr,Trim, TrimLeft, TrimRight

Example
Program Example79;

{ This program demonstrates the RightStr function }

Uses sysutils;

Begin
  Writeln (RightStr('abcdefghijklmnopqrstuvwxyz',20));
  Writeln (RightStr('abcdefghijklmnopqrstuvwxyz',15));
  Writeln (RightStr('abcdefghijklmnopqrstuvwxyz',1));
  Writeln (RightStr('abcdefghijklmnopqrstuvwxyz',200));
End.


20.8.39 StrFmt

Declaration
Function StrFmt(Buffer,Fmt : PChar; Const args: Array of const) : Pchar;
Description
StrFmt will format fmt with Args, as the Format function does, and it will store the result in Buffer. The function returns Buffer. Buffer should point to enough space to contain the whole result.
Errors
for a list of errors, see Format.
See also
StrLFmt, FmtStr, Format, FormatBuf

Example
Program Example80;

{ This program demonstrates the StrFmt function }

Uses sysutils;

Var S : AnsiString;

Begin
  SetLEngth(S,80);
  Writeln (StrFmt (@S[1],'For some nice examples of fomatting see %s.',['Format']));
End.


20.8.40 StrLFmt

Declaration
Function StrLFmt(Buffer : PCHar; Maxlen : Cardinal;Fmt : PChar; Const args: Array of const) : Pchar;
Description
StrLFmt will format fmt with Args, as the Format function does, and it will store maximally Maxlen characters of the result in Buffer. The function returns Buffer. Buffer should point to enough space to contain MaxLen characters.
Errors
for a list of errors, see Format.
See also
StrFmt, FmtStr, Format, FormatBuf

Example
Program Example80;

{ This program demonstrates the StrFmt function }

Uses sysutils;

Var S : AnsiString;

Begin
  SetLEngth(S,80);
  Writeln (StrLFmt (@S[1],80,'For some nice examples of fomatting see %s.',['Format']));
End.


20.8.41 StrToInt

Declaration
Function StrToInt(const s: string): integer;
Description
StrToInt will convert the string Sto an integer. If the string contains invalid characters or has an invalid format, then an EConvertError is raised.

To be successfully converted, a string can contain a combination of numerical characters, possibly preceded by a minus sign (-). Spaces are not allowed.

Errors
In case of error, an EConvertError is raised.
See also
IntToStr, StrToIntDef

Example
Program Example82;

{$mode objfpc}

{ This program demonstrates the StrToInt function }

Uses sysutils;

Begin
  Writeln (StrToInt('1234'));
  Writeln (StrToInt('-1234'));
  Writeln (StrToInt('0'));
  Try
    Writeln (StrToInt('12345678901234567890'));
  except
    On E : EConvertError do
      Writeln ('Invalid number encountered');
  end;
End.


20.8.42 StrToIntDef

Declaration
Function StrToIntDef(const S: string; Default: integer): integer;
Description
StrToIntDef will convert a string to an integer. If the string contains invalid characters or has an invalid format, then Default is returned.

To be successfully converted, a string can contain a combination of numerical characters, possibly preceded by a minus sign (-). Spaces are not allowed.

Errors
None.
See also
IntToStr, StrToInt

Example
Program Example82;

{$mode objfpc}

{ This program demonstrates the StrToInt function }

Uses sysutils;

Begin
  Writeln (StrToIntDef('1234',0));
  Writeln (StrToIntDef('-1234',0));
  Writeln (StrToIntDef('0',0));
  Try
    Writeln (StrToIntDef('12345678901234567890',0));
  except
    On E : EConvertError do
      Writeln ('Invalid number encountered');
  end;
End.


20.8.43 Trim

Declaration
Function Trim(const S: string): string;
Description
Trim strips blank characters (spaces) at the beginning and end of S and returns the resulting string. Only #32 characters are stripped.

If the string contains only spaces, an empty string is returned.

Errors
None.
See also
TrimLeft, TrimRight

Example
Program Example84;

{ This program demonstrates the Trim function }

Uses sysutils;
{$H+}

Procedure Testit (S : String);

begin
  Writeln ('"',Trim(S),'"');
end;

Begin
  Testit ('  ha ha what gets lost ? ');
  Testit (#10#13'haha ');
  Testit ('              ');
End.


20.8.44 TrimLeft

Declaration
Function TrimLeft(const S: string): string;
Description
TrimLeft strips blank characters (spaces) at the beginning of S and returns the resulting string. Only #32 characters are stripped.

If the string contains only spaces, an empty string is returned.

Errors
None.
See also
Trim, TrimRight

Example
Program Example85;

{ This program demonstrates the TrimLeft function }

Uses sysutils;
{$H+}

Procedure Testit (S : String);

begin
  Writeln ('"',TrimLeft(S),'"');
end;

Begin
  Testit ('  ha ha what gets lost ? ');
  Testit (#10#13'haha ');
  Testit ('              ');
End.


20.8.45 TrimRight

Declaration
Function TrimRight(const S: string): string;
Description
Trim strips blank characters (spaces) at the end of S and returns the resulting string. Only #32 characters are stripped.

If the string contains only spaces, an empty string is returned.

Errors
None.
See also
Trim, TrimLeft

Example
Program Example86;

{ This program demonstrates the TrimRight function }

Uses sysutils;
{$H+}

Procedure Testit (S : String);

begin
  Writeln ('"',TrimRight(S),'"');
end;

Begin
  Testit ('  ha ha what gets lost ? ');
  Testit (#10#13'haha ');
  Testit ('              ');
End.


20.8.46 UpperCase

Declaration
Function UpperCase(const s: string): string;
Description
UpperCase returns the uppercase equivalent of S. Ansi characters are not taken into account, only ASCII codes below 127 are converted. It is completely equivalent to the UpCase function of the system unit, and is provided for compatiibility only.
Errors
None.
See also
AnsiLowerCase, LowerCase, AnsiUpperCase
Errors
See also

Example
Program Example87;

{ This program demonstrates the UpperCase function }

Uses sysutils;

Begin
  Writeln (UpperCase('this will come OUT ALL uPpErCaSe !'));
End.



root
2000-12-20