Chapter 4
of the
Turbo Pascal Reference
The System Library Reference
This chapter is part of the Turbo Pascal Reference electronic freeware book (C)
Copyright 1992 by Ed Mitchell. This freeware book contains supplementary
material to Borland Pascal Developer's Guide, published by Que Corporation,
1992. However, Que Corporation has no affiliation with nor responsibility for
the content of this free book. Please see Chapter 1 of the Turbo Pascal
Reference for important information about your right to distribute and use this
material freely. If you find this material of use, I would appreciate your
purchase of one my books, such as the Borland Pascal Developer's Guide or
Secrets of the Borland C++ Masters, Sams Books, 1992. Thank you.
Note: For ease of access, Chapter 4 is continued in TPR4B.TXT.
The System Library contains several standard units, including System, Crt,
Dos, Overlay and Printer. These units provide a large set of routines for
performing input and output, file system access and file manipulation, access
to DOS, full text screen support including selecting foreground and background
colors, mathematical functions and other features. This section describes the
available library routines. The Overlay and Graph units are described in the
Borland Pascal Developer's Guide, Que Books, 1992. The System Library
Reference contains, in alphabetical order, explanations and sample code for the
functions, procedure and variables defined in each of the units.
The procedures and functions contained in the System unit are directly
accessible to your programs and units at all times; you do not need to use the
System unit. However, the procedures and functions available in the Crt, Dos,
Graph, Overlay and Printer units require that these units be named in a uses
statement in your program or unit.
The contents of the System, Crt, Dos, Overlay and Printer units are
normally contained in the TURBO.TPL library file. You can add or delete units
in TURBO.TPL using the TPUMOVER utility (see "Using TPUMOVER to Update
TURBO.TPL" in chapter 2, "Units and Dynamic Link Libraries" in the Borland
Pascal Developer's Guide (Que Books, 1992)). The GRAPH unit, due to its size,
is kept in a separate GRAPH.TPU file.
Overcoming Potential Name Conflicts
Occassionally a unit procedure or function identifier will conflict with
one of your own identifiers. When this occurs, you can still access the
library identifier by prefacing it with its unit name. For example,
System.Abs, or Dos.GetTime.
Quick Reference to
Crt, Dos and System Unit Procedures and Functions
Unit: Crt
procedure AssignCrt(var F: Text);
procedure ClrEol;
procedure ClrScr;
procedure Delay(MS: Word);
procedure DelLine;
procedure GotoXY(X,Y: Byte);
procedure HighVideo;
procedure InsLine;
function KeyPressed: Boolean;
procedure LowVideo;
procedure NormVideo;
procedure NoSound;
function ReadKey: Char;
procedure Sound(Hz: Word);
procedure TextBackground(Color: Byte);
procedure TextColor(Color: Byte);
procedure TextMode(Mode: Integer);
function WhereX: Byte;
function WhereY: Byte;
procedure Window(X1,Y1,X2,Y2: Byte);
Unit: Dos
function DiskFree(Drive: Byte): Longint;
function DiskSize(Drive: Byte): Longint;
function DosVersion: Word;
function DosExitCode: Word;
function EnvCount: Integer;
function EnvStr(Index: Integer): String;
procedure Exec(Path: PathStr; ComLine: ComStr);
function FExpand(Path: PathStr): PathStr;
procedure FindFirst(Path: PathStr; Attr: Word; var F: SearchRec);
procedure FindNext(var F: SearchRec);
function FSearch(Path: PathStr; DirList: String): PathStr;
procedure FSplit(Path: PathStr; var Dir: DirStr;
var Name: NameStr; var Ext: ExtStr);
procedure GetCBreak(var Break: Boolean);
procedure GetDate(var Year,Month,Day,DayOfWeek: Word);
function GetEnv(EnvVar: String): String;
procedure GetIntVec(IntNo: Byte; var Vector: Pointer);
procedure GetFAttr(var F; var Attr: Word);
procedure GetFTime(var F; var Time: Longint);
procedure GetTime(var Hour,Minute,Second,Sec100: Word);
procedure GetVerify(var Verify: Boolean);
procedure Intr(IntNo: Byte; var Regs: Registers);
procedure Keep(ExitCode: Word);
procedure MsDos(var Regs: Registers);
procedure PackTime(var T: DateTime; var P: Longint);
procedure SetCBreak(Break: Boolean);
procedure SetDate(Year,Month,Day: Word);
procedure SetFAttr(var F; Attr: Word);
procedure SetFTime(var F; Time: Longint);
procedure SetIntVec(IntNo: Byte; Vector: Pointer);
procedure SetTime(Hour,Minute,Second,Sec100: Word);
procedure SetVerify(Verify: Boolean);
procedure SwapVectors;
procedure UnpackTime(P: Longint; var T: DateTime);
Unit: System
function Abs( X : Integer) : Integer; { Note result type is same as }
function Abs( X : Real ) : Real; { parameter type }
function Addr ( X ) : Pointer;
procedure Append ( var F : Text );
function ArcTan ( X: Real );
procedure AssignCrt(var F: Text );
procedure BlockRead( var F: File; var Buf; Count: Word [; var Result:
Word]);
procedure BlockWrite( var F: File; var Buf; Count : Word [; var Result:
Word]);
function Chr( X : Byte) : Char;
procedure Close (var F);
function Concat ( S1 [, S2, ... Sn] : String ) :String;
function Copy ( S: String; Index : Integer; Count: Integer ) : String;
function Cos( X : Real );
function CSeg : Word;
procedure Dec ( var X [; N : Longint] );
procedure Delete(var S: String; Index: Integer; Count: Integer);
procedure Dispose ( var P : Pointer [, Destructor] );
function DSeg : Word;
function Eof : Boolean;
function Eof(var F: Text): Boolean;
function Eof(var F): Boolean;
function Eoln : Boolean;
function Eoln(var F: Text): Boolean;
procedure Erase ( var F: File );
procedure Exit;
function Exp( X: Real ): Real;
function FilePos ( var F ): Longint;
function FileSize ( var F ) : Longint;
procedure FillChar( var X; Count : Word; Value );
procedure Flush ( var F: Text );
function Frac ( X: Real ): Real;
procedure FreeMem (var P: Pointer; Size : Word );
function FSearch( Path: PathStr; DirList: String ): PathStr;
procedure FSplit ( Path : PathStr; var Dir: DirStr;
var Name: NameStr; var Ext: ExtStr );
procedure GetDate(var Year, Month, Day, DayofWeek: Word);
procedure GetDir( D: Byte; var S: String );
procedure GetIntVec(IntNo: Byte; var Vector:Pointer);
procedure GetMem(var P: Pointer; Size: Word);
procedure GetTime(var Hour, Minute, Second, Sec100:Word);
procedure Halt [ (ExitCode: Word); ]
function Hi ( X ) : Byte;
procedure Inc (var X [; N: Longint ] );
procedure Insert( Source: String; var S: String;Index: Integer);
function Int( X: Real ) : Real;
function IOResult : Word;
function Length ( S : String );
function Ln( X : Real );
function Lo(X): Byte;
procedure Mark (var P: Pointer);
function MaxAvail : Longint;
function MemAvail : Longint;
procedure MkDir(S: String);
procedure Move (var Source, Dest; Count : Word);
procedure New( var P: Pointer [, Init: constructor] );
function Odd( X: Longint ): Boolean;
function Ofs( X ): Word;
function Ord( X ): Longint;
procedure PackTime(var DT: DateTime; var Time:Longint);
function ParamCount : Word;
function ParamStr( Index: Word ) : String;
function Pi : Real;
function Pos ( Substr, S: String ): Byte;
function Pred( X ) : <same type as X>;
function Ptr( Seg, Ofs : Word) : Pointer;
function Random [ (Range: Word) ] : Word;
function Random [ (Range: Word) ] : Real;
procedure Randomize;
procedure Read( [var F: Text; ] V1 [, V2, ..., Vn ]);
procedure Read ( F, V1 [, V2, ..., Vn ] );
procedure Readln( [var F: Text; ] [V1, V2, ..., Vn ] );
procedure Release (var P: Pointer);
procedure Rename(var F; Newname : String );
procedure Reset (var F [: File; RecSize: Word] );
procedure Rewrite (var F [: File; RecSize: Word] );
procedure RmDir ( S: String );
procedure Round ( X: Real );
procedure RunError [ ( ErrorCode: Byte ) ];
procedure Seek(var F; N: Longint);
function SeekEof [ ( var F: Text ); ]
function SeekEoln[ (var F: Text); ]
function Seg(X): Word;
procedure SetTextBuf(var F: Text; var Buf [; Size:Word ] );
procedure SetTime(Hour, Minute, Second, Sec100:Word);
function Sin ( X: Real ) : Real;
function SizeOf( X ) : Word;
function SPtr : Word;
function Sqr( X ) : <type of X>
function Sqrt(X: Real) : Real;
function SSeg: Word;
procedure Str(X [: Width [:Decimals] ]; var S:);
function Succ(X) : <same type as X>;
function Swap(X) : <same type as X>;
function Trunc( X: Real ): Longint;
procedure Truncate(var F);
procedure UnpackTime(Time: Longint; var DT:DateTime);
function UpCase (Ch: Char): Char;
procedure Val(S: String; var V; var Code: Integer);
procedure Write( [ var F: Text; ] V1 [, V2, ..., Vn] );
procedure Write( var F; V1, [, V2, ..., Nn ] );
procedure Writeln( [var F:Text; ] [V1 [V2, ..., Vn]] );
Reference Section
Abs function
----------------------------------------------------------------
Declaration:
function Abs( X : Integer) : Integer;
function Abs( X : Real ) : Real;
Example:
Writeln ( Abs( 3.14159 ):6:5 );
Writeln( Abs( -3.14159 ):6:5);
Writeln ( Abs (-3 ) );
outputs,
3.14159
3.14159
3
Purpose:
If X is less than zero, then Abs returns -X, hence, converting X to a
positive value. If X is greater than zero, then Abs returns X. Abs assumes
the data type of the parameter, either integer or real.
Addr Function
----------------------------------------------------------------
Declaration:
function Addr ( X ) : Pointer;
Example:
var
S : String;
PS : ^String;
...
S := 'This is only a test!';
PS := Addr ( S );
Writeln( PS^ );
Purpose:
Like the @ address-of operator, Addr returns the memory address of its
operand. The statement,
PS := Addr(S);
is equivalent to writing,
PS := @S;
Append procedure
----------------------------------------------------------------
Declaration:
procedure Append ( var F : Text );
Example:
var
TextFile : Text;
...
Assign ( TextFile, 'OLDFILE.TXT' );
Append ( TextFile );
Writeln ('This will be written at the end of the existing file
OLDFILE.TXT');
Purpose:
Like Reset, Append is used to open a text file, but instead of positioning
the file pointer to the beginning of the file, Append places the file pointer
at the very end. This way, subsequent writes are appended to the existing data
in the text file. Obviously, the file identifier opened by Append becomes a
write-only file type.
ArcCos/ArcSin functions
----------------------------------------------------------------
The Turbo Pascal library omits arc-sine and arc-cosine functions. However,
these functions may be calculated using the the relations shown in these
function definitions, returning a result in the range of [-Pi/2 .. Pi/2 ]:
function ArcCos ( X : Real ): Real;
var
TempArcCos : Real;
begin
if X = 0.0 then { to avoid division by 0 }
TempArcCos := Pi / 2.0
else
TempArcCos := ArcTan ( Sqrt ( 1 - X*X ) / X );
if X < 0.0 then
TempArcCos := PI - TempArcCos;
ArcCos := TempArcCos;
end;
function ArcSin ( X : Real ): Real;
begin
if X = 1.0 then { to avoid division by 0 }
ArcSin := Pi / 2.0
else
ArcSin := ArcTan ( X / Sqrt ( 1 - X * X ) );
end;
See ArcTan, Cos, Sin, Sqrt, Tan
ArcTan function
----------------------------------------------------------------
Declaration:
function ArcTan ( X: Real );
Purpose:
Computes the arc-tangent of X, returning an angle measurement, in radians.
See ArcCos/ArcSin, Cos, Sin, Tan
Assign procedure
----------------------------------------------------------------
Declaration:
procedure Assign( var F; Name : String );
Example:
var
InputFile : Text;
...
Assign ( InputFile, 'DATA.TXT' );
{$I-}
Reset ( InputFile );
Purpose:
Associates the filename Name with the file identifier F, where Name
contains a standard DOS filename, optionally including drive and path
specifications up to 79 characters in length and F is of any file type. You
must use Assign before opening a file with Reset, Rewrite or Append, or when
using the Erase or Rename procedures.
If you Assign the null string to a file identifier, as,
Assign ( InputFile, '' );
a subsequent Reset opens the DOS standard input file and a Rewrite opens the
DOS standard output. The standard input and output files may be used with DOS
command line redirection.
See Append, Close, Reset, Rewrite, and "File Operations" in chapter 3 of the
Turbo Pascal Reference.
AssignCrt procedure
----------------------------------------------------------------
Declaration:
procedure AssignCrt(var F: Text );
Unit: Crt
Example:
if UseScreen then
AssignCrt( OutFile )
else
AssignCrt( OutFile, 'OUTPUT.TXT' );
Rewrite ( OutFile );
Writeln ( OutFile, 'Report of Summer Activities');
Writeln( OutFile );
Purpose:
AssignCrt is used in conjunction with Reset and Rewrite, to access the Crt
screen as a file. AssignCrt may be used to provide an option in your program
to direct output to either a file or to the screen. When file output is
selected, use Assign to specify the output text file. When the screen is
requested, use AssignCrt. Then, after using Rewrite to open the output device,
your Write statements will route your output to the file or the screen,
depending upon how you made the initial assignment to the file identifier.
See Assign, Close, Reset, Rewrite
BlockRead procedure
----------------------------------------------------------------
Declaration:
procedure BlockRead( var F: File; var Buf; Count: Word
[; var Result: Word] );
Example:
See "File Operations" in chapter 3 of Turbo Pascal Reference.
Purpose:
BlockRead reads Count * RecSize bytes from the untyped file F, and places
them in Buf where Buf is typically an array of byte or char of the appropriate
size. RecSize is the record size specified as the optional second parameter to
Reset or Rewrite, or the default value of 128 if no record size is specified.
You may optionally add a Result variable parameter which returns the actual
number of complete records read. In the event that the end of file is reached
in the middle of a record, the last partial record will not be included in the
Result value. If you do not use the Result variable in the call to BlockRead,
you should set the {$I-} compiler directive and check IOResult after ever call
to BlockRead.
See "Disk File Operations" in chapter 2, BlockWrite, IOResult, Reset, Rewrite
BlockWrite procedure
----------------------------------------------------------------
Declaration:
procedure BlockWrite( var F: File; var Buf; Count : Word
[; var Result : Word]);
Example:
See "Disk File Operations" in chapter 3 of Turbo Pascal Reference.
Purpose:
BlockWrite writes Count * RecSize bytes from Buf to the untyped file F.
RecSize is either the default value of 128, or is the record size specified as
the optional second parameter of Reset or Rewrite, and Buf is usually an array
of byte or char values. The optional Result variable parameter returns the
number of complete records actually written to the file. If you do not use the
Result variable in the call to BlockWrite, you should set the {$I-} compiler
directive and check IOResult after ever call to BlockWrite.
See "Disk File Operations" in chapter 3, BlockRead, Reset, Rewrite
CheckBreak
----------------------------------------------------------------
Declaration:
CheckBreak: Boolean; {Default = True}
Unit: Crt
Purpose:
By setting CheckBreak to False, you can disable the Ctrl-Break key, used
to interrupt program execution. When CheckBreak is True, pressing Ctrl-Break
will terminate program execution at the next output sent to the screen.
See GetCBreak, SetCBreak
CheckEOF
----------------------------------------------------------------
Declaration:
CheckEOF : Boolean; {Default = False}
Unit: Crt
Purpose:
If you press Ctrl-Z at the keyboard, an end-of-file character may be
returned to the input, depending on the setting of CheckEof. Setting CheckEof
to True enables end-of-file character generation; setting CheckEof to False
disables this operation.
CheckSnow
----------------------------------------------------------------
Declaration:
CheckSnow: Boolean; {Default = True}
Unit: Crt
Purpose:
The setting of CheckSnow is used in conjunction with the DirectVideo
boolean variable. On older or less expensive CGA color displays, the color
graphics adaptor uses single ported memory. When the video display circuitry
and the CPU both try to access the memory at the same time a video effect
referred to as "snow" appears on the screen. The solution to this problem
involves changing the low level output routines so that the CPU only updates
the video memory area during horizontal or vertical screen retrace intervals.
You don't need to worry about the technical details of all that. However, if,
when running your applications in a color display environment and you see snow
or static on the screen, set CheckSnow to True. As a last resort, you may need
to set DirectVideo to False, however, this will result in extremely slow screen
updates since all screen I/O will be forced to go through the BIOS interface.
According to Borland, the value of CheckSnow defaults to True, initially.
However, I found that on my system, CheckSnow defaults to False. For fastest
video output, you want CheckSnow to be False and DirectVideo to be True,
consistent with avoiding a video snow fall.
See DirectVideo
ChDir procedure
----------------------------------------------------------------
Declaration:
procedure ChDir ( S : String );
Example:
{$I-}
ChDir('\TP\UTILS');
ErrCode := IOResult;
if ErrCode <> 0 then { handle error condition ... }
Purpose:
Changes the current subdirectory to the directory specified by the string
S. ChDir works the same as the DOS commands CD or CHDIR, making the directory
in S the current working directory. You may also include a drive name, by
prefacing the subdirectory pathname with the drive letter, as,
ChrDir ('D:\TP\UTILS');
Chr function
----------------------------------------------------------------
Declaration:
function Chr( X : Byte) : Char;
Example:
var
I : Integer;
S : String;
...
{ Convert all upper case letters to lower case letters }
for I := 1 to Length(S) do
if (S[I]>='A') and (S[I]<='Z') then
S[I] := Chr( Ord(S[I]) + 32 );
Purpose:
Chr (often pronounced "char") is used to translate the integer valued byte
expression to a char-type value. Effectively, Chr converts an ASCII character
code in the range 0 to 255 to a character type. To convert a character value
to an integer, use the Ord function.
See Ord
Close procedure
----------------------------------------------------------------
Declaration:
procedure Close (var F);
Example:
Assign ( OutFile, 'SCRATCH.DAT' );
Rewrite ( OutFile );
....
Close ( OutFile );
Purpose:
When you are finished reading or writing data to a file, that file must be
closed by calling the Close procedure. For output files, Close causes any
remaining internal buffers to be written to disk. Failure to call Close may
result in incomplete data being stored in the file. As with all file
operations, you should se the {$I-} compiler directive and check the value of
IOResult to determine if the Close was successful.
See Append, Assign, Reset, Rewrite
ClrEol procedure
----------------------------------------------------------------
Declaration:
procedure ClrEol;
Unit: Crt
Example:
Gotoxy ( 1, 10 ); { Clear the 10th line down in the screen
or Window }
ClrEol;
Purpose:
Beginning at the current cursor location, ClrEol erases the screen to the
right edge of the screen (or the edge of the viewing window if the Window
procedure has been called), setting the erased area to blanks displayed the
current background color (see TextBackground). By using Gotoxy to position the
cursor, you can use ClrEol to erase portions of lines anywhere on the screen.
See ClrScr, TextBackground, Window
ClrScr procedure
----------------------------------------------------------------
Declaration:
procedure ClrScr;
Unit: Crt
Example:
{ Clear the screen }
ClrScr;
Purpose:
Clears the display screen (or the area within the region defined by the
Window procedure) and sets the screen color to the current TextBackground
color. The cursor position is set to the upper left corner of the screen (or
Window region).
See ClrEol, TextBackground, Window
Concat function
----------------------------------------------------------------
Declaration:
function Concat ( S1 [, S2, ... Sn] : String ) : String;
Example:
S := Concat ( 'Hello', ' World', '!' );
{is equivalent to writing
S := 'Hello' + ' World' + '!';
}
Purpose:
Concat takes a parameter list of string values to be concatenated or
joined together, and appends the second string onto the end of the first, and
the third on to the end of that, and so on. Additional string values, in turn,
are appended to the previously joined values in the list up to a maximum string
length of 255. Any text beyond 255 characters is disgarded and the result
string is truncated to 255 characters.
See Copy, Delete, Insert, Length, Pos
Copy function
----------------------------------------------------------------
Declaration:
function Copy ( S: String; Index : Integer;
Count : Integer ) : String;
Example:
Writeln( Copy( 'ABCDEFGHIJKLMN', 4, 3 ) );
outputs,
DEF
Purpose:
Extracts and returns a subset of string S, beginning at the Index'th
character position and extending for Count bytes. If Index is greater than
Length(S), Copy returns a null string. If Index + Count is greater than
Length(S), then Copy returns all the characters between Index and Length(S).
If you've programmed string operations in the BASIC language, you have
undoubtedly appreciated the convenience of BASIC's LEFT$, MID$ and RIGHT$
functions. Copy is equivalent to MID$. By setting Copy's Index to 1, Copy
operates the same as LEFT$. You can implement a RIGHT$ equivalent function by
writing,
function Right ( S : String; Index: Integer ) : String;
begin
Right := Copy ( S, Length(S) - Index + 1, 255 );
end;
See Concat, Delete, Insert, Length, Pos
Cos function
----------------------------------------------------------------
Declaration:
function Cos( X : Real );
Example:
GetAspectRatio ( Xasp, Yasp );
{ Compute (X,Y) 10% further out than the radius. }
X := Round( 1.1 * Radius * Cos ( AngleInRadians ) );
Y := - Round( 1.1 * Radius * Sin ( AngleInRadians ) *
(Xasp/Yasp));
Purpose:
Computes and returns the cosine of X, where X is an angle measurement in
radians. Note that many of the graphics routines use an angle measurement in
degrees. To convert from degrees to radians, divide the degree measurement by
180 / Pi.
See ArcSin/ArcCos, ArcTan, Sin, Tan
CSeg function
----------------------------------------------------------------
Declaration:
function CSeg : Word;
Purpose:
CSeg returns the value of the 80x86 CS register in use by the code that
called CSeg.
See DSeg, SSeg
Dec function
----------------------------------------------------------------
Declaration:
procedure Dec ( var X [; N : Longint] );
Example:
Dec(I); { Equivalent to I := I - 1; }
Dec(I, Amount); { Equivalent to I := I - Amount; }
Purpose:
If given a single ordinal-type variable parameter, X, Dec uses optimized
code to decrement the value of X by 1 and is equivalent to,
X := X - 1;
If the second parameter N is given, Dec decrements X by N, and is equivalent to
X := X - N;
See Inc, Pred, Succ
Delay procedure
----------------------------------------------------------------
Declaration:
procedure Delay (Ms : Word);
Unit: Crt
Example:
repeat
SetPalette ( Random(GetMaxColors), Random(GetMaxColors));
Delay ( 50 );
until Keypressed;
Purpose:
Delays or pauses execution of the program for approximately the number of
milliseconds specified by the parameter Ms.
Delete procedure
----------------------------------------------------------------
Declaration:
procedure Delete(var S: String; Index: Integer;
Count: Integer);
Example:
var
s : string;
begin
S:='ABCDEFGHIJKLM';
Delete(S,4,3);
Writeln(s);
end.
outputs
ABCGHIJKLM
Purpose:
Removes or deletes a subsection of string S, beginning at the Index'th
position and continuing for Count characters. To delete all of the characters
to the right of and including the Index position, you can substitute 255 for
the Count parameter, like this:
Delete(S, IndexPos, 255);
Since IndexPos + Count exceeds the length of the string, the remaining
characters are deleted. If Index is greater than Length(S) then no characters
are deleted.
See Concat, Copy, Insert, Length, Pos
DelLine procedure
----------------------------------------------------------------
Declaration:
procedure DelLine;
Unit: Crt
Example:
procedure ScrollUp ( Y : Integer; NumLines : Integer );
var
I : Integer;
begin
Gotoxy ( 1, Y );
for I := 1 to NumLines do
DelLine;
end;
Purpose:
Use DelLine to scroll all the lines below the current cursor location up
by 1 line. The routine ScrollUp, shown above, implements a generic scroll up
routine useful in a variety of applications. Since DelLine operates relative
to the current settings of the Window procedure, DelLine can scroll lines
within the Window region on the screen.
See InsLine, Window
DirectVideo variable
----------------------------------------------------------------
Declaration:
DirectVideo: Boolean; {Default = True}
Unit: Crt
Purpose:
Turbo Pascal programs, like most programs written for the PC family of
computers, perform output to the video display by copying their text and video
attributes directly into the video memory. This provides the fastest possible
screen updates. In some situations, this can result in the appearance of
"video snow" or "static". When this occurs, set the CheckSnow variable to True
(See CheckSnow).
By setting DirectVideo to False, programs will perform their output by
calling the BIOS video routines. This results in greatly reduced display
performance.
See CheckSnow
DiskFree function
----------------------------------------------------------------
Declaration:
function DiskFree( Drive: Byte ) : Longint;
Unit: Dos
Purpose:
Where Drive selects a disk drive (0=A, 1=B, 2=C, ...), DiskFree returns
the number of bytes of remaining free space, or -1 if Drive selects a
non-existent drive.
See DiskSize, GetDir
DiskSize function
----------------------------------------------------------------
Declaration:
function DiskSize( Drive: Byte ): Longint;
Unit: Dos
Purpose:
Where Drive selects a disk drive (0=A, 1=B, 2=C, ...), DiskSize returns
the capacity of the drive, in bytes, or -1 if Drive selects a non-existent
drive.
See DiskFree, GetDir
Dispose procedure
----------------------------------------------------------------
Declaration:
procedure Dispose ( var P : Pointer [, Destructor] );
Example:
type
PString = ^String;
var
S : PString;
...
New( S );
S^:='Goodbye World!'';
Dispose (S);
Purpose:
Deallocates the dynamic memory allocation used by the item or object
pointed to by parameter variable P. When disposing of objects (see chapter 5,
"Object Oriented Programming"), an optional second parameter may specify the
name of the destructor method for the object pointed to by P. When used in
this form, Dispose first calls the destructor method of the object prior to
deallocating the the memory pointed to by P.
Important!
After calling Dispose, the value of P is no longer valid. A commom
programming error is to continue using a pointer after it has been deallocated.
Because the pointer may still point to the original location in memory where
the object had been allocated and since that memory may not be immediately
claimed for use by another entity, this will sometimes work temporarily.
However, to do so is a serious programming error and may cause the program to
crash! Don't do it!
When calling Dispose, P must be a valid pointer. If P does not point to
the memory used by the heap system, Dispose will issue a run-time error and
stop execution of the program.
See FreeMem, GetMem, Mark, New, Release
DosError variable
----------------------------------------------------------------
Declaration:
DosError: Integer;
Unit: Dos
Purpose:
DosError contains the DOS result code after performing a DOS procedure
such as FindFirst/FindNext.
DosExitCode function
----------------------------------------------------------------
Declaration:
function DosExitCode : Word;
Unit: Dos
Purpose:
When another program, or COMMAND.COM is executed from within the current
program by calling the Exec procedure, the executed program may return a
DOS-level exit code. The value of this return code may be examined by checking
the result returned by DosExitCode. The return values correspond to the
following:
0=normal termination
1=Subprogram terminated by user pressing Ctrl-C
2=Subprogram terminated due to a DOS device error (e.g. drive door open)
3=Subprogram terminated by the Keep procedure.
See Exec
DosVersion function
----------------------------------------------------------------
Declaration:
function DosVersion : Word;
Unit: Dos
Example:
See FSearch for an example.
Purpose:
To determine the version of DOS used by the computer that the program is
running on, call DosVersion. The low byte returns the main version number and
the high byte returns the minor version number. For example, for DOS 5.0 the
low byte is 5 and the high byte is 0. You can access the high and low bytes
using the Hi and Lo functions, respectively.
See Hi, Lo
DSeg function
----------------------------------------------------------------
Declaration: function DSeg : Word;
Purpose:
Use DSeg to access the current value of the DS register.
See CSeg, SSeg
EnvCount function
----------------------------------------------------------------
Declaration:
function EnvCount : Integer;
Unit: Dos
Example:
for I := 1 to EnvCount do
Writeln ( EnvStr( I ) );
Purpose:
Use EnvCount in conjunction with EnvStr to access the string values stored
in the DOS environment variable area. The DOS environment keeps track of your
PATH=, COMSPEC=, SET= statements and so on. You can access the current values
stored in the DOS environment through the EnvCount variable, which returns the
total number of environment strings (each <variable>=<value> declaration is
treated as a single string), and EnvStr to access the n'th environment string.
See EnvStr, GetEnv
EnvStr function
----------------------------------------------------------------
Declaration:
function EnvStr( Index: Integer );
Unit: Dos
Example:
See EnvCount
Purpose:
When the Index value is in the range of 1 to EnvCount, EnvStr returns the
values of the Index'th environment variable. If Index is out of range, EnvStr
returns a null string. Also see Envcount.
Eof function
----------------------------------------------------------------
Declaration:
function Eof : Boolean;
or
function Eof( var F: Text ) : Boolean;
or
function Eof( var F: File ) : Boolean;
Example:
Program DemoEof;
var
InFile : Text;
TextLine : String;
begin
Assign( Infile, 'TEMP.PAS' );
Reset( Infile );
while not Eof( Infile ) do
begin
Readln( Infile, TextLine );
Writeln( TextLine );
end;
Close( Infile );
end.
Purpose:
Eof is used to detect the end of a file while reading input from the file.
In the first form, if Eof specifies no file parameter, Eof checks the standard
input file and returns True if an end of file condition is detect, otherwise
False. Typing Ctrl-Z at the keyboard sets an Eof condition on the standard
input.
When used with a text file, Eof(F) returns True if the current file
position is past the last character of the file, otherwise False.
When used with a typed or untyped file, Eof(F) returns True if the current
position is past the last record of the file, otherwise False.
Eoln function
----------------------------------------------------------------
Declaration:
function Eoln : Boolean;
or
function Eoln ( var F : Text ) : Boolean;
Example:
while not Eoln do { Reads characters until Enter pressed }
Read(ch);
Purpose:
Whenever Eoln is called, Eoln returns True if the current location in the
file is an end-of-line (or carriage-return) marker, or False if it is not.
Whenused without the file parameter, Eoln checks for the Enter key being
pressed at the keyboard.
Erase procedure
----------------------------------------------------------------
Declaration:
procedure Erase ( var F: File );
Example:
Assign( F, 'KILL-ME.TXT' );
{$I-}
Erase ( F );
ErrCode := IOResult;
if ErrCode <> 0 then { process error condition }
Purpose:
Used in conjunction with Assign, to assign a filename to the file variable
F, Erase deletes the named file from the DOS directory structure. Always
insure that F is closed before calling Erase.
Exec procedure
----------------------------------------------------------------
Declaration:
procedure Exec ( Path, CmdLine : String );
Unit: Dos
Example:
{ For regular, non-Turbo Vision applications, use this example code }
SwapVectors;
Exec( ProgName, ParamStr );
SwapVectors;
{ Use this example code when using Exec from within Turbo Vision applications }
ClrScr;
DoneSysError;
DoneEvents;
DoneVideo;
DoneMemory;
SetMemTop(HeapPtr);
SwapVectors;
Exec( ProgName, ParamStr );
SwapVectors;
SetMemTop(HeapEnd);
InitMemory;
InitVideo;
InitEvents;
InitSysError;
Purpose:
Where Path is the name of a program to execute (with optional drive and
optional subdirectory path), Exec loads and executes the program specified and
passes the contents of the CmdLine parameter to that program. The executed
program can examine the contents of CmdLine as if it had been launched from the
DOS command line (See ParamStr). After control returns from the Exec
procedure, you can call DosExitCode to see if the program ran successfully.
Important! Setting Heap Size
When using the Exec procedure, you must insure that adequate memory is
available to launch the desired program. Normally, Turbo Pascal programs
allocate all of the available free memory to the heap management system. When
this occurs, there's no memory left in which to load and execute another
program!
The solution is to specify the maximum heap size required by your program.
If you are using the IDE, select the Options menu, Memory sizes selection, and
enter a new value for the High heap limit such as 16,384 bytes or what ever is
appropriate for your application. The default value is 655,360 bytes.
You may also imbed a compiler directive {$M} to set memory allocation
within the source code (see Chapters 2 and 3). If using the command line
compilers TPC or TPCX (or BPC), you may set the heap size using the command
line switch /$M to specify the stacksize, and mininum and maximum heap values.
Exit procedure
----------------------------------------------------------------
Declaration:
procedure Exit;
Purpose:
Call Exit to cause a procedure or function to immediately return back to
the calling code (be sure to take into account that you may not have a valid
value assigned for the function result). Exit is often used to prematurely
terminate execution of a subroutine when an error has occurred and has the
equivalent effect of a goto jump to the end statement of the procedure or
function.
When used in the main body of a program, Exit results in termination of
the program.
See ExitProc, Halt
ErrorAddr variable
----------------------------------------------------------------
Declaration:
ErrorAddr: Pointer = nil;
Purpose:
If a program terminates abnormally, ErrorAddr contains the address where
the error occurred, or possibly nil. The variable ExitCode contains the error
code corresponding to the problem that caused the program to terminate. See
ExitProc for details.
ExitCode variable
----------------------------------------------------------------
Declaration:
ExitCode: Integer = 0;
Purpose:
If a program terminates abnormally ExitCode contains the error code
corresponding to the problem that caused program terminatation. An ExitCode of
zero means that no error occurred. See ExitProc for details.
ExitProc variable
----------------------------------------------------------------
Declaration:
ExitProc: Pointer = nil;
Example:
{ Demonstration of installing and using an exit handler procedure. You can use
this code example in your programs. Modify ExitHandler
to check for the conditions that your program requires, to close files, or
whatever exit clean up is needed by your application.
}
var
LastExitProc : Pointer;
procedure ExitHandler; far;
begin
{ Restore previous exit handler address }
ExitProc := LastExitProc;
{ Process exit codes or other operations here }
Writeln('ExitCode=',ExitCode);
if ErrorAddr = nil then
Writeln('ErrorAddr=nil')
else
Writeln('ErrorAddr is not nil');
{If you display an error message here, be sure to clear
the error condition by setting ErrorAddr := nil to
prevent other exit handlers from catching this
error }
end;
begin
{ Install the exit handler procedure }
LastExitProc := ExitProc;
ExitProc := @ExitHandler;
{Main program code goes here as per a normal program}
{If Exit is called in the main section, or Halt is called
anywhere in the program, or a run-time error occurs, then
as part of program termination, your ExitHandler
procedure will be called.}
ErrorAddr := nil;
end.
Purpose:
ExitProc points to a far procedure to be executed as part of the normal or
abnormal termination of your program, or when the Halt procedure is called.
Inside your program's exit handling procedure you can check for abnormal
program termination by examining the values of ExitCode and ErrorAddr. If
ErrorAddr is not equal to nil, then a run-time error occurred and ExitCode
contains the corresponding error code. If ErrorAddr is nil and ExitCode is
non-zero, then the program was terminated by calling Halt and ExitCode is the
value set by the Halt procedure. A normal termination produces values of
ExitCode = 0 and ErrorAddr=nil.
When the program exits, the run-time system calls the procedure pointed to
by ExitProc. Since a program may have more than one exit handler (such as for
each unit), they are strung together in a chain of exit procedures. Upon
return from the ExitProc procedure, the run-time system checks the value of
ExitProc and if non-nil, the run-time system again invokes whatever ExitProc
points to. Eventually, when there are no more error handlers to invoke,
ExitProc is set to nil and the run-time system returns to DOS.
This chain of exit procedures is linked together so that each unit, as
well as the run-time system, may have a chance to perform exit handling clean
up operations. Such operations may include closing files, restoring interrupt
vectors, erasing incomplete files and so on. The chain is constructed by
having each unit or program that installs an exit procedure first save the
address of the existing exit procedure into a local variable before setting
ExitProc equal to the address of the new exit handler. Then, inside the exit
handler, immediately reset ExitProc to the saved value. In this way, when your
exit handler finishes up, it returns to the run-time system with ExitProc now
pointing to the exit handler that was installed before this exit procedure.
Thelast exit procedure in the chain (which is the default exit handler), sets
ExitProc to nil to mark the end of the chain.
The example code above shows how an exit procedure is inserted into a
program. You may also add such code into a unit's initialization section. In
this way, each unit can have its own exit code for cleaning up after itself.
Important! Reset ErrorAddr to nil
If your own program exit code examines and processes the ErrorAddr and
ExitCode results, you should set ErrorAddr to nil before leaving your exit code
procedure. If you fail to do this, an exit handler located elsewhere in the
program or run-time system may also display an error message.
Exp function
----------------------------------------------------------------
Declaration:
function Exp( X: Real ): Real;
Purpose:
Computes and returns the value of e raised to X'th power where Exp(1) is
approximately equal to 2.7182818. To compute an arbitrary A to the X'th power,
use this relation:
AX = exp( X * Ln(A) )
where Ln is the natural logarithm function (see Ln)
See Ln
FExpand function
----------------------------------------------------------------
Declaration:
function FExpand ( Path : PathStr );
Unit: Dos
Purpose:
To determine the current subdirectory, call FExpand, setting Path to a
null string, like this:
Writeln('Current directory is: ', FExpand ('') );
FExpand returns as its result the full drive and subdirectory pathname. If you
set Path to a filename, FExpand adds that filename to the resulting path to
create a fully qualified file name. All values, including Path, are converted
to upper case characters. Any errors encountered are returned through
IOResult.
See FSplit
FilePos function
----------------------------------------------------------------
Declaration:
function FilePos ( var F ): Longint;
Purpose:
FilePos returns the current file position or record number within the open
file F (F may be typed on untyped but not a Text file) The first position in
the file is zero. Any errors encountered are returned through IOResult.
See Seek
FileSize function
----------------------------------------------------------------
Declaration:
function FileSize ( var F ) : Longint;
Example:
var { Display size of a text file }
F: File of Char;
begin
Assign(F,'TEST.PAS');
Reset( F );
Writeln( FileSize( F ));
Readln;
Close ( F );
end.
Purpose:
Where F is an open typed file, FileSize(F) provides the number of
components currently stored in the file. While FileSize does not work on Text
files, you can cheat a little and open a text file as a typed File of Char, as
shown above, and then FileSize returns the number of bytes in the text file.
FillChar procedure
----------------------------------------------------------------
Declaration:
procedure FillChar( var X; Count : Word; Value );
Example:
var
AString : String;
AnArray : Array[1..30] of Integer;
...
FillChar ( AString, SizeOf( AString ), ' ' );
AString[0] := Chr(80);
FillChar ( AnArray, SizeOf( AnArray), 0 );
Purpose:
FillChar copies Value into Count number of bytes of X, where X is a
variable of any type, usually an array or record structure. FillChar is often
used as a fast and easy method of initializing arrays to zero, or strings to
blanks. When initializing string values, make certain that you manually set
the string's length byte, as shown in the example above. You can use FillChar
on part of an array or string by changing the values of X and Count. For
example,
FillChar ( AString[70], 10, ' ' );
sets the last 10 characters of AString to blanks. Be careful not to run off
the end of the buffer to which values are written. To do so is a commom but
difficult to track down problem. Particularly since writing past the end of
one variable will overwrite the contents of the next declared variable in the
var declarations. This is difficult to track down because the problem shows up
as incorrect values in some other variable, not the one on which FillChar is
used!
FindFirst
----------------------------------------------------------------
Declaration:
procedure FindFirst( Path : String; Attr : Word;
var S : SearchRec );
Unit: Dos
Example:
{ This is an excerpt from the TVSHELL8 program in the Borland
Pascal Developer's Guide }
var
DirEntry : SearchRec; { Holds the contents of a
directory entry
consisting of filename, size, etc }
FileCount : Integer;
IsADirectory : Boolean;
begin
FindFirst( Path + '*.*', AnyFile, DirEntry );
FileCount := 0;
while DosError = 0 do
begin
if DirEntry.Name[1] <> '.' then
{Add all names other than those beginning with '.'.
This eliminates our displaying the '.' and '..'
names used by DOS}
begin
IsADirectory := (DirEntry.Attr and Directory) =
Directory;
if IsADirectory and FilesOnly then goto 1;
{ Note that normally Goto's are to be avoided but in
this instance, a single forward jump reduces the
number of boolean conditions that need to be tested}
if not IsADirectory then
DirEntry.Name := LowerCase (DirEntry.Name);
{We convert file names to lowercase and leave
directory names in upper case for ease of reading
the directory listing}
FileCount := FileCount + 1;
Inc(StartingEntry);
DirectoryCollection^.AtInsert(StartingEntry,
New(PDirectoryEntry, Init( SubLevel, FileCount,
DirEntry )));
1:
end; { begin }
FindNext( DirEntry );
end; { begin }
end; {TDirList.ReadDirectory}
Purpose:
FindFirst is used to initiate a directory search (and should be used in
conjunction with FindNext). Path is set to the name of the file to find and
may contain a combination of characters and DOS wildcard characters * and ?.
For example, by setting Path := '*.DOC' you prepare to search for all files
ending in .DOC. You can further narrow the search by specifying a file
attribute, Attr, selected from one of the following constants:
ReadOnly = $01;
Hidden = $02;
SysFile = $04;
VolumeID = $08;
Directory = $10;
Archive = $20;
AnyFile = $3F;
By selecting one of the file attributes you may restrict the search to
directory names only, read-only files, or any type of file. You can determine
if the end of the directory has been reached or no files were found by checking
the DosError function. DosError returns 0 if no error occurred, or non-zero if
an error occurred.
The record S returns the filename and other file attributes of the first
matching file that is located, where SearchRec is defined as:
type
SearchRec = record
Fill: array[1..21] of Byte;
Attr : Byte;
Time : Longint;
Size : Longint;
Name : String[12];
end;
See FExpand, FindNext
FindNext
----------------------------------------------------------------
Declaration:
procedure FindNext (var S: SearchRec );
Unit: Dos
Example:
See FindFirst
Purpose:
FindNext is called after an iniitial FindFirst to find subsequent matching
files. Always check the value of DosError, as described under FindFirst, to
determine if no more matching files can be found in subsequent calls to
FindNext.
See FindFirst
Flush procedure
----------------------------------------------------------------
Declaration:
procedure Flush ( var F: Text );
Purpose:
When you write output to a text file, the data may not be immediately
written to disk. Instead, the data is temporarily stored in an internal memory
buffer. When the buffer becomes full, or the file is closed, the buffer is
physcially transferred to the disk. To force the buffer to be "emptied" to
disk, call the Flush procedure. By calling Flush, you insure that the data on
disk are up to date after each Write or Writeln.
See SetTextBuf
Frac function
----------------------------------------------------------------
Declaration:
function Frac ( X: Real ): Real;
Example:
Writeln( Frac( Pi ):8:7 );
outputs,
0.1415927
Purpose:
Use Frac to obtain the fractional part of a real valued expression. Use
Int(X) to obtain the integer part of the real value.
See Int
FreeMem procedure
----------------------------------------------------------------
Declaration:
procedure FreeMem (var P: Pointer; Size : Word );
Purpose:
FreeMem disposes of the memory block pointed to by P, where P was
initialized by calling GetMem. The Size parameter must be the exact size in
bytes used to request the allocation with GetMem. See Dispose for a discussion
of important restrictions concerning the value of P before and after the
allocation.
See Dispose, GertMem, New
FSearch function
----------------------------------------------------------------
Declaration:
function FSearch( Path: PathStr; DirList: String ) :
PathStr;
Unit: Dos
Example:
1 { FSEARCH.PAS }
2 Program DemoSearch;
3 { Demonstrates an algorithm to locate a program's required data and
4 configuration files through the use of the DosVersion function,
5 ParamStr function, FSplit procedure and FSearch function. This
algorithm
6 assumes that the required config. files are kept in the same directory
7 as the .EXE file.
8 }
9 uses
10 Dos;
11
12 const
13 { This is the filename that we must locate }
14 DataFilename = 'SCRATCH.DAT';
15
16 var
17 Path : PathStr;
18 Directory : DirStr;
19 FName : NameStr;
20 Extension : ExtStr;
21 F : File;
22
23 begin
24
25 Path := '';
26 {$I-}
27 { First, check the current directory }
28 Assign( F, DataFilename );
29 Reset( F );
30 if IoResult <> 0 then
31 { if not found here, then continue checking ... }
32 begin
33 if Lo(DosVersion) >= 3.0 then
34 { if running >= DOS 3.0, then use ParamStr(0) to get location of
35 the .EXE file and assume that directory for the data files }
36 begin
37 FSplit ( ParamStr(0), Directory, FName, Extension );
38 Path := Directory;
39 end
40 else
41 { Otherwise, search through the list of directories in the DOS
42 PATH statement. The .EXE, and hence, its data files, must
43 have been booted from one of these directories. }
44 Path := FSearch ( DataFileName, GetEnv('PATH') );
45 end
46 else
47 Close ( F );
48
49 Writeln('Path = ', Path );
50 end.
Purpose:
FSearch scans through a list of directories, specified by DirList, and
returns either the full filename, including the subdirectory name, or the null
string if the file could not be found.
A typical use of FSearch is when your application first starts to run and
needs to find its various data files. Most applications store their
configuration and other file data in the subdirectory where the .EXE executable
is located. You could, of course, hard code a subdirectory name into your
program, such as 'C:\MYAPP\'. But this precludes letting users place the
application in a directory of their choosing. So instead of hard coding the
subdirectory name, most applications use an algorithm such as the following:
Step 1: First look in the current directory. If the data files are not found,
then continue to Step 2.
Step 2: If running DOS 3.0 or newer, use ParamStr(0) to fetch the full path
and file name of the .EXE that is currently running. Then use FSplit to
extract the subdirectory name and use this as the directory where the data
files should be located.
Step 3: If running an older version of DOS, then search through the list of
subdirectories contained in the DOS PATH statement. In order for the program
to be launched, it must exist in one of the path directories.
See DosVersion, FSplit, Lo, ParamCount, ParamStr
FSplit function
----------------------------------------------------------------
Declaration:
procedure FSplit ( Path : PathStr; var Dir: DirStr;
var Name: NameStr; var Ext: ExtStr );
type
PathStr = String[79];
DirStr = String[67];
NameStr = String[8];
ExtStr = String[4];
Unit: Dos
Example:
See FSearch
Purpose:
Where Path contains a potentially fully qualified filename, including a
leading directory name, FSplit, splits apart the filename and returns 3
separate components:
Dir - the directory name part of the filename
Name - the filename minus the extension
Ext - the filename extension including the leading period character.
If Path does not contain some of the components, such as a filename extension,
then the corresponding return variable is set to the null string ''.
GetCBreak procedure
----------------------------------------------------------------
Declaration:
procedure GetCBreak (var Break: Boolean);
Unit: Dos
Purpose:
The DOS operating system periodically checks for a the Ctrl-Break key
combination being pressed during program execution. As you know, pressing
Ctrl-Break interrupts the flow of program execution. However, the actual
processing of the Ctrl-Break key depends on the state of a DOS internal
variable. GetCBreak returns the current state of this flag: if set to True,
DOS checks for Ctrl-Break at every DOS system call; if False, DOS checks only
during input/output operations to the console (CON:), printer (LPT:) or
communications ports (COMx:). To change the state of Ctrl-Break processing
flag, call SetCBreak. Also see CheckBreak.
GetDate procedure
----------------------------------------------------------------
Declaration:
procedure GetDate(var Year, Month, Day, DayofWeek: Word);
Unit: Dos
Purpose:
GetDate fetches the system date (you were expecting that, weren't you?)
from the current DOS date setting, returning the Year as a value from 1980 to
2099, the Month from 1 to 12, the Day from 1 to 31 and the DayOfWeek value from
0 (Sunday) to 6 (Saturday).
See GetTime, SetDate, SetTime
GetDir procedure
----------------------------------------------------------------
Declaration:
procedure GetDir( D: Byte; var S: String );
Purpose:
Use GetDir to determine the currently active subdirectory on a specific
disk drive. By setting D to 0 for drive A, 1 for drive B, 2 for drive C, and
so forth, GetDir returns the current subdirectory in drive S. The default
return value is '\', even if D specifies an invalid drive, so be certain that D
is an appropriate value for the system on which the program is running.
See ChDir
GetEnv function
----------------------------------------------------------------
Declaration:
function GetEnv(EnvVar : String) : String;
Unit: Dos
Example:
CurrentPath := GetEnv('PATH');
Command := GetEnv('COMSPEC');
Also see FSearch for another example.
Purpose:
DOS maintains a set of environment variables such as PATH, COMSPEC, and so
on. GetEnv looks up and returns the value of the environment variable
specified by EnvVar.
GetFAttr procedure
----------------------------------------------------------------
Declaration:
procedure GetFAttr( var F; var Attr: Word );
Unit: Dos
Example:
Assign(F, 'SCRATCH.DAT' );
GetFAttr( F, Attr );
if (Attr and Archive)<>0 then {archive bit set}
else
if (Attr and ReadOnly)<>0 then {read only file}
...
Purpose:
Every file on the system has associated with it a set of file attributes.
These attributes indicate if the file is read-only, hidden, or perhaps a
directory name. You can obtain a file's attribute settings by calling
GetFAttr, where F is a file variable to which a filename has been assigned with
Assign (but should not be open). The attribute value is returned in Attr, as a
bit pattern. You can check for individual bits using these predefined constant
identifers:
ReadOnly = $01;
Hidden = $02;
SysFile = $04;
VolumeID = $08;
Directory = $10;
Archive = $20;
AnyFile = $3F;
AnyFile is typically used with FindFirst and FindNext and doesn't really have
any use here. Its possible for a file to have more than one attribute bit set,
such as ReadOnly and Hidden, so be sure to check multiple attribute settings if
necessary. Also check DosError in case an error occurs.
You can set specific file attributes by calling SetFAttr. To get and set
the file's access date and time, see GetFTime and SetFTime.
GetFTime procedure
----------------------------------------------------------------
Declaration:
procedure GetFTime(var F; var Time: Longint );
Unit: Dos
Example:
uses dos;
var
F : Text;
LFileInfo : Longint;
DFileInfo : DateTime; { declared in Dos unit }
begin
Assign( F, 'FSEARCH.PAS' );
Reset( F );
GetFTime ( F, LFileInfo );
UnpackTime ( LFileInfo, DFileInfo );
with DFileInfo do
Writeln(Month, '-', Day, '-',
Year, ' ', Hour:2,':',Min:2,':',Sec:2);
Readln;
end.
Purpose:
Every file has associated with it, a date and time stamp indicating when
the file was last written to. You can fetch this date and time information by
calling GetFTime, passing a open file identifier. GetFTime returns the date
and file time packed into a Longint value. Use UnpackTime to translate the
packed representation into individual date and time components (see the example
above, as well as PackTime and UnpackTime).
GetIntVec procedure
----------------------------------------------------------------
Declaration:
procedure GetIntVec(IntNo: Byte; var Vector: Pointer);
Unit: Dos
Purpose:
Use GetIntVec to obtain the current address stored in the interrupt number
IntNo, ranging from 0 up to 255. GetIntVec returns the address as pointer
value in Vector. Call SetIntVec to set a specific interrupt vector.
GetMem procedure
----------------------------------------------------------------
Declaration:
procedure GetMem(var P: Pointer; Size: Word);
Example:
type
TBuffer = Array[0..65521] of char;
PBuffer = ^TBuffer;
var
TextBuffer : PBuffer;
BufSize : Word;
I : Integer;
begin
{ Depending on some condition, such as low memory, or
user command, you
set BufSize at run-time to the exact size of the buffer
that is needed. }
BufSize := 35000;
GetMem ( TextBuffer, BufSize );
{ Perform needed processing on TextBuffer
Be certain that you index the buffer only in the range
from 0
to BufSize. Even though TBuffer is defined to hold up to
65,521 bytes,
we have only allocated enough memory for the first 35,000
bytes. }
For I := 0 to BufSize do
TextBuffer^[I] := ' ';
{ Return the buffer memory back to the free space on the
heap }
FreeMem ( TextBuffer, BufSize );
Readln;
end.
Purpose:
GetMem allocates a memory block from the heap sufficient to hold Size
bytes (up to a maximum of 65,521 bytes), and returns a pointer to the allocated
memory in variable parameter P. While most dynamic variable allocations are
made with the New procedure, you can use GetMem for allocating buffers whose
size is not known until program execution. The example above shows how to
allocate a dynamically sized array of char. You can use this code fragment to
allocate other types of data structures. To allocate a single record, set
BufSize := SizeOf(recordstructuretype). To create a dynamically allocated
array of records, write:
BufSize := SizeOf(recordstructuretype) * MaximumElements;
where MaximumElements is the largest array index that you will need. Its
important when multiplying these values to insure that you do not exceed 65,521
bytes in size. To create an array of other data types, such as Integer,
Longint or Real, substitute the appropriate data type in the SizeOf expression
shown above.
See Dispose, FreeMem, Mark, New, Release
GetTime procedure
----------------------------------------------------------------
Declaration:
procedure GetTime(var Hour, Minute, Second, Sec100: Word);
Unit: Dos
Purpose:
The DOS operating system maintains a system clock to keep track of the
time in resolution down to 100th of a second. By calling GetTime you can
obtain the current values for Hour, Minute, Second and hundredth's of a second.
See GetDate, PackTime, SetDate, SetTime, UnpackTime
GetVerify procedure
----------------------------------------------------------------
Declaration:
procedure GetVerify( var Verify: Boolean );
Unit: Dos
Purpose:
DOS can optionally verify that every disk write operation is correctly
performed by having the disk controller read the disk record back into memory
and comparing the result to what it wrote. You can check the current setting
of the DOS verify flag by calling GetVerify, which returns Verify set to True
when disk writes are being verified, and False if disk writes are not verified.
Disk write verification is, of course, quite time consuming and can be turned
on or off by calling SetVerify. Because of the slowness that this can cause
(all disk writes take twice as long), most DOS users leave verification turned
off.
GotoXY procedure
----------------------------------------------------------------
Declaration:
procedure Gotoxy (X, Y: Byte);
Unit: Crt
Purpose:
Gotoxy moves the text cursor to a new screen location specified by the
coordinate pair (X,Y) (relative to the current settings of the Window
procedure). The screen coordinates range from (1,1) in the upper left corner
to (80,25) at the lower right corner when using the standard 80x25 text screen
size. The maximum values vary depending on the type and mode settings of the
video monitor. X increases from left to right and Y increases from top to
bottom.
You can obtain the current cursor position by calling WhereX and WhereY.
See Window
Halt procedure
----------------------------------------------------------------
Declaration:
procedure Halt [ (ExitCode: Word); ]
Purpose:
Halt stops your program from executing and returns to DOS, optionally
setting the program's exit code to ExitCode. Be sure to see ExitCode and
ExitProc for additional details regarding program exit handling.
See Exit, ExitCode, RunError
HeapError variable
----------------------------------------------------------------
Declaration:
HeapError : is a pointer to a function having this structure
function HeapFunc(Size: Word): Integer; far;
Purpose:
HeapError may be set to point to a special far function to assist with
handling of out of memory errors that may arise when attempting to allocate
dynamic variables with New or GetMem. See "Pointers and Memory Management" in
Chapter 3 for details.
Hi function
----------------------------------------------------------------
Declaration:
function Hi ( X ) : Byte;
Purpose:
Where X is either an Integer or Word value, Hi(X) returns the high byte of
the 2 byte data value. Lo(X) returns the low byte value.
See Lo, Swap
HighVideo procedure
----------------------------------------------------------------
Declaration:
procedure HighVideo;
Unit: Crt
Purpose:
Text is written to the screen in 1 of 8 possible colors (see TextColor).
The values 0 to 7 are the basic color set, with the next 8 values, 8 to 15,
defining high-intensity or bright renditions of the basic color set. When
writing text in one of the basic colors (0 to 7), calling HighVideo effectively
adds 8 to the current text color. This may be turned off by calling LowVideo
or NormVideo.
See LowVideo, NormVideo, TextBackground, TextColor
Inc procedure
----------------------------------------------------------------
Declaration:
procedure Inc (var X [; N: Longint ] );
Purpose:
Inc provides an optimized method of incrementing the value of a variable.
When used in the form Inc(X), the value of X is increased by 1. This is
equivalent to writing,
X := X + 1;
When used in the form Inc(X, N), the value of X is increased by N. This is
equivalent to writing,
X := X+ N;
See Dec
Insert procedure
----------------------------------------------------------------
Declaration:
procedure Insert( Source: String; var S: String;
Index: Integer);
Example:
AString := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
Insert( '0123456789', AString, 14 );
Writeln( AString );
produces this output,
ABCDEFGHIJKLM0123456789NOPQRSTUVWXYZ
Purpose:
Use Insert to place one string inside of another. Insert copies Source
into S starting at Index, pushing the existing characters in S to the right.
See Concat, Copy, Delete, Length, Pos
InsLine procedure
----------------------------------------------------------------
Declaration:
procedure InsLine;
Unit: Crt
Example:
Gotoxy (1, 10);
InsLine; { Insert a blank line at line 10 }
Purpose:
Use InsLine to scroll text on the screen downwards (also see DelLine to
scroll text upwards), inserting a new blank line in the current TextBackground
color. Use Gotoxy to move the cursor to the screen or window location where
the insert line operation should begin. You can use InsLine within a screen
window (see Window) to scroll only a portion of the screen.
See DelLine, Gotoxy, TextBackground, Window
Int function
----------------------------------------------------------------
Declaration:
function Int( X: Real ) : Real;
Purpose:
Removes the fractional part of X and returns the integer portion of X as
the result. For example, Int(Pi) returns 3, Int(-7.,89) returns -7.
See Frac, Round, Trunc
Intr procedure
----------------------------------------------------------------
Declaration:
procedure Intr(IntNo: Byte; var Regs: Registers);
Unit: Dos
Example:
uses
Dos;
const
StartLine = 4; { Top scan line }
EndLine = 8; { Bottom scan line }
var
Reg : Registers;
begin
{ Demonstration of changing the shape of the on-screen
text cursor }
Reg.AH := $01;
Reg.CH := StartLine;
Reg.CL := EndLine;
Intr ( $10, Reg );
Readln;
end.
Purpose:
Use Intr to access the software interrupt specified by IntNo. Regs is of
type Register, which is a case-variant record structure for representing the
CPU registers, defined as:
type
Registers = record
case Integer of
0: (AX, BX, CX, DX, BP, SI, DI, DS, ES, Flags: Word);
1: (Al, AH, BL, BH, CL, CH, DL, DH: Byte);
end;
Note that the SS and SP registers are not available in this structure and
cannot be used in conjunction with BIOS and DOS calls.
The example code, above, uses Int 10H Subfunction 01H Set Cursor Type to
change the shape of the text mode cursor. The cursor shape is defined as a
block between the StartLine and EndLine values, where the top line is line 0
and the bottom or EndLine is determined by the display adaptor and screen
resolution in use. For CGA equivalent displays, characters are 8 pixels high,
hence, these values range from 0 to 7.
For complete details on DOS and BIOS software interrupt function calls,
see DOS Programmer's Reference, by Terry Dettmann and Jim Kyle (Que Books,
1989).
IOResult function
----------------------------------------------------------------
Declaration:
function IOResult : Word;
Example:
repeat
Writeln( 'Enter name of file to open:' );
Readln( FileName );
{$I-}
Assign( F, FileName );
Reset( F );
{$I+} { I usually leave $I- set for the duration of my
programs }
ErrorCode := IOResult;
if ErrorCode <> 0 then
begin
Writeln('Unable to open file ', FileName );
end;
until ErrorCode = 0;
Purpose:
IOResult returns the error code of the last input/output operation. To
use IOResult, you must disable automatic IOResult checking by writing {$I-}
before performing an I/O operation. Then, after each I/O operation you can
manually check the result code returned by IOResult, and take appropriate
action.
Normally, you should copy the value of IOResult to a temporary variable,
like this:
ErrorCode := IOResult;
If ErrorCode <> 0 then {take action}
While you can check IOResult directly, IOResult resets the last error condition
to zero when called. This means if you check the value of IOResult in an
if-then statement, and then in the process of handling the error you again
reference IOResult, the value returned will now be 0! Trying to track this type
of problem is a bit maddening until you realize that IOResult returns the
current error code and then resets itself to zero.
Keep procedure
----------------------------------------------------------------
Declaration:
procedure Keep(ExitCode: Word);
Unit: Dos
Purpose:
Terminates a program but leaves the program resident in memory. Such a
program is a TSR program, which must latch itself onto a interrupt to be
"revivied", and which must be aware of the other considerations that apply to
a TSR program (such as avoiding DOS reentrant code and so on). The ExitCode
parameter value is passed to the Halt standard procedure for indicating an
error condition. DO NOT use this procedure unless you know what you are doing!
You can learn how to write a TSR program entirely in Turbo Pascal by reading
Chapter 9, "Special Programming Techniques: 8087 Usage, Interrupts and TSRs",
in the Borland Pascal Developer's Guide, from Que Books.
KeyPressed function
----------------------------------------------------------------
Declaration:
function KeyPressed : Boolean;
Unit: Crt
Example:
repeat
{ Do any operations repeatedly here }
until KeyPressed;
Purpose:
KeyPressed returns True if a keyboard character has been typed, False
otherwise. KeyPressed is useful for executing a section of code until a
character is typed at the keyboard. KeyPressed only tells you that 1 or more
characters have been typed; you need to call Read, Readln or ReadKey to read
the input.
See ReadKey
Length function
----------------------------------------------------------------
Declaration:
function Length ( S : String );
Example:
Writeln( Length ('ABCDEFGHIJKLMNOPQRSTUVWXYZ') );
outputs,
26
Purpose:
Length(S) returns the current value of the length byte of S, which is the
actual length of the string that is stored in S. SizeOf returns the total
storage occupied by S. If, for example, S is declared as,
var
S : String[80];
then SizeOf(S) returns 81 (80 bytes plus the length byte), and Length(S)
returns a value from 0 to 80, depending upon the current contents of the
string.
See SizeOf
Ln function
----------------------------------------------------------------
Declaration:
function Ln( X : Real );
Purpose:
Returns the natural logarithm of X. To compute the base 10 logarithm of
an expression, define a new function like this:
function Log10 ( X : Real ): Real;
begin
Log10 := Ln(X) / Ln(10);
end;
See Exp
Lo function
----------------------------------------------------------------
Declaration:
function Lo(X): Byte;
Purpose:
Returns the low byte of X, where X is either an Integer or Word value.
Thefunction Hi(X) returns the corresponding high byte.
See Hi, Swap
LowVideo procedure
----------------------------------------------------------------
Declaration:
procedure LowVideo;
Unit: Crt
Purpose:
Performs the inverse of HighVideo by subtracting 8 from the text
attribute's foreground color, translating color values in the range 8 to 15
down to 0 to 7. See HighVideo for more details.
See HighVideo, NormVideo, TextColor
Lst file
----------------------------------------------------------------
Declaration:
Lst : Text;
Unit: Printer
Purpose:
The Printer unit provides a special Lst file identifier for easy printer
output. All you need do to use Lst, is use the Printer unit in your program or
unit's uses statement. Thereafter, to send output to the printer, specify Lst
as the file identifier in your Write or Writeln statements. You do not need to
open or close the printer as this is handled automatically by the Printer
unit's internal initialization section.
See Write, Writeln
Mark procedure
----------------------------------------------------------------
Declaration:
procedure Mark (var P: Pointer);
Purpose:
Copies the current value of the heap pointer to P. Mark, together with
Release, enable you to dynamically allocate a group of objects, and then
dispose of them in a single call to Release. See "The Use of Mark and Release
Procedures" in Chapter 3, for full details.
MaxAvail function
----------------------------------------------------------------
Declaration:
function MaxAvail : Longint;
Purpose:
During program execution, the heap memory area may become fragmented with
blocks allocated here and there. By calling MaxAvail you can determine the
size, in bytes, of the largest free block available for allocation. A related
function, MemAvail, returns the total number of free bytes available in the
heap.
MemAvail function
----------------------------------------------------------------
Declaration:
function MemAvail : Longint;
Purpose:
Returns the total number of free bytes in the heap. Note that you may not
be able to allocate a dynamic variable as large as MemAvail because the heap
may be fragmented. You can determine the largest possible free block by
calling MaxAvail.
A common use for MemAvail is to periodically check your memory allocation
and deallocation. If you find that MemAvail is constantly increasing durng
program execution, you may be dynamically allocating a variable and never
disposing of the memory block. Eventually, your program will run out of memory
and be halted.
You may also wish to place MemAvail checks at key points within your
program. For example, before calling a procedure that makes a large number of
dynamic memory allocations, save the contents of MemAvail in another variable.
Then, upon return from the procedure, compare MemAvail to the saved value. If
they are not the same, this is a sign that somewhere within the called
procedure, or perhaps a procedure called by it, memory is not being properly
disposed.
Mkdir procedure
----------------------------------------------------------------
Declaration:
procedure MkDir(S: String);
Example:
var
DirName : String;
ErrorCode : Integer;
begin
repeat
Write('Enter name of directory to make: ');
Readln( DirName );
if DirName <> '' then
begin
{$I-}
MkDir ( DirName );
ErrorCode := IOResult;
if ErrorCode <> 0 then
Writeln('Error creating directory ', DirName )
else
Writeln('Directory ', DirName,
' has been created.');
end;
until DirName = '';
end.
Purpose:
To create or make a subdirectory, call MkDir, setting the parameter S to
the name of the directory to create. S may specify a full path, such as
'C:\TP\UTILS\GRAPHICS' or a simple directory name such as 'GRAPHICS' which
creates subdirectory 'GRAPHICS' in the current subdirectory.
The directory name specified may not be the name of an existing file. You
can check for errors by setting {$I-} and examining the value returned by
IOResult.
Move procedure
----------------------------------------------------------------
Declaration:
procedure Move (var Source, Dest; Count : Word);
Example:
1 { DEMOMOVE.PAS }
2 program MoveDemo;
3 { Demonstrates how Move procedure can be used to move large numbers
4 of bytes around inside an array. This demo stores lines of text
5 into a large TextArray. New lines are added by calling AddLine, which
6 calls MakeAHole to slide the existing data in the TextArray to make
7 room for new text. AddLine then uses Move to copy the string data
8 into TextArray. Data is fetched using the procedure GetLine.
9 The variable CurSize keeps track of how many bytes of TextArray are
10 currently in use. CurLocation keeps track of the current position; if we
11 were writing a text editor based on this approach, CurLocation would
index
12 into TextArray where the editor's cursor appears on the screen. In other
13 word, the next new line that we type would be inserted at CurLocation.
14 }
15
16 const
17 MaxSize = 32000;
18 MARKER = 13;
19
20 var
21 TextArray : Array[0..MaxSize] of Char;
22 CurSize : Word;
23 CurLocation : Word;
24
25
26 procedure MakeAHole ( Address : Word; Size : Word );
27 { Slides data in the TextArray sideways, leaving a "hole" to fill
28 with new data }
29 begin
30 Move( TextArray[Address], TextArray[Address+Size], CurSize - Address +
1 );
31 end;
32
33
34
35 procedure AddLine ( var Address : Word; S : String );
36 { Adds the contents of S to the TextArray, starting at location Address }
37 var
38 NumBytes : Integer;
39 begin
40 NumBytes := Length(S) + 1;
41 S[0] := Chr(MARKER);
42 MakeAHole ( Address, NumBytes );
43 Move( S[0], TextArray[Address], NumBytes );
44 CurSize := CurSize + NumBytes;
45 Address := Address + NumBytes;
46 end;
47
48
49
50 procedure GetLine ( Address : Word; var S : String );
51 { On entry, Address points to a MARKER character in the text array.
GetLine
52 copies the text between this marker and the next marker (or end of array)
53 to S. }
54 var
55 TempAddr : Word;
56 begin
57 TempAddr := Address + 1;
58 while (TempAddr <= CurSize) and
59 (TextArray[TempAddr] <> Chr(MARKER)) do
60 Inc(TempAddr);
61 Move ( TextArray[Address+1], S[1], TempAddr - Address );
62 S[0] := chr( TempAddr - Address );
63 end;
64
65
66 procedure MoveAhead (var Address : Word );
67 { Where address points to some location in TextArray, MoveAhead positions
68 Address to the index location of the next Marker character. }
69 begin
70 if TextArray[Address] = chr(MARKER) then
71 Inc(Address);
72 while (Address <= CurSize) and
73 (TextArray[Address] <> Chr(MARKER)) do
74 Inc(Address);
75 end;
76
77
78 var
79 I : Integer;
80 ALine : String;
81
82 begin
83 CurSize := 0;
84 CurLocation := 0;
85
86 { Add some sample data into TextArray }
87 AddLine ( CurLocation, 'Line 1 I''m the first line of data');
88 AddLine ( CurLocation, 'Line 2 and I''m the second!');
89 AddLine ( CurLocation, 'Line 3 The quick brown fox jumped over the');
90 AddLine ( CurLocation, 'Line 4 lazy brown dog and fell and hurt
herself.');
91
92 CurLocation := 0;
93 MoveAhead ( CurLocation );
94 AddLine ( CurLocation, 'One more line!!!!!');
95
96 CurLocation := 0;
97 for I := 1 to 5 do
98 begin
99 GetLine ( CurLocation, ALine );
100 Writeln( ALine );
101 MoveAhead ( CurLocation );
102 end;
103
104 readln;
105 end.
Purpose:
Move copies a block of bytes of Count size from Source to Dest. Move uses
optimized assembly language to provide extremely fast copies of potentially
large amounts of data and is particular useful for sliding values around inside
large text arrays, such as might be used in a text editor (see example, above).
Important! Range Checking!
Move does not perform range checking. You may, for instance, move 30,000
bytes into a 255 character string. And Move will go ahead and do just that,
writing over portions of your run-time stack, other variables, and generally
anything else that gets in the way. So be careful!
MsDos procedure
----------------------------------------------------------------
Declaration:
procedure MsDos (var Regs: Registers );
Unit: Dos
Example:
uses
Dos;
var
Reg : Registers;
begin
{ Call the DOS Int 21H Function 0EH Select Disk function
to determine
the maximum number of drives permitted for the system;
this
is equivalent to the number of logical drives on the
system, or
the LASTDRIVE value in the CONFIG.SYS file, or a default
of 5
if LASTDRIVE (approximately) }
Reg.AH := $0E;
Reg.DL := $00;
MsDos( Reg );
Writeln( 'Total Drives=', Reg.AL );
end.
Purpose:
MsDos access the DOS-functions available through software interrupt 21H.
While most of the especially useful DOS-level functions are available through
Turbo Pascal library routines such as GetFTime, SetDate, and so on, you can
access some of the other functions using the MsDos procedure call mechanism.
The variable parameter Regs defines a case variant record structure for
representing the CPU registers, where Register is defined as:
type
Registers = record
case Integer of
0: (AX, BX, CX, DX, BP, SI, DI, DS, ES, Flags: Word);
1: (Al, AH, BL, BH, CL, CH, DL, DH: Byte);
end;
Note that the SS and SP registers are not available in this structure and
cannot be used in conjunction with MsDos calls. For complete details on DOS
function calls, see DOS Programmer's Reference, by Terry Dettmann and Jim Kyle
(Que Books, 1989).
New procedure
----------------------------------------------------------------
Declaration:
procedure New( var P: Pointer [, Init: constructor ] );
Example:
See "The Pointer type" in Chapter 3 of the Turbo Pascal Reference.
Purpose:
Dynamic variable allocations and dynamic object creations are performed
with New. New allocates a memory block, from the heap memory area, and sets P
to point to the memory block. If P points to an object, you can optionally add
the name of the object's constructor method and it will be called immediately
after the memory is allocated. This provides a short hand method of
simultaneously allocating and initializing the object's fields and virtual
method table.
The New procedure may fail if there is insufficient memory in the heap to
allocate the new block. Normally, this results in a run-time error that
terminates the program. However, by setting the HeapError variable to point to
your own heap error handler, your program can take steps to gracefully recover
from out of memory conditions. See HeapError in this section, and chapter 3,
"Pointers and Memory Management" for tips on trapping the out of memory error
condition.
You must make certain that you dispose of allocated memory blocks once
they are no longer needed (see Dispose). If you fail to dispose of a memory
block it continues to occupy memory space and can contribute to your program's
running of out memory.
Since a pointer variable "points" to a memory block, you reference the
thing that P points to by typing P^. This is described in chapter 3.
See Dispose, FreeMem, GetMem
NormVideo procedure
----------------------------------------------------------------
Declaration:
procedure NormVideo;
Unit: Crt
Purpose:
Resets the current text attribute to the original text attribute that was
in use when the program was launched. Specifically, when the program is
started, the value of the text attribute where the cursor is located is saved.
You can use NormVideo to restore this original text attribute at program exit.
By doing so, the screen image will be reset to whatever screen attributes were
in effect when the program was started (or specifically, the screen attribute
at the cursor's location when the program was started).
See HighVideo, LowVideo, TextBackground, Textcolor
NoSound procedure
----------------------------------------------------------------
Declaration:
procedure NoSound;
Unit: Crt
Purpose:
NoSound is used in conjunction with the Sound procedure. Sound turns on
the speaker and emits a user selected tone. To turn off the speaker, call
NoSound.
See Sound
Odd function
----------------------------------------------------------------
Declaration:
function Odd( X: Longint ): Boolean;
Purpose:
Odd returns True if its parameter is an odd number, or False if its
parameter is an even number. Sort of an odd function.
Ofs function
----------------------------------------------------------------
Declaration:
function Ofs( X ): Word;
Purpose:
Where X is any type of variable, Ofs(X) produces the offset portion of the
variable's address. All 80x86 addresses consist of a segment:offset word pair.
The two values are added together to produce the actual physical memory
address. To find the corresponding segment value, call Seg(X).
See Addr, Seg
Ord function
----------------------------------------------------------------
Declaration:
function Ord( X ): Longint;
Example:
var
I : Integer;
S : String;
...
{ Convert all upper case letters to lower case letters }
for I := 1 to Length(S) do
if (S[I]>='A') and (S[I]<='Z') then
S[I] := Chr( Ord(S[I]) + 32 );
Purpose:
Ord translates its parameter X to a Longint value reprsenting X's
ordinality. For example, Ord('A') returns a value of 65, because A is the
sixty-fifth value in the set of characters (this also coincides with 'A's ASCII
code value). The sample code shown above uses Ord to convert a character value
to its ASCII code. Since the capital letter 'A' has an ASCII value of 65, and
the lower case letter 'A' has an ASCII code of 97, adding 32 to the ordinal
value of a character is equivlant to converting the character to lower case.
Chr converts the integer result back to a character value.
If you have an ordinal type declared as,
type
DaysOfTheWeek= (Sun,Mon,Tue,Wed,Thu,Fri,Sat);
var
Day : DaysOfTheWeek;
And then the code,
Day := Tue;
Writeln(Ord(Day));
The output will be:
2
since the ordinal values of DaysOfTheWeek are:
Sun 0
Mon 1
Tue 2
Wed 3
Thu 4
Fri 5
Sat 6
PackTime procedure
----------------------------------------------------------------
Declaration:
procedure PackTime(var DT: DateTime; var Time: Longint);
Unit: Dos
Example:
uses dos;
var
F : Text;
LFileInfo : Longint;
DFileInfo : DateTime; { declared in Dos unit }
begin
Assign( F, 'FSEARCH.PAS' );
Reset( F );
GetFTime ( F, LFileInfo );
UnpackTime ( LFileInfo, DFileInfo );
with DFileInfo do
Writeln(Month, '-', Day, '-', Year,
' ',Hour:2,':',Min:2,':',Sec:2);
{ Change file's date to 1992 }
DFileInfo.Year := 1992;
PackTime ( DFileInfo, LFileInfo );
SetFTime ( F, LFileInfo );
Readln;
end.
Purpose:
PackTime converts a date and time record DT, containing individual values
for Year, Month, Day, Hour, Min and Sec, into a 4 byte Longint reprsentation
and returns the result in parameter variable Time.
PackTime is used with UnpackTime, for encoding and decoding the date and
time data returned or set by GetFTime and SetFTime, respectively. You can write
a program, such as the sample program above, to pre- or post-date files, as
needed. When that important project needs to be done on a Friday and you find
yourself feverishly coding through late weekend hours, you still might be able
to convince your boss that you really did finish the job on Friday!
See GetFTime, SetFTime, UnpackTime
ParamCount function
----------------------------------------------------------------
Declaration:
function ParamCount : Word;
Purpose:
When you start up a program from the DOS command line, you can add a
number of comand line parameters that are accessible from your program (see
ParamStr). ParamCount returns the total number of command line parameters
entered on the command line.
ParamStr function
----------------------------------------------------------------
Declaration:
function ParamStr( Index: Word ) : String;
Purpose:
When you start up a program from the DOS command line, you can add a
number of comand line parameters that are accessible from your program. These
command line parameters might be filenames, starting directories or any other
values that your application requires. For example, the command line compiler
TPC has a large variety of command line options that may be specified when
starting the compiler. Inside your application, you can fetch each of the
command line parameters by calling ParamStr and setting Index to choose a
particular parameter.
Normally, you should restrict the value of Index to the range of 1 to
ParamCount, where ParamCount returns the total number of command line
parameters. Invalid values for Index result in a null string being returned by
ParamStr. On DOS 3.0 and later, ParamStr(0) provides the name of the program
that is currently executing. ParamStr(0) is especially useful when an
application must find the subdirectory from where it was launched.
See ParamCount
Pi function
----------------------------------------------------------------
Declaration: function Pi : Real;
Purpose:
Pi returns the constant value 3.1415926535897932385, where the exact
precision depends on the math emulation or math processor mode that is in use.
Port/PortW pseudo arrays
----------------------------------------------------------------
Declaration:
When used for output:
Port[ Index ] := <byte valued expression>
PortW[ Index ] := <word valued expression>
When used for input:
<Result> := Port[ Index ];
<Result> := PortW[ Index ];
Example:
{ Assign the value of Databyte to I/O address $3F8 }
Port[$3F8] := Databyte;
Purpose:
Port and PortW act like arrays whose index corresponds to a hardware I/O
port. The index value ranges from 0 up to 65,535. By using Port for byte
values and PortW for word values, these pseudo-array variables are used to
write high level language implementations of hardware device drivers, such as
serial port access routines. PortW is used to access a word value.
Port and PortW are not really arrays but Pascal level access mechanisms
for the low-level data ports. As such, Port and PortW should only be used to
the left of an assignment statement or as a component in an expression. They
cannot be used as variable parameters to any procedure or function.
Pos function
----------------------------------------------------------------
Declaration:
function Pos ( Substr, S: String ): Byte;
Example:
{ This examples uses the Pos() function to implement
a string replacement routine }
function Replace ( SearchFor, ReplaceWith,
InThis : String ): String;
{ Finds every occurrence of SearchFor within InThis, and
changes each occurrence to the value of ReplaceWith.
This function solves the problem recursively. Once it finds
an occurrence of SearchFor, it makes the first replacement
and then calls itself on the remainder of the string.}
var
Index : Integer;
begin
Index := Pos (SearchFor, InThis);
if Index > 0 then
Replace := Copy ( InThis, 1,
Pos(Searchfor, InThis) - 1) +
ReplaceWith +
Replace( SearchFor, ReplaceWith,
Copy( InThis, Index + Length(Searchfor),255 ));
else
Replace := InThis;
end;
Example Usage of Replace:
Writeln(
Replace('e', '*',
'The quick brown fox jumped over the lazy dog.');
outputs,
Th* quick brown fox jump*d ov*r the lazy dog.
Purpose:
When you need to search for a substring within another string, use the Pos
function. Pos scans through string S searching for an occurrence of Substr.
Iffound, Pos returns the character index in S where Substr begins. If not
found, Pos returns 0.
The example function Replace, above, is a handy routine to perform a "find
and replace" operation on strings. Replace uses Pos to find the first
occurence of the Searchfor string, replaces it with ReplaceWith, and then calls
Replace recursively to change the remainder of the string.
Pred function
----------------------------------------------------------------
Declaration:
function Pred( X ) : <same type as X>;
Example:
type
DaysOfTheWeek= (Sun,Mon,Tue,Wed,Thu,Fri,Sat);
var
Day : DaysOfTheWeek;
...
Day := Tue;
Day := Pred( Day ); { Sets Day to Mon }
Purpose:
Pred(X) sets X to the predecessor value in the ordinal valued set from
which X is derived. In the case of an integer or word value, Pred is
equivalent to the Dec function. Some additional examples:
Pred(10) = 9
Pred('B') = 'A'
See Dec, Inc, Succ
PrefixSeg variable
----------------------------------------------------------------
Declaration:
PrefixSeg: Word = 0;
Purpose:
PrefixSeg contains the segment address of the Program Segment Prefix
(PSP). The PSP contains information about the program loaded in memory,
including the command line that was used to load the program (so the program
can access command line parameters), pointers to the memory blocks used by the
program and other information. PrefixSeg is used in the example TSR program
shown in Chapter 11 of this book. For further details about the data contained
in the PSP, consult Appendix F of DOS Programmer's Reference, 2nd edition, Que
Books, 1989.
Ptr function
----------------------------------------------------------------
Declaration:
function Ptr( Seg, Ofs : Word) : Pointer;
Example:
{ Using Ptr to manufacture a pointer into the DOS data area
to obtain the number of Kbytes of low memory available to
DOS. On most systems today, this will always
be 640k bytes. }
var
DOSMemory : word;
begin
DOSMemory:= Word(Ptr( $40, 19 )^);
Writeln('Low DOS Memory, in k bytes=', DOSMemory);
end.
Purpose:
Ptr is used to create a pointer to a specific memory address, specified by
Seg:Ofs.
Random function
----------------------------------------------------------------
Declaration:
function Random [ (Range: Word) ] : Word
or
function Random [ (Range: Word) ] : Real;
Example:
{ On an EGA or VGA monitor, randomly rearrange the colors in
the palette }
Randomize;
repeat
SetPalette( Random(GetMaxColors), Random(GetMaxColors));
Delay ( 50 );
until Keypressed;
Purpose:
Random produces a pseudo-random sequence of numbers. In its default
usage, Random returns a Real random value between 0 and 1 ( 0<= Random < 1).
Each subsequent call to Random returns another number in the pseudo-random
sequence.
If you specify a Range value, Random returns a Word value betetween 0 up
to Range ( 0<= Random < Range). For instance, Random(10) returns random values
in the range of 0 to 9.
The specific sequence generated by Random depends upon the initial value
of the RandSeed variable, which is set by Randomize. If you do not call
Randomize at the start of your program, every time that your program executes
it will generate the same random number sequence.
Randomize procedure
----------------------------------------------------------------
Declaration:
procedure Randomize;
Purpose:
Randomize sets the RandSeed variable to a value translated from the
current system clock time. Generally you will wish to call Randomize at the
start of your program. If you do not call Randomize, your program will
generate the same random number sequence each time that it is executed. You
can select a specific random number sequence by initializing the RandSeed
variable to a value of your own choosing. See the description of RandSeed.
RandSeed variable
----------------------------------------------------------------
Declaration:
RandSeed : Longint;
Example:
RandSeed := 99879;
repeat
SetPalette( Random(GetMaxColors), Random(GetMaxColors) );
Delay ( 50 );
until Keypressed;
Purpose:
RandSeed contains the random number generator seed value. By explicitly
setting RandSeed to a value of your choosing, you can repeatedly generate the
same random number sequence.
Read procedure
----------------------------------------------------------------
Purpose:
The Read procedure inputs values from the keyboard or text file and
assigns the values to variables. When used on typed files, Read reads the next
file component into a variable.
By setting {$I-}, you can manually check for errors that may occur when
reading data by checking the result code from IOResult.
Text files
Declaration:
procedure Read( [var F: Text; ] V1 [, V2, ..., Vn ] );
Description:
When reading data from a text file or the system input (keyboard) file,
the behavior of Read depends on the data type of the variables to receive the
data and the position of the file pointer (for example, at end of file). The
basic operation is to copy data from the input, convert if necessary to the
appropriate format, and place into one of the parameter variables. Read may
have from 1 to many variables specified, and the variable type may be different
for each of the variables. For example, to read 2 integers and a single real
value, write:
var
N1, N2 : Integer;
X : Real;
...
Read( N1, N2, X );
You should type the response to this input using blanks, tabs or the Enter key
to separate each of the values, such as,
57 68 2345.987
Interestingly, you may use the Enter key to separate each value, such as,
57 <Enter>
68 <Enter>
2345.987 <Enter>
Important! The Dangling Enter key!
In the previous example, the last <Enter> remains in the input buffer.
Forthis reason, when reading input from the keyboard, it is recommended that
you use the Readln procedure instead of Read. Readln behaves identically to
Read except that Readln swallows and disgards the Enter key.
From a user interface perspective, it would be preferable to allow numeric
input values to be separated by the comma "," character. Unfortunately, Readln
does not support this capability.
The details of how Read performs on the various data types are described
in the following sections. Also see the closely related procedure, Readln, and
the output procedures Write and Writeln.
String
Read copies input characters to the string variable, until it encounters
an end-of-line or end-of-file condition. The end-of-line character is never
included in the data copied to the string variable. When reading data from a
text file, the next Read operation begins at the previous end-of-line
character. Thinking that it is at the end of another line, Read returns a null
string. The result of this is that Read only reads the first line and then
gets stuck on the end-of-line character. The solution is to use Readln for
reading successive lines of text.
If the input line exceeds the defined maximum length for the string
variable, then only that portion of the text that will fit is read into the
string variable. The remaining text out to the next end-of-line character is
disgarded.
Integer
When reading integer values to an integer variable, Read skips over
leading blanks and tabs and then reads until encountering the next blank, tab,
end-of-line character or end-of-file. The characters that is has read are then
converted to an integer value. If these characters do not correspond to the
proper format for an integer, an error condition occurs. You can trap these
errors by setting {$I-} and checking the value of IOResult.
If the end-of-file is reached while reading the characters that make up an
integer value, then the integer value is set to 0.
Real
When reading real number values to a real variable, Read skips over
leading blanks and tabs and then reads characters until encountering the next
blank, tab, end-of-line character or end-of-file. The characters that it has
read, assuming that they correspond to the proper format for a real constant
are then converted to a real value and assigned to the variable. If the
characters have an invalid format for a real constant, then an error occurs.
Char
Read (Ch), where Ch is a Char data type, reads the next single character
from the file and copies the character to Ch. If the file is positioned at the
end of file, Ch is set to Chr(26) to mark the end-of-file. If the file pointer
is positioned on an end-of-line character, then Ch is set to Chr(13). Note
that while you can use Read(Ch) to read an individual character from the
standard input or keyboard, you must still press the Enter key to terminate the
input. If you wish to read invididual keystrokes without having to press
Enter, use the ReadKey function.
Typed files
Declaration:
procedure Read ( F, V1 [, V2, ..., Vn ] );
Description:
In this form, Read is used to read individual recordor (or file
components) from a disk file. You can read the data in the file sequentially,
by specifying multiple data values, or by repeatedly calling Read. After each
record is read, the file pointer is advanced to the next record in the file.
Toread records at random locations, call Seek to reposition the file pointer to
a new location in the file. As with all I/O operations, you can manually check
for I/O errors by setting the {$I-} compiler option and checking the result
value returned by IOResult.
For further information on record file operations, see chapter 3, "Disk
File operations".
See Seek, Write
ReadKey function
----------------------------------------------------------------
Declaration:
function ReadKey : Char;
Unit: Crt
Example:
1 { KEYTEST.PAS }
2 Program KeyTest;
3 Uses
4 Crt;
5 Var
6 Code : Integer;
7
8
9 Function GetKey : Integer;
10 { Pauses for input of a single keystroke from the keyboard and returns
11 the ASCII value. In the case where an Extended keyboard key is
pressed,
12 GetKey returns the ScanCode + 256. The Turbo Pascal ReadKey function
13 is called to perform the keystroke input. This routine returns a 0
14 when an Extended key has been typed (e.g. left or right arrow) and we
15 must read the next byte to determined the Scan code.
16 }
17 Var
18 Ch : Char;
19 Begin
20 Ch := ReadKey;
21 If Ord(Ch) <> 0 Then
22 GetKey := Ord(Ch) { Return normal ASCII value }
23 Else
24 Begin
25 { Read the DOS Extended SCAN code that follows }
26 GetKey := Ord(ReadKey) + 256;
27 End;
28 End;{GetKey}
29
30 Begin
31 Repeat
32 Code := GetKey;
33 Writeln(Code);
34 Until Code = 27;
35 End.
Purpose:
If a key has already been entered, ReadKey returns the key that was typed.
Otherwise, ReadKey waits for a key to be pressed on the keyboard. In both
cases, the key that is entered is not echoed to the screen.
Normal characters having ASCII codes from 1 to 255 are returned by
ReadKey. However, the IBM PC supports additional character codes in order to
recognize the function keys, Ins, Del, and so on. When one of these extended
keyboard characters is typed at the keyboard, ReadKey returns Chr(0) and you
must then call ReadKey a second time to read the actual scan code. The
function GetKey, shown in the example above, provides a simple routine to read
both normal and extended IBM keyboard values.
Readln procedure
----------------------------------------------------------------
Declaration:
procedure Readln( [var F: Text; ] [V1 , V2, ..., Vn ] );
Purpose:
Readln is identical to Read except that after reading the input data,
Readln causes the file pointer to advance to the start of the next line (just
after the previous end-of-line marker).
Unlike Read, you can call Readln with no parameters and Readln disgards
all input characters up to the next end-of-line. Readln, without parameters,
is often used to wait for the user to press the Enter key, like this:
Write('Press Enter to continue.');
Readln;
Release procedure
----------------------------------------------------------------
Declaration:
procedure Release (var P: Pointer);
Purpose:
Release resets the top of heap pointer to the value in P, which should
have been initialized previously with a call to Mark. See "The Use of Mark and
Release Procedures" in Chapter 3, "The Turbo Pascal Language" of the Turbo
Pascal Reference.
Rename procedure
----------------------------------------------------------------
Declaration:
procedure Rename(var F; Newname : String );
Example:
var
OldName: String;
NewName: String;
F: File;
begin
Write('Old filename: ');
Readln( OldName );
Write('New filename: ');
Readln( NewName );
Assign(F, OldName);
Rename(F, NewName );
end.
Purpose:
With a filename assigned to file identifier F (using Assign), call Rename
to change the name of the file to Newname. F must not be open. Interestingly,
if NewName contains a directory name in addition to the filename, you can use
Rename to move a file from one directory to another directory, with or without
a name change. Further, this move is nearly instantaneous, is handled
internally by DOS shifting its internal file directory around, not by actually
copying the entire file from one directory to another. For example, to move
MYFILE from the current subdirectory to the \TOOLS subdirectory, write,
Assign( F, 'MYFILE' );
Rename( F, '\TOOLS\MYFILE' );
Reset procedure
----------------------------------------------------------------
Declaration:
procedure Reset (var F [: File; RecSize: Word] );
Example:
See "Disk file operations" in Chapter 3, "The Turbo Pascal Language".
Purpose:
Reset opens an existing file of any type for subsequent reading or writing
of data and positions the file pointer to the beginning of the file. In the
case of text files, Reset sets the file to read-only; if you wish to write to a
text file, use either Append or Rewrite to open the file. Prior to calling
Reset, you should assign a filename to the file identifier by calling Assign (a
null filename '' may be used to open the standard input file).
The parameter RecSize may only be used with untyped files only and
specifies a record size to be used when reading or writing blocks of data. If
unspecified, the default record size is 128 bytes. See BlockRead/BlockWrite
for additional details on block I/O.
If the file does not exist, Reset produces an I/O error that can be
trapped by setting the {$I-} compiler directive and manually checking the
IOResult return value.
See Append, Assign, Close, Rewrite, Truncate
Rewrite procedure
----------------------------------------------------------------
Declaration:
procedure Rewrite (var F [: File; RecSize: Word] );
Example:
See "Disk file operations" in Chapter 3, "The Turbo Pascal Language" of
The Turbo Pascal Reference.
Purpose:
Rewrite creates a new file. Prior to calling Rewrite, you should call
Assign to associate a filename (a null filename '' specifies the standard
output file) with the file identifier F. Rewrite creates a new disk file,
erasing any previous file with the same name, and in the case of a text file,
makes the file available for write-only access.
For untyped files, you can specify a record size parameter in RecSize (see
BlockRead/BlockWrite). If unspecified, the default record size is 128 bytes.
See Append, Assign, Close, Reset, Truncate
RmDir procedure
----------------------------------------------------------------
Declaration:
procedure RmDir ( S: String );
Purpose:
Use RmDir to delete an existing - and empty of any files - subdirectory.
Sspecifies the name of the directory to delete. If the directory still
contains files, or if the directory does not exist, an I/O error occurs (use
the {$I-} compiler directive and IOResult to check for errors).
See MkDir
Round function
----------------------------------------------------------------
Declaration:
procedure Round ( X: Real );
Example:
{Round the value of Pi to the nearest's thousandth's place }
Writeln( Round ( Pi * 1000 ) / 1000.0 );
Purpose:
Where X is a real value, X is rounded to the nearest integer value. When
X is halfway between two integer values (e.g. 3.5), then X is rounded as
follows:
If X > 0, then X is rounded up to the next integer value. Examples: 3.5
becomes 4; 7.5 becomes 8.
if X < 0, then X is rounded down to the next integer value. Examples:
-3.5 becomes -4; -7.5 becomes 8.
The code shown in the example above illustrates a method of using Round to
round numbers to a particular number of decimal places. In the example, the
value of Pi, 3.1415926535.... is multiple by 1000, producing 3141.5926535....
This value is then rounded to 3142.0, and divided by 1000.0, producing 3.142 as
the value of Pi rounded to the thousandth's place.
See Int, Trunc
RunError procedure
----------------------------------------------------------------
Declaration:
procedure RunError [ ( ErrorCode: Byte ) ];
Example:
{$IFDEF Validate}
if (Temperature < 0.0) or (Temperature > 212.0) then
RunError( TempOutOfRange );
{$ENDIF}
Purpose:
RunError, like the Halt procedure, stops program execution. RunError,
however, generates a run-time error by setting ErrorAddr equal to the address
of the statement that called RunError, and if specified, sets ExitCode to
ErrorCode.
A good use for RunError is to assist in debugging your programs by placing
internal consistency checks into your code. For example, inside your code, you
may wish to place special code to insure that values are always within their
specified range, that pointers are non-nil, and so on. An invalid value
indicates that your program is not operating correctly, so you can call
RunError to force an immediate halt to program execution. Normally, you should
place this type of check code inside of conditional compilation statements so
that you can remove it from the final version of your program.
See ErrorAddr, ExitCode, ExitProc, Halt
Seek procedure
----------------------------------------------------------------
Declaration:
procedure Seek(var F; N: Longint);
Example:
Also see "Random Access Data Files" in Chapter 3, "The Turbo Pascal
Language".
type
TDataRecord = record
Name : String[20];
PhoneNumber : String[14];
Age : Integer;
Available : Boolean;
end;
var
RandomFile : File of TDataRecord;
...
Write('Enter number of record to edit: ');
Readln( RecordNum );
Seek( RandomFile, RecordNum );
Read( RandomFile, DataRecord);
if DataRecord.Available then
Writeln('Record #', RecordNum, ' does not contain any data.');
Purpose:
When performing random accesss to a disk file, Seek is used to position
the file pointer of file F, to the Nth component of the file. Another way of
saying that is that Seek positions to the Nth record in the file. The next
read or write operation will be made to record N.
When you need to add new records to the end of a random access file, you
can use Seek to position to the last record, plus 1. This way the next write
will append a new record to the end of the file. A convenient way to access
the last record is to write,
Seek ( F, FileSize(F) );
since FileSize returns the current filesize in terms of file components or
records.
See FilePos, FileSize, Read, Reset, Rewrite, Write
SeekEof function
----------------------------------------------------------------
Declaration:
function SeekEof [ ( var F: Text ); ]
Purpose:
Text files often contain extra blanks, tabs or blank lines after the last
useful data contained in the file. For this reason, its possible that the
Eof(F) function will return False, even though the next Read (F) will encounter
an end of file condition. The solution is to call SeekEof instead of Eof.
SeekEof skips ahead, past any blanks, tabs or blank lines to determine if the
current file pointer is at the logical end of file.
Make sure that you use SeekEof only on open text files, and no other file
types. To manually check for file errors, set the {$I-} compiler directive and
check IOResult.
See Eof
SeekEoln function
----------------------------------------------------------------
Declaration: function SeekEoln[ (var F: Text); ]
Purpose:
SeekEoln exists for the same reason as SeekEof (See SeekEof). SeekEoln
skips over trailing blanks and tabs in a line to locate the end-of-line marker.
Seg function
----------------------------------------------------------------
Declaration:
function Seg(X): Word;
Purpose:
Computes and returns the segment part of the segment:offset address of X,
where X is any identifier, including variables, procedures and functions.
See Addr, Ofs
SetCBreak procedure
----------------------------------------------------------------
Declaration:
procedure SetCBreak( Break: Boolean);
Unit: Dos
Purpose:
The DOS operating system periodically checks for a the Ctrl-Break key
combination being pressed during program execution. As you know, pressing
Ctrl-Break interrupts the flow of program execution. However, the actual
processing of the Ctrl-Break key depends on the state of a DOS internal
variable. GetCBreak returns the current state of this flag: if set to True,
DOS checks for Ctrl-Break at every DOS system call; if False, DOS checks only
during input/output operations to the console (CON:), printer (LPT:) or
communications ports (COMx:).
You can set the state of the Ctrl-Break flag by calling SetCBreak and
setting Break to True, to enable checking at each DOS system call; or False to
restrict checking to input/output operations.
See CheckBreak, GetCBreak
SetDate procedure
----------------------------------------------------------------
Declaration:
procedure SetDate( Year, Month, Day: Word );
Unit: Dos
Purpose:
Sets the DOS system date to the Year, Month and Day parameters, where Year
should be in the range 1980 to 2099, Month in the range 1 to 12, and Day in the
range 1 to 31. SetDate does not return an error status; if the date values are
erroneous, the new date is not set.
See GetDate, GetTime, SetTime
SetFAttr procedure
----------------------------------------------------------------
Declaration:
procedure SetFAttr (var F; Attr: Word );
Unit: Dos
Example:
Assign(F, 'SCRATCH.DAT' );
GetFAttr( F, Attr );
SetFAttr( F, Attr or Hidden ); { Make the file a hidden file }
Purpose:
Every file on the system has associated with it a set of file attributes.
These attributes indicate if the file is read-only, hidden, or perhaps a
directory name. You can obtain a file's attribute settings by calling
GetFAttr, where F is a file variable to which a filename has been assigned with
Assign (but should not be open).
Using SetFAttr, you can change the file's attributes, as shown in the
example above. The bit pattern used for attributes is determined by these
constants:
ReadOnly = $01;
Hidden = $02;
SysFile = $04;
VolumeID = $08;
Directory = $10;
Archive = $20;
AnyFile = $3F;
AnyFile is typically used with FindFirst and FindNext and doesn't really have
any use here except that it can be used to match any file attributes with an
and operation.
Combinations of attributes are set by or'ing the values together, as shown
in the example above. To get and set the file's access date and time, see
GetFTime and SetFTime.
SetFTime procedure
----------------------------------------------------------------
Declaration:
procedure SetFTime( var F; Time: Longint );
Unit: Dos
Example:
Assign( F, 'FSEARCH.PAS' );
Reset( F );
GetFTime ( F, LFileInfo );
UnpackTime ( LFileInfo, DFileInfo );
with DFileInfo do
Writeln(Month, '-', Day, '-', Year,
' ',Hour:2,':',Min:2,':',Sec:2);
{ Change file's date to 1992 }
DFileInfo.Year := 1992;
PackTime ( DFileInfo, LFileInfo );
SetFTime ( F, LFileInfo );
Purpose:
Every file has associated with it, a date and time stamp indicating when
the file was last written to. You can fetch this date and time information by
calling GetFTime (see GetFTime). GetFTime returns the date and file time
packed into a Longint value (see UnpackTime for converting the packed time
format into individual date and time components).
The example, above, shows how to use SetFDate to output a new date and
time stamp to the open file associated with F. DFileInfo is declared as a DT
record, where DT defines the fields, Month, Day, Year, Hour, Min, Sec. After
setting the field values, you must use PackTime to convert the record into a
packed Loingint, prior to calling SetFDate.
See GetFAttr, GetFTime, PackTime, SetFAttr, UnpackTime
SetIntVec procedure
----------------------------------------------------------------
Declaration:
procedure SetIntVec( IntNo: Byte; Vector: Pointer);
Purpose:
Places an address, Vector, in to the interrupt vector table at entry
number IntNo, where IntNo is a value from 0 to 255.
See GetIntVec
SetTextBuf procedure
----------------------------------------------------------------
Declaration:
procedure SetTextBuf(var F: Text; var Buf [; Size: Word ] );
Example:
(See GetMem for an example of a dynamically allocated text buffer).
Program SetTextBufDemo;
var
F : Text;
Buffer : Array[0..1023] of Char;
TextLine : String;
begin
Assign( F, 'TEMP.PAS' );
SetTextBuf( F, Buffer );
Reset( F );
while not Eof(F) do
begin
Readln( F, TextLine );
Writeln( TextLine );
end;
Close( F );
end.
Purpose:
By default, all text files use an internal 128-byte buffer for reading and
writing textual data to and from the disk. For faster text file performance,
programs can create their own text file buffer, of any appropriate size, by
calling SetTextBuf and passing the name of the buffer as the Buf variable
parameter. By creating a larger text file buffer, such as 1,024 bytes, you
will generally see a significant improvement in performance. You don't need to
specify the Size parameter; by default, SetTextBuf sets the internal text
buffer size to SizeOf(Buf). The new buffer will be used until you close file
F, or open a new file using the F file id. After closing the file, be certain
to properly dispose of the buffer, particularly if the buffer is a dynamic
variable.
Important! Call SetTextBuf Before Calling Append, Reset, or Rewrite
As a rule of thumb, always call SetTextBuf just prior to calling Append,
Reset or Rewrite. While you can call SetTextBuf after opening a file, the act
of switching text buffers can cause a potential loss of data. So just don't do
that!
See "Disk file operations" in Chapter 3, or Append, Reset, Rewrite
SetTime procedure
----------------------------------------------------------------
Declaration:
procedure SetTime(Hour, Minute, Second, Sec100: Word);
Unit: Dos
Purpose:
Use SetTime to set the system clock. If any of the values are out of the
permissible ranges (0 to 23 for Hour, 0 to 59 for Minute and Second, and 0 to
100 for Sec100), the time is not changed.
See GetTime
SetVerify procedure
----------------------------------------------------------------
Declaration:
procedure SetVerify(Verify: Boolean);
Unit: Dos
Purpose:
By calling SetVerify with Verify set to True, DOS will subsequently verify
the accuracy of all disk write operations (by rereading the data it just
wrote). Since this is a time consuming operation, many applications will
choose not to use this feature. To turn off automatic verification, call
SetVerify with Verify to False.
Sin function
----------------------------------------------------------------
Declaration:
function Sin ( X: Real ) : Real;
Example:
GetAspectRatio ( Xasp, Yasp );
{ Compute (X,Y) 10% further out than the radius. }
X := Round( 1.1 * Radius * Cos ( AngleInRadians ) );
Y := - Round( 1.1 * Radius * Sin ( AngleInRadians ) *
(Xasp/Yasp));
Purpose:
Computes and returns the sine of X, where X is an angle measurement in
radians. Note that many of the graphics routines use an angle measurement in
degrees. To convert from degrees to radians, divide the degree measurement by
180 / Pi.
See ArcCos/ArcSin, ArcTan, Cos, Tan
SizeOf function
----------------------------------------------------------------
Declaration:
function SizeOf( X ) : Word;
Purpose:
SizeOf computes and returns the total memory storage, in bytes, of its
parameter X, where X is either a variable or a data type. SizeOf is frequently
used when allocating memory blocks dynamically (such as GetMem ( PBuffer,
SizeOf(Buffer) )) and elsewhere.
Sound procedure
----------------------------------------------------------------
Declaration:
procedure Sound(Hz : Word);
Unit: Crt
Purpose:
Activates the PC's speaker, setting it to a tone having the frequency (in
hertz or cycles per second) specified by Hz. The only way to turn off the
speaker, once activated, is to call NoSound. Between calls to Sound and
NoSound, use the Delay procedure to leave the speaker turned on for a set
amount of time.
See Delay, Sound
SPtr function
----------------------------------------------------------------
Declaration:
function SPtr : Word;
Purpose:
Returns the value of 80x86 SP (stack pointer) register. SP is always
relative to the SS (Stack segment) register.
See SSeg
Sqr function
----------------------------------------------------------------
Declaration:
function Sqr( X ) : <type of X>
Purpose:
Returns X squared, which is equivalent to X * X.
Sqrt function
----------------------------------------------------------------
Declaration:
function Sqrt(X: Real) : Real;
Purpose:
Where X is greater than or equal to 0, Sqrt(X) returns the square root of
X. Sqrt(X) if not defined for negatives values of X.
SSeg function
----------------------------------------------------------------
Declaration:
function SSeg: Word;
Purpose:
Returns the current value of the SS or Stack Segment register of the CPU.
See SPtr
Str procedure
----------------------------------------------------------------
Declaration:
procedure Str(X [: Width [:Decimals] ]; var S: String);
Purpose:
When you need to convert a byte, integer, word, longint, or one of the
real data types to a string representation, use the Str procedure, specifying
an optional field Width and number of Decimals of accuracy. For example,
Str( 3.14159, S );
sets S equal to '3.1415900000E+00'. To convert the value to a decimal
notation, you must specify the Width and Decimals parameters, where Width
specifies the overall length of the resulting string, and Decimals specifies
the number of decimal places to be included in the result. For example,
Str( 3.14159:5:2, S );
sets S equal to '3.14'. Changing Decimals from 2 to 4 sets S equal to
'3.1416'. Note: The value of X is rounded, as needed, to fit within the
specified width and decimal places.
To convert the string representation of a number, say '3.14159' to the
internal numeric format, use the Val procedure.
Succ function
----------------------------------------------------------------
Declaration:
function Succ(X) : <same type as X>;
Purpose:
Where X is any ordinal value, Succ(X) returns the successor of X. For
example, the Succ(9) is 10. See Pred for an example involving ordinal types.
See Inc, Pred
Swap function
----------------------------------------------------------------
Declaration:
function Swap(X) : <same type as X>;
Purpose:
When X is either an integer or word value, Swap(X) returns the result of
swapping the high and low order bytes of X. You can examine the high or low
order bytes of an integer or word value using the Hi and Lo functions.
SwapVectors procedure
----------------------------------------------------------------
Declaration:
procedure SwapVectors;
Unit: Dos
Example:
See Exec.
Purpose:
SwapVectors is normally used before and after calling the Exec procedure,
which is used to launch another application. Essentially, SwapVectors results
in saving the state of the interrupt vectors before a call to Exec, and
restoring the vector table upon return. This helps prevent problems that may
occur if your application depends on specific settings in the interrupt vector
table - settings that may be changed by the application which is launched.
Test8087 variable
----------------------------------------------------------------
Declaration:
Test8087: Byte = 0;
Purpose:
When a Turbo Pascal program starts up, the initialization code determines
if the 8087 math coprocessor is available for use, and sets Test8087 as
follows:
Value Meaning
0 No math coprocessor found.
1 8087 available.
2 80287 available.
3 80387 available.
TextAttr variable
----------------------------------------------------------------
Declaration:
TextAttr: Byte;
Unit: Crt
Example:
uses Crt;
begin
TextColor(3);
TextBackground(5);
Writeln('Foreground color=', TextAttr and 15);
Writeln('Background color=', (TextAttr shr 4) and 15);
Readln;
end.
Purpose:
Stores the currently defined text attributes (color, background color) in
internal format.
TextBackground procedure
----------------------------------------------------------------
Declaration:
procedure TextBackground( Color: Byte );
Unit: Crt
Purpose:
Text written to the display has two color attributes: a foreground color
and a background color. TextBackground sets the current background color
attribute to the value of Color, such that all text output following the call
to TextBackground will be drawn with the specified background color. Color
should have a value from 0 to 7, to choose one of the 8 possible background
colors. You may substitute one of the following constants for your color
choice:
Black 0
Blue 1
Green 2
Cyan 3
Red 4
Magenta 5
Brown 6
LightGray 7
TextColor procedure
----------------------------------------------------------------
Declaration:
procedure TextColor(Color: Byte);
Unit: Crt
Purpose:
Text written to the display has two color attributes, a foreground color
and a background color. TextColor sets the foreground color attribute to the
value of Color, so that all subsequent text output will be written in the
selected color, using the current TextBackground color. Foreground color
choices may range from 0 to 15, with values 8 through 15 referred to as "high
intensity" equivalents of colors 0 to 7. You may use the following constants
to select the color choice:
Black 0
Blue 1
Green 2
Cyan 3
Red 4
Magenta 5
Brown 6
LightGray 7
DarkGray 8
LightBlue 9
LightGreen 10
LightCyan 11
LightRed 12
LightMagenta 13
Yellow 14
White 15
TextMode procedure
----------------------------------------------------------------
Declaration:
procedure TextMode(Mode: Word);
Unit: Crt
Example:
TextMode ( CO80 );
Purpose:
Most of today's video displays support a variety of text operating modes,
including both 40 and 80 column wide displays, color and black & white display
modes, and for EGA and VGA displays, the ability to display 43 or 50 lines of
text. The TextMode procedure selects the appropriate display mode by setting
Mode to one of the following constants:
BW40 Selects B&W in 40 x 25 line display mode
BW80 Selects B&W in 80 x25 line display mode
Mono Selects B&W in 80 x25 line on monochrome
display adaptor card
CO40 Selects color in 40 x 25 line display mode
CO80 Selects color in 80 x 25 line display mode
C40 Same as CO40
C80 Same as CO80
LastMode Restores the previous video mode prior to
program startup.
The selected text mode takes effect immediately and results in the screen being
cleared.
LastMode is a variable and it stores the contents of the video mode at the
time the program was started. If your program changes video modes during
program execution, you may wish to save the value of LastMode so that you can
restore the appropriate video mode at program termination (also see ExitProc).
You may also use TextMode to select 43 or 50 line mode for use on EGA/VGA
displays by adding or or'ing the constant Font8x8 (where Font8x8 = 256 and
selects a small font for use in the higher resolution modes) to the mode
selection constant, like this:
TextMode( LastMode and 255 or Font8x8 );
In this form, the current video mode (such as 80 column color) is retained but
the number of lines is increased to 43 or 50 lines, depending on your display.
You may explicitly select both a video mode and 43 or 50 line mode by writing:
TextMode( CO80 + Font8x8 );
To switch back to 25 line mode and maintain the the other mode settings, you
can write,
TextMode( LastMode and 255 );
or specifically set a new mode, such as,
TextMode( BW80 );
You can also use the Lo() and Hi() functions to check the value of LastMode.
Hi(LastMode) returns Font8x8 if 43/50 line mode is in effect. Lo(LastMode)
returns the current video mode.
Trunc function
----------------------------------------------------------------
Declaration:
function Trunc( X: Real ): Longint;
Purpose:
Trunc converts the real value X to a longint integer value by disgarding
the fractional portion of X. For example, Trunc(3.14159) results in 3. When
converting real values to Longint, be aware that the range of valid real
numbers exceeds the permissible range of Longint, and it is possible to receive
an out of range run-time error.
See Frac, Int, Round
Truncate procedure
----------------------------------------------------------------
Declaration:
procedure Truncate(var F);
Purpose:
When using any open file, other than text files, Truncate(F) disgards all
current data in the file from the current file pointer position on to the end
of the file, effectively making the current file position the new end of file.
Unpacktime procedure
----------------------------------------------------------------
Declaration:
procedure UnpackTime(Time: Longint; var DT: DateTime);
Unit: Dos
Example:
uses dos;
var
F : Text;
LFileInfo : Longint;
DFileInfo : DateTime; { declared in Dos unit }
begin
Assign( F, 'FSEARCH.PAS' );
Reset( F );
GetFTime ( F, LFileInfo );
UnpackTime ( LFileInfo, DFileInfo );
with DFileInfo do
Writeln(Month, '-', Day, '-', Year,
' ',Hour:2,':',Min:2,':',Sec:2);
Readln;
end.
Purpose:
The procedures GetFTime, SetFTime, FindFirst and FindNext all use a
special packed date/time format that packs the date and time information into a
Longint value. To convert the Longint packed representation into individual
date and time components, use UnPackTime. To convert back to packed format,
use PackTime.
UnPackTime converts its Time parameter value into the contents of the DT
record parameter variable. DT contains separate fields for Year, Month, Day,
Hour, Min and Sec, each a Word type value. You can use these fields to display
the date or time of a file in traditional date or time formats.
UpCase function
----------------------------------------------------------------
Declaration:
function UpCase (Ch: Char): Char;
Example:
function Uppercase( S : String ): String;
var
I : Integer;
begin
for I := 1 to Length(S) do
S[I] := Upcase(S[I]);
Uppercase := S;
end;
begin
Writeln(Uppercase('Now is the time for all good men and women...'));
Readln;
end.
Purpose:
UpCase converts its parameter Ch to uppercase, (if Ch is a letter from 'a'
to 'z') or makes no changes if Ch is not a lower case letter, and returns the
new value as its return result. The example above shows a simple function to
convert an entire string to upper case.
Val procedure
----------------------------------------------------------------
Declaration:
procedure Val(S: String; var V; var Code: Integer);
Example:
uses Crt;
var
S : String;
Result : Real;
ErrCode : Integer;
begin
ClrScr;
Gotoxy(1,10);
Write('Enter number: ');
Readln(S);
{$R-}
Val( S, Result, ErrCode );
if ErrCode = 0 then
Writeln(S, ' converted successfully to ', Result )
else
begin
Gotoxy( 14+ErrCode, 11 );
Write('^ invalid character in number.');
end;
Readln;
end.
Purpose:
Val converts a string containing a number, into its internal numeric
format for the appropriate variable type, such as integer or real. The string
to convert is passed as parameter S and is returned in variable parameter V.
The string to convert must contain a valid number for the type of the
variable parameter V. If an invalid character is detected during the
conversion, Code is set to the index of the offending character within string
S. The example code above uses the returned error code to display a pointer to
the invalid character.
When converting numbers, its possible for the number in S to be out of
range of the permissible values for variable V. For example, attempting to
convert the string value shown below results in a range violation:
var
W : Word;
...
Val('8799343.5', W, ErrCode );
To avoid out of range errors, you can select the {$R-} compiler directive to
disable automatic range checking. A more thorough procedure, however, is to
convert the value first to a temporary Real or Longint variable and then use an
if-then statement to insure that the result falls within the valid range for
the target variable.
WhereX function
----------------------------------------------------------------
Declaration:
function WhereX : Byte;
Unit: Crt
Purpose:
Returns the current X coordinate of the text cursor. WhereY returns the
corresponding Y coordinate.
WhereY function
----------------------------------------------------------------
Declaration:
function WhereY: Byte;
Unit: Crt
Purpose:
Returns the current Y coordinate of the text cursor.
WindMin/WindMax variables
----------------------------------------------------------------
Declaration:
WindMin, WindMax : Word;
Unit: Crt
Purpose:
WindMin stores the coordinate of the upper left corner and WindMax the
lower right corner of a window defined by the Window procedure. The values are
stored such that the X value is stored in the low byte and Y in the high byte.
Note that in WindMin and WindMax, the stored values are 0-relative, and not