0% found this document useful (0 votes)
132 views

Turbo Pascal Version 7.0 Programmers Reference 1992

Pascal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
132 views

Turbo Pascal Version 7.0 Programmers Reference 1992

Pascal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 310

7.

PROGRAMMER'S
REFERENCE
RUNTIME LIBRARY
COMMANDlINE COMPILER
ERROR MESSAGES
COMPILER DIRECTIVES

BORLAND

Turbo PascafB>
Version 7.0

Programmer's Reference

BORLAND INTERNATIONAL INC. 1800 GREEN HILLS ROAD


P.O. BOX 660001, SCOTTS VALLEY, CA 950670001

Copyright 1983, 1992 by Borland International. All rights


reserved. All Borland products are trademarks or registered
trademarks of Borland International, Inc. Windows, as used in this
manual, shall refer to Microsoft's implementation of a windows
system. Other brand and product names are trademarks or
registered trademarks of their respective holders.

PRINTED IN 'THE USA.

Rl

Introduction
1
What's in this manual? ................. 1
How to contact Borland . . . . . . . . . . . . . . .. 2
Chapter 1 Library reference
5
Sample procedure . . . . . . . . . . . . . . . . . . . .. 5
Abs function ......................... 6
Addr function ........................ 6
Append procedure . . . . . . . . . . . . . . . . . . .. 6
ArcCoordsType type .................. 7
Arc procedure . . . . . . . . . . . . . . . . . . . . . . .. 8
ArcTan function ...................... 8
Assign procedure ..................... 9
AssignCrt procedure ................. 10
Assigned function . . . . . . . . . . . . . . . . . . .. 10
Bar constants . . . . . . . . . . . . . . . . . . . . . . .. 11
Bar procedure ....................... 11
Bar3D procedure ..................... 12
BitBlt operators .. . . . . . . . . . . . . . . . . . . .. 12
BlockRead procedure . . . . . . . . . . . . . . . .. 13
BlockWrite procedure ................ 14
Break procedure ..................... 15
ChDir procedure ............. " ...... 15
CheckBreak variable ................. 16
CheckEOF variable . . . . . . . . . . . . . . . . . .. 16
CheckSnow variable ............... ~ ". 16
Chr function ........................ 17
Circle procedure ..................... 17
ClearDevice procedure ............... 18
ClearViewPort procedure ............. 19
Clipping conshints ................... 19
Close procedure ..................... 20
CloseGraph procedure . . . . . . . . . . . . . . .. 20
ClrEol procedure .................... 21
ClrScr procedure ...... '.' . . . . . . . . . . . .. 21
Color constants .. . . . . . . . . . . . . . . . . . . .. 22

Color constants for SetRGBPalette ..... .


Concat function ..................... .
Continue procedure ................. .
Copy function ...................... .
Cos function ....................... .
CreateDir procedure ................ .
Crt mode constants ................. .
CSeg function ...................... .
DateTime type .... ~ ................. .
Dec procedure ...................... .
Delay procedure .................... .
Delete procedure ................... .
DelLine procedure .................. .
DetectGraph procedure .............. .
DirectVideo variable ................ .
DiskFree function ................... .
DiskSize function ................... .
Dispose procedure .................. .
DosError variable ................... .
DosExitCode function ...... ; ........ .
DosVersion function ....... ; ........ .
DrawPoly procedure ................ .
Driver and mode constants ........... .
DSeg function ...................... .
Ellipse procedure .................. "..
EnvCount function .................. .
EnvStr function ..................... .
Eof function (text files) ............... .
Eof function (typed, untyped files) .... .
Eoln function ....................... .
Erase procedure ..................... .
ErrorAddr variable .................. .
Exclude procedure .................. .
Exec procedure ..................... .
Exit procedure ...................... .
ExitCode variable ................... .

22
23
23
24
25
25
25
26
26
27
27
27
28
28
29
30
30
30
31
32
32
32
33
35
35
36
36
36
37
37
38
39
39
39
40
41

ExitProc variable . . . . . . . . . . . . . . . . . . . ..
Exp function .............. ;.........
fcXXXX flag constants ................
FExpand function ..................... '
File attribute constants . . . . . . . . . . . . . . ..
File name length constants ............
FileExpand function . . . . . . . . . . . . . . . . ..
File-handling string types ............
FileMode variable . . . . . . . . . . . . . . . . . . ..
FilePos function .....................
FileRec type . . . . . . . . . . . . . . . . . . . ... . . ..
FileSearch function . . . . . . . . . . . . . . . . . ..
FileSize function .............. . . . . . ..
FileSplit function. '.' ................. :
Fill pattern constants .................
FillChar procedure ... . . . . . . . . . . . . . . ..
FillEllipse procedure ..' ...............
FillPatternType type . . . . . . . . . . . . . . . . ..
FillPoly procedure ...................
FillSettingsType type .................
FindFirst procedure ..................
FindNext procedure . . . . . . . . . . . . . . . . ..
Flag constants .......................
FloodFill procedure ..................
Flush procedure .....................
fmXXXX constants ...................
Font control constants ................
F~ac function ................. : . . . . ..
FreeList variable .....................
FreeMem procedure . . . . . . . .. .. . . . . . ..
FSearchfunction . . . . . . . . . . . . . . . . . . . ..
FSplit procedure .....................
GetArcCoords procedure ............ ,
GetArgCount function . . . . . . . . . . . . . . ..
GetArgStr function . . . . .. . . . . . . . . . . . ..
GetAspectRatio procedure ............
GetBkColor function .................
GetCBreak procedure. . . . . . . . . . . . . . . ..
GetColor function . . . . . . . . . . . . . . . . . . ..
GetCurDir function ..................
GetDate procedure . . . . . . . . . . . . . . . . . ..
GetDefaultPalette function ............
GetDir procedure ....................
GetDriverName function. . . . . . . . . . . . ..

41
42
42
42
43
43
44
44
45
45
46
46
47
47
48
49
49
50
50
51
51
52
53
53
54
55
55
55
56
56
57
57
58
59
59
59
60
61
62
62
63
63
64
64

GetEnv function ..................... 65


GetEnvVar function. . . . . . . . . . . . . . . . .. 66
GetFAttr procedure .................. 66
GetFillPattern procedure . . . . . . . . . . . . .. 67
GetFillSettings procedure . " ........... 67
GetFTime procedure ................. 68
GetGraphMode function . . . . . . . . . . . . .. 69
GetImage procedure ................. 70
GetIntVec procedure ................. 71
GetLineSettings procedure ............ 71
GetMaxColor function . . . . . . . . . . . . . . .. 72
GetMaxMode function. . . . . . . . . . . . . . .. 72
GetMaxX'function ... ; ............... 73
GetMaxY function ................... 74
GetMem procedure .................. 74
GetModeName function .............. 75
GetModeRange procedure ............ 75
GetPalette procedure ................. 76
GetPaletteSize function ............... 77
GetPixel function .................... 77
GetTextSettings procedure ............ 78
GetTime procedure .................. 78
GetVerify procedure ................. 79
GetViewSettings procedure ........... 79
GetX function ....................... 80
GetY function ....................... 81
GotoXYprocedure ................... 81
GraphDefaults procedure ............. 82
GraphErrorMsg function. . . . . . . . . . . . .. 82
GraphFreeMemPtr variable ........... 83
GraphGetMemPtr variable ............ 83
GraphResult function. . . . .. . . . . . . . . . .. 84
grXXXX constants .................... 85
Halt procedure ...................... 85
HeapEnd variable . . . . . . . . . . . . . . . . . . .. 86
i-IeapError variable. . . . . . . . . . . . . . . . . .. 86
HeapOrg variable . . . . . . . . . . . . . . . . . . .. 86
HeapPtr variable. . . . . . . . . . . . . . . . . . . .. 87
Hi function ......................... 87
High function ....................... 87
HighVideo procedure ................ 88
ImageSize function ...... 'c.' 88
Inc procedure ...................... .89
Include procedure ................... 90

InitGraph procedure ................. 90


InOutRes variable . . . . . . . . . . . . . . . . . . .. 92
Input variable ....................... 92
Insert procedure ..................... 93
InsLine procedure ..................... 93
InstallUserDriver function ............ 94
InstallUserFont function .............. 96
Int function ......................... 97
Intr procedure ....................... 97
IOResult function .................... 98
Justification constants ................ 99
Keep procedure. . . . . . . . . . . . . . . . . . . . .. 99
KeyPressed function ................. 99
LastMode variable .................. 100
Length function . . . . . . . . . . . . . . . . . . . .. 100
Line procedure ..................... 100
Line style constants ................. 101
LineRelprocedure .................. 102
LineSettingsType type ............... 103
LineTo procedure ................... 103
Ln function ........................ 104
Lo function ........................ 104
Low function . . . . . . . . . . . . . . . . . . . . . .. 104
LowVideo procedure ................ 105
Lst variable ........................ 106
MaxAvail function .................. 106
MaxColors constant ................. 107
MemAvail function .................. 107
MkDir procedure ................... 108
Move procedure .................... 108
MoveRelprocedure ................. 109
MoveTo procedure . . . . . . . . . . . . . . . . .. 110
MsDos procedure ................... 110
New procedure ..................... 111
NormVideo procedure ............... 111
NoSound procedure ................. 112
Odd function . . . . . . . . . . . . . . . . . . . . . .. 112
Ofs function . . . . . . . . . . . . . . . . . . . . . . .. 112
Ord function ....................... 112
Output variable . . . . . . . . . . . . . . . . . . . .. 113
OutText procedure .................. 113
OutTextXYprocedure ............... 115
OvrClearBuf procedure, ............. 116
OvrCodeList variable . . . . . . . . . . . . . . .. 116

OvrDebugPtr variable ...............


OvrDosHandle variable . ~ ............
OvrEmsHandle variable .............
OvrFileMode variable ...............
OvrGetBuf function ..................
OvrGetRetry function ...............
OvrHeapEnd variable ...............
OvrHeapOrg variable ...............
OvrHeapPtr variable ................
OvrHeapSize variable ...............
OvrInit procedure. . . . . . . . . . . . . . . . . ..
OvrInitEMS procedure ..............
OvrLoadCount variable. . . . . . . . . . . . ..
OvrLoadList variable . . . . . . . . . . . . . . ..
OvrReadBuf variable ...... . . . . . . . . ..
OvrResult variable ........ . . . . . . . . ..
OvrSetBuf procedure . . . . . . . . . . . . . . ..
OvrSetRetry procedure ..............
OvrTrapCount variable . . . . . . . . . . . . ..
ovrXXXX constants. . . . . . . . . . . . . . . . ..
PackTime procedure ................
PaletteType type . . . . . . . . . . . . . . . . . . ..
ParamCount function ...............
ParamStr function . . . . . . . . . . . . . . . . . ..
Pi function . . . . . . . . . . . . . . . . . . . . . . . ..
PieSlice procedure ..................
PointType type .....................
Pos function . . . . . . . . . . . . . . . . . . . . . . ..
Pred function . . . . . . . . . . . . . . . . . . . . . ..
PrefixSeg variable . . . . . . . . . . . . . . . . . ..
Ptr function ........................
PutImage procedure. . . . . . . . . . . . . . . ..
PutPixel procedure . . . . . . . . . . . . . . . . ..
Random function ...................
Randomize procedure ...............
RandSeed variable ..................
Read procedure (text files) ......... ,.
Read procedure (typed files) ..........
ReadKey function . . . . . . . . . . . . . . . . . ..
Readln procedure ...................
Rectangle procedure ................
RegisterBGIdriver function . . . . . . . . . ..
RegisterBGIfont function. . . . . . . . . . . ..
Registers type ......................

iii

117
117
117
118
118
118
119
119
120
120
120
121
122
122
123
123
123
124
125
125
125
126
126
127
127
127
128
128
129
129
129
130
132
132
133
133
133
135
135
136
136
137
139
141

RemoveDir procedure ...............


Rename procedure ..................
Reset procedure ....................
RestoreCrtMode procedure ...........
Rewrite procedure ..................
RmDir procedure ...................
Round function . . . . . . . . . . . . . . . . . . . ..
RunError procedure .................
SavelntXX variables .................
SearchRec type .....................
Sector procedure . . . . . . . . . . . . . . . . . . ..
Seek procedure ......................
SeekEof function . . . . . . . . . . . . . . . . . . ..
SeekEoln function . . . . . . . . . . . . . . . . . ..
Seg function ....................... ;
Seg0040 variable ....................
SegAOOO variable ...................
SegBOOO variable . . . . . . . . . . . . . . . . . . ..
SegB800 variable . . . . . . . . . . . . . . . . . . ..
SelectorInc variable .................
SetActivePage procedure ............
SetAllPalette procedure . . . . . . . . . . . . ..
SetAspectRatio procedure ............
SetBkColor procedure ...............
SetCBreak procedure ................
SetColor procedure .................
SetCurDir procedure ................
SetDate procedure ..................
SetFAttr procedure ...................
SetFillPattern procedure .............
SetFillStyle procedure ...............
SetFTime procedure . . . . . . . . . . . . . . . ..
SetGraphBufSize procedure ..........
SetGraphMode procedure . . . . . . . . . . ..
SetIntVec procedure. . . . .. . . . . .. . . . ..
SetLineStyle procedure ..............
SetPaletteprocedure ................
SetRGBPalette procedure ............
SetTextBuf procedure ................
SetTextJustify procedure .............
SetTextStyle procedure ..............
SetTime procedure ........ ~ . . . . . . . ..
SetU serCharSize procedure ..........
SetVerify procedure .................

141
142
142
143
144
145
145
146
146
147
148
149
149
149
150
150
150
151
151
151
152
152
154
155
155
156
156
157
157
158
159
160
160
160
161
162
163
164
168
169
169
171
171
172

SetViewPort procedure ..............


SetVisualPage procedure. . . . . . . . . . . ..
SetWriteMode procedure ............
Sin function ........................
SizeOf function . . . . . . . . . . . . . . . . . . . ..
Sound procedure ...................
SPtr function .......................
Sqr function ........................
Sqrt function .......................
SSeg function .......................
StackLimit variable. . . . . . . . . . . . . . . . ..
Str procedure .......................
StrCat function .....................
StrComp function . . . . . . . . . . . . . . . . . ..
StrCopy function ...................
StrDispose function .................
StrECopy function ..................
StrEnd function ................... "
StrIComp function ..................
StrLCat function ................. : ..
StrLComp function ..................
StrLCopy function ..................
StrLen function .....................
StrLIComp function . . . . . . . . . . . . . . . ..
StrLower function ...................
StrMove function ...................
StrNew function ....................
StrPas function .....................
StrPCopy function ..................
StrPos function .....................
StrRScan function . . . . . . . . . . . . . . . . . ..
StrScan function ....................
StrUpper function ...................
Succ function . . . . . . . . . . . . . . . . . . . . . ..
Swap function . . . . . . . . . . . . . . . . . . . . ..
SwapVectors procedure. . . . . . . . . . . . ..
TDateTime type .......... ... . . . . . ..
Test8086 variable ...................
Test8087 variable ...................
TextAttr variable. . . . . . . . . . . . . . . . . . ..
Text color constants .................
TextBackground procedure ..........
TextColor procedure ................
TextHeight function .................

iv

172
173
174
175
176
176
177
177
177
177
177
178
178
179
179
180
180
181
181
181
182
182
183
183
184
184
185
185
186
186
187
187
188
188
188
189
189
190
190
191
192
192
193
193

TextMode procedure ................


TextRec type .......................
TextSettingsType type ...............
TextWidth function .................
TFileRec type . . . . . . . . . . . . . . . . . . .. . ..
TRegisters type .....................
Trunc function . . . . . . . . . . . . . . . . . . . . ..
Truncate procedure .................
TSearchRec type ....................
TTextRec type ......................
TypeOf function ....................
UnpackTime procedure ..............
UpCase function . . . . . . . . . . . . . . . . . . ..
Valprocedure ......................
View PortType type .................
WhereX function. . . . . . . . . . . . . . . . . ...
WhereY function . . . . . . . . . . . . . . . . . . ..
WindMax and WindMin variables ....
Window procedure .................
Write procedure (text files) ...........
Write procedure (typed files) .........
Writeln procedure ..................

194
195
196
196
197
198
198
198
199
199
200
200
200
201
202
202
202
203
203
204
206
206

Chapter 2 Compiler directives


Align data .........................
Boolean evaluation ......... ; ........
Debug information . . . . . . . . . . . . . . . . ..
DEFINE directive ...................
ELSE directive ......................
Emulation .........................
ENDIF directive ....................
Extended syntax ....................
Force far calls. . . . . . . . . . . . . . . . . . . . . ..
Generate 80286 Code ................
IFDEF directive . . . . . . . . . . . . . . . . . . . ..
IFNDEF directive ...................
IFOPT directive .....................
Include file . . . . . . . . . . . . . . . . . . . . . . . ..
Input/output checking. . . . . . . . . . . . . ..
Link object file . . . . . . . . . . . . . . . . . . . . ..
Local symbol information ............
Memory allocation sizes .............
Numeric coprocessor ................
Open string parameters ..............

209
211
211
212
212
213
213
213
214
214
215
215
215
215
216
216
216
217
218
218
218

Overflow checking ..................


Overlay code generation .............
Overlay unit name ..................
Range checking . . . . . . . . . . . . . . . . . . . ..
Stack-overflow checking .............
Symbol reference information ........
Type-checked pointers . . . . . . . . . . . . . ..
UNDEF directive ...................
Var-string checking .................
Using conditional compilation
directives ..........................
Conditional symbols ..............

219
219
220
220
221
221
222
222
222
223
224

Chapter 3 Command-line compiler 227


Command-line compiler options .. . . .. 228
Compiler directive options ......... 229
The switch directive option . . . . . .. 229
The conditional defines option .... 230
Compiler mode options . . . . . . . . . . .. 230
The make (1M) option ........... 231
The build all (lB) option ......... 231
The find error (IF) option ........ 231
The link buffer (lL) option ....... 232
The quiet (I Q) option ........... 232
Directory options ................. 233
The TPL & CFG directory (IT)
option ......................... 233
The EXE & TPU directory (IE)
option ......................... 234
The include directories (IE) option. 234
The unit directories (lU) option . .. 234
The object files directories (I 0)
option ......................... 234
Debug options . . . . . . . . . . . . . . . . . . .. 234
The map file (I G) option . . . . . . . .. 234
The debugging (IV) option . . . . . .. 235
The TPC.CFG file ................... 235
Chapter 4 Error messages'
Compiler error messages .............
Run-time errors .....................
DOS errors . . . . . . . . . . . . . . . . . . . . . ..
I/O errors .......................
Critical Errors ....................

237
237
257
258
260
261

Fatal errors. . . . . . . . . . . . . . . . . . . . . .. 261

Appendix B Compiler directives quick


reference
271

Appendix A Editor reference


265
Editor commands in depth ......... 269
Searching with regular expressions . . .. 270

vi

Appendix C Reserved words and


standard directives

275

Appendix 0 ASCII characters

277

Index

281

1.1: Graph unit driver constants ......... 33


1.2: Graph unit mode constants ......... 34
1.3: The components of the output
string ........................... 205
1.4: The components of the fixed-point
string ........................... 205
3.1: Command-line options ............ 228
4.1: Error message types ............... 237
A.1: Editing commands ............... 266

A.2: Block commands in depth ......... 268


A.3: Borland-style block commands .... 269
A.4: Other editor commands in depth ... 269
A.5: Regular expression wildcards ..... 270
B.1: Compiler directives ............... 271
C.1: Turbo Pascal reserved words ...... 275
C.2: Turbo Pascal standard directives ... 276
D.1: ASCII table ...................... 278

vii

viii

See the User's Guide for an


oveNiew of the entire Turbo
Pascal documentation set.
Read its introduction to find
out how to use the Turbo
Pascal m'anuals most
effectively.

This manual is a reference that you can keep nearby when you're
programming. Use it when you want to
Look up the details of a particular run-time library procedure,
function, variable, type, or constant and find out how to use it
Understand what each compiler directive does, how it works,
and how to use it
Learn how to use the command-line compiler
Find out what an error message means
Look up editor commands
Look up compiler directives in a quick reference table
Review a list of reserved words and standard compiler
directives
Look up ASCII alphanumeric characters, symbols, and control
instructions

What's in this manual?


See the Language Guide for
an oveNiew of the units
found in Turbo Pascal's
run-time library.

This manual has four reference chapters and four appendixes.


Chapter 1: Library reference is an alphabetized lookup of all the
procedures, functions, variables, types, constants, and typed
constants found in the units that make up the run-time library.
Chapter 2: Compiler directives explains how to use the three
types of compiler directives and presents a detailed, alphabetized
lookup of all the directives.
Chapter 3: Command-line compiler explains how to use the

command-line compiler.
Chapter 4: Error messages lists in numerical order all the error
messages you might encounter and explains what they mean.

Introduction

Appendix A: Editor reference explains the key combinations and


commands you can use while editing your code.
.
Appendix B: Compiler directives quick reference lists all the
compiler directives, their command-line equivalents, and brief
descriptions. To find more detailed explanations, read Chapter 2.
Appendix C: Reserved words and standard directives lists all the

reserved words and standard directives in Turbo Pascal.


Appendix D: ASCII characters lists all the American Standard
Code for Information Interchange (ASCII) characters.

How to contact Borland


Borland offers a variety of services to answer your questions
about Turbo Pascal.
1111"

Be sure to send in the registration card; registered owners are


entitled to technical support and may receive information on
upgrades and supplementary products.
Tech Fax

800-822-4269 (voice)

TechFax is a 24-hour automated service that sends free technical


information to your fax machine. You can use your touch-tone
phone to request up to three documents per call.

Borland Download BBS


408-439-9096 (modem)
up to 9600 Baud

The Borland Dowriload BBS has sample files, applications, and


technical information you can download with your modem. No
special setup is required.

Online informotion services


Subscribers to the CompuServe, GEnie, or BIX information
services can receive technical support by modem. Use the.
commands in the following table to contact Borland while
accessing an information service.

Programmer's Reference

Online information services

Service

Command

CompuServe GO BORLAND
BIX
JOIN BORLAND
GEnie
BORLAND

Address electronic messages to Sysop or All. Don't include your


serial number; messages are in public view unless sent by a
service's private mail system. Include as much information on the
question as possible; the support staff will reply to the message
within one working day.

Borland Technical Support


408-467 -9744
6 a.m. to 5 p.m. PT

Borland Technical Support is available weekdays from 6:00 a.m.


to 5:00 p.m. Pacific time to answer technical questions about
Borland products. Please call from a telephone near your
computer, with the program running and the following
information available:
Product name, serial number, and version number
Brand and model of the hardware in your system
Operating system and version number-use the operating
system's VER command to find the version number
Contents of your AUTOEXEC.BAT and CONFIG.SYS files
(located in the root directory (\) of your computer's boot disk)
Contents of your WIN.INI and SYSTEM.INI files (located in
your Windows directory)
Daytime phone number where you can be reached
If the call concerns a software problem, please be able to describe

the steps that will reproduce the problem.


Borland Technical Support also publishes technical information
sheets on a variety of topics.

Borland Advisor Line


900-555- 7007
6 a.m. to 5 p.m. PT

The Borland Advisor Line is a service for users who need


immediate access to advice on Turbo Pascal issues.
The Advisor Line operates weekdays from 6:00 a.m. to 5:00 p.m.
Pacific time. The first minute is free; each subsequent minute is
$2.00.

Introduction

Borland Customer Service


408-467-9000 (voice)
7 a.m. to 5 p.m. PT

Borland Customer Service is available weekdays from 7:00 a.m. to


5:00 p.m. Pacific time to answer nontechnical questions about
Borland products, including pricing information, upgrades, and
order status.

Programmer's Reference

1
Library reference
This chapter contains a detailed description of all Turbo Pascal
procedures, functions, variables, types, and constants. At the
beginning of each alphabetically listed entry is the name of the
unit or units containing the data element or routine, followed by
the purpose, the declaration format, and any remarks specifically
related to that entry. If any special restrictions apply, these are
also described. The cross-referenced entries and examples provide
additional information about how to use the specified entry. The
first sample procedure illustrates this format.

Sample procedure
Purpose
Declaration

Remarks
Restrictions

Unit it occupies

Description of purpose.
How the data element or routine is declared; user-defined entries are
italicized. Tables instead of declarations are used to illustrate constants
whose values cannot be changed.
Specific information about this entry.
Special requirements that relate to this entry.

See also

Related variables, constants, types, procedures, and functions that are also
described in this chapter.

Example

A sample program that illustrates how to use this entry. In cases where
the same function (for example, DiskFree) is included in more than one

Chapter 7, Library reference

Abs function

unit (for example, the Dos and WinDos units), separate program examples
are listed only if significant differences exist between the two versions.

Abs function
Purpose
Declaration

System
Returns the absolute value of the argument.
function Abs (X) ;

Remarks

X is an integer-type or real-type expression. The result, of the same type


as X, is the absolute value of X.

Example

var
r: Real;

i: Integer;
begin
r := Abs(-2.3);
i : = Abs (-157) ;
end.

Addr function
Purpose
Declaration

System
Returns the address of a specified object.
function Addr (X): Pointer;

Remarks

X is any variable, or a procedure or function identifier. The result is a


pointer that points to X. Like nil, the result of Addr is assignment
compatible with all pointer types.

See also

Dfs, Ptr, Seg

Example

var P: Pointer;
begin
P : = Addr (P) ;
end.

Append procedure
Purpose
Declaration
Remarks

{ 2.3 }
{ 157 }

{ Now points to itself }

System

Opens an existing file for appending.


procedure Append(var F: Text);

F is a text file variable that must have been associated with an external file
using Assign.

Programmer's Reference

Append procedure

Append opens the existing external file with the name assigned to F. An
error occurs if no external file of the given name exists. If F is already
open, it is closed, then reopened. The current file position is set to the end
of the file.
If a Ctrl+Z (ASCII 26) is present in the last 128-byte block of the file, the
current file position is set to overwrite the first Ctrl+Z in the block. In this
way, text can be appended to a file that terminates with a Ctrl+l.
If F was assigned an empty name, such as Assign(F, "), then, after the call
to Append, F refers to the standard output file (standard handle number 1).
After a call to Append, F becomes write-only, and the file pointer is at endof-file.
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.
See also

Assign, Close, Reset, Rewrite

Example

var F:Text;
begin
Assign{F, 'TEST.TXT');
Rewrite (F) ;
Writeln{F, 'original text');
Close (F) ;
Append (F) ;
Writeln{F, 'appended text');
Close (F) ;
end.

ArcCoordsType type
Purpose
Declaration

See also

{ Create new file }


{ Close file, save changes }
{ Add more text onto end }
{ Close file, save changes }

Graph

Used by GetArcCoords to retrieve information about the last call to Arc or


Ellipse.
type
ArcCoordsType = record
X, Y: Integer;
Xstart, Ystart: Integer;
Xend, Yend: Integer;
end;

GetArcCoords

Chapter 7, Library reference

Arc procedure

Arc procedure
Draws a circular arc from a starting angle to an ending angle.

Purpose
Declaration
Remarks

Graph

procedure Arc (X, Y: Integer; StAngle, ,EndAngle, Radius: Word);

Draws a circular arc around (X, Y), with a radius of Radius from StAngle to
EndAngle in the current drawing color.
Each graphics driver contains an aspect ratio used by Circle, Are, and
PieS lice. A start angle of 0 and an end angle of 360 draws a complete circle.
The angles for Are, Ellipse, and PieS lice are counterclockwise with 0
degrees at 3 0' clock, 90 degrees at 12 0' clock, and so on. Information about
the last call to Arc can be retrieved by GetArcCoords.

Restrictions

Must be in graphics mode.

See also ' Circle, Ellipse, FillEllipse, GetArcCoords, GetAspectRatio, PieS lice, Sector,

SetAspectRatio
Example

uses Graph;
var
Gd, Gm: Integer;
Radius: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt(l) ;
for Radius := 1 to 5 do
Arc(100, 100, 0, 90, Radius * 10);
Readln;
CloseGraph;
end.

ArcTan function
Purpose
Declaration

System

Returns the arctangent of the argument.


function ArcTan (x: Real): Real;

Remarks

X is a real-type expression. The result is the principal value, in radians, of


the arctangent of X.

See also

Cos, Sin

Programmer's Reference

ArcTan function

Example

var R: Real;

begin
R := ArcTan (Pi) ;
end.

Assign procedure
Purpose
Declaration
Remarks

System

Assigns the name of an external file to a file variable.


procedure Assign(var F; Name);

F is a file variable of any file type, and Name is a string-type expression or


an expression of type PChar if extended syntax is enabled. All further
operations on F operate on the external file with the file name Name.
After a call to Assign, the association between F and the external file
continues to exist until another Assign is done on F.
A file name consists of a path of zero or more directory names separated
by backslashes, followed by the actual file name:
Drive:\DirName\ .. . \ DirName\ Fi1 eName

If the path begins with a backslash, it starts in the root directory;

otherwise, it starts in the current directory.

Drive is a disk drive identifier (A-Z). If Drive and the colon are omitted,
the default drive is used. \DirName\ ... \ DirName is the root directory and
subdirectory path to the file name. FileName consists of a name of up to
eight characters, optionally followed by a period and an extension of up to
three characters. The maximum length of the entire file name is 79
characters.
A special case arises when Name is an empty string, that is, when
Length(Name) is zero. In that case, F becomes associated with the standard
input or standard output file. These special files allow a program to utilize
the I/O redirection feature of the DOS operating system. If assigned an
empty name, then after a call to Reset(F), F refers to the standard input file,
and after a call to Rewrite(F), F refers to the standard output file.
Restrictions

Never use Assign on an open file.

See also

Append, Close, Lst, Reset, Rewrite

Example

{Try redirecting this program from DOS to PRN, disk file, etc. }
var F: Text;

begin
Assign(F, ");

Chapter 7, Library reference

{ Standard output }

Assign procedure

Rewrite (F) ;
Writeln(F, 'standard output ... ');
Close(F);
end.

AssignCrt procedure,
Purpose
Declaration
Remarks

Crt

Associates a text file with the CRT.


procedure AssignCrt (var F: Text);
AssignC~t

works exactly like the Assign standard procedure except that no


file name is specified. Instead, the text file is associated with the CRT.

This allows faster output (and input) than would normally be possible
using standard output (or input).
Example

uses Crt;
var F: Text;
begin
Write('Output to screen or printer [S, P]? ');
if UpCase(ReadKey) = 'P' then
Assign(F, 'PRN')
{ Output to printer }
else
AssignCrt(F);
{ Output to screen, use fast CRT routines}
Rewrite (F) ;
Writeln(F, 'Fast output via CRT routines ... ');
Close(F);
end.

System

Assigned function
Purpose
Declaration

Tests to determine if a pointer or procedural variable is nil.


function Assigned(var P): Boolean;

Remarks

P must be a variable reference of a pointer or procedural type. Assigned


returns True if P is not nil, or False if nil. Assigned(P) corresponds to the
test P <> nil for a pointer variable, and @P <> nil for a procedural variable.

Example

var P: Pointer;
begin
P := nil;

if Assigned(P) then Writeln('You won't see this');


P := @P;

if Assigned(P) then Writeln('You'll see this');


end.

10

Programmer's Reference

Bar constants

Bar constants

Graph

Purpose

Constants that control the drawing of a 3-D top on a bar.

Remarks

Used by the Bar3D procedure to control whether to draw a top on' 3-D
bars.

See also

Constant

Value

Top On
TopOf!

True
False

Bar3D

Bar procedure
Purpose
Declaration
Remarks

Restrictions

Graph

Draws a bar using the current fill style and color.


procedure Bar(Xl, Yl, X2, Y2: Integer) i

Draws a filled-in rectangle (used in bar charts, for example). Uses the
pattern and color defined by SetFillStyle or SetFillPattern. To draw an
outlined bar, call Bar3D with a depth of zero.
Must be in graphics mode.

See also

Bar3D, GraphResult, SetFillStyle, SetFillPattern, SetLineStyle

Example

uses Graphi
var
Gd; Gm: Integeri
I, Width: Integeri
begin
Gd := Detecti
InitGraph(Gd, Gm, ")i
if GraphResult <> grOk then
Halt(l) ;
Width := 10i
for I := 1 to 5 do
Bar(I * width, I * 10, Suce(I) * Width, 200)
Readln;
CloseGraph;
end.

Chapter 7, Library reference

11

Bar3D procedure

Bar3D procedure
Purpose
Declaration
Remarks

Graph

Draws a 3-D bar using the current fill style and color.
procedure Bar3D(X1, Yl, X2, Y2: Integer; Depth: Word; Top: Boolean);

Draws a filled-in, three-dimensional bar using the pattern and color


defined by SetFillStyle or SetFillPattern. The 3-D outline of the bar is drawn
in the current line style and color as set by SetLineStyle and SetColor. Depth
is the length in pi~els of the 3-D outline. If Top is TopOn, a 3-D top is put
on the bar; if Top is TopOff, no top is put on the bar (making it possible to
stack several bars on top of one another).
A typical depth could be calculated by taking 25% of the width of the bar:
Bar3D(Xl, Yl, X2, Y2, (X2 - Xl

Restrictions

1) div 4, TopOn);

Must be in graphics mode.

See also

Bar, GraphResult, SetFillPattern, SetFillStyle, SetLineStyle

Example

uses Graph;
var
Gd, Gm: Integer;
YO, Yl, Y2, Xl, X2: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt(l);
YO := 10;
Yl := 60;
Y2 : = 110;
Xl := 10;
X2 := 50;
Bar3D(Xl, YO, X2, Yl, 10, TopOn);
Bar3D(Xl, Yl, X2, Y2, 10, TopOff);
Readln;
CloseGraph;
end.

BitBlt operators
Purpose

Graph

BitBlt operators used with PutImage and SetWriteMode.

Remarks . The following constant values represent the indicated logical operations.

12

Programmer's Reference

BitBlt operators

Constant

Value

CopyPut
XORPut

o (mov)

II

1 (xor)

These BitBlt constants are used by PutImage only:


OrPut
AndPut
NotPut

2(or)
3 (and)
4 (not)

BlockRead procedure
Purpose
Declaration
Remarks

System

Reads one or more records into a variable.


procedure BlockRead(var F: file; var Buf; Count: Word [ ; var Result: Word 1 );

F is an untyped file variable, Buf is any variable, Count is an expression of


type Word, and Result is a variable of type Word.
BlockRead reads Count or fewer records from the file F into memory,
starting at the first byte occupied by Buf. The actual number of complete
records read (less than or equal to Count) is returned in the optional
parameter Result. If Result is not specified, an I/O error occurs if the
number read is not equal to Count.
The entire transferred block occupies at most Count * RecSize bytes, where
RecSize is the record size specified when the file was opened (or 128 if the
record size was unspecified). An error occurs if Count * RecSize is greater
than 65,535 (64K).

Result is an optional parameter. If the entire block was transferred, Result


will be equal to Count on return. Otherwise, if Result is less than Count, the
end of the file was reached before the transfer was completed. In that case,
if the file's record size is greater than 1, Result returns the number of
complete records read; that is, a possible last partial record is not included
in Result.
The current file position is advanced by Result records as an effect of

BlockRead.
With {$I-}, IOResult returns 0 if the operation succeeded; otherwise, it
returns a nonzero error code.
Restrictions
See also

File must be open.

BlockWrite

Chapter 7, Library reference

13

BlockRead prc;>cedure

Example

program CopyFile;
{ Simple, fast file copy program with NO error-checking }
var
FromF, ToF: file;.
NumRead, NumWritten: Word;
Buf: array[1 .. 2048] of Char;
begin
Assign (FromF, ParamStr(l));
Reset (FromF, 1);
Assign(ToF, ParamStr(2));
Rewrite (ToF, 1);
Writeln('Copying " FileSize(FromF), , bytes ... ');
repeat
BlockRead(FromF, Buf, SizeOf(Buf), NumRead);
BlockWrite(ToF, Buf, NumRead, NumWritten);
until (NumRead = 0) or (NumWritten <> NumRead);
Close (FromF) ;
Close (ToF) ;
end.

BlockWrite procedure
Purpose
Declaration
Remarks

{ Open input file


{ Record size = 1
{ Open output file
{. Record size = 1

}
}
}
}

System

Writes one or more records from a variable.


procedure BlockWrite(var F: file; var Buf; Count: Word
[ ; var Result: Word] );

F is an untyped file variable, Buf is any variable, Count is an expression of


type Word, and Result is a variable of type Word.
BlockWrite writes Count or fewer records to the file F from memory,
starting at the first byte occupied by Buf. The actual number of complete
records written (less than or equal to Count) is returned in the optional
parameter Result. If Result is not specified, an I/O error occurs if the
number written is not equal to Count.
The entire block transferred occupies at Il)ost Count * RecSize bytes, where
RecSize is the record size specified when the file was opened (or 128 if the
record size was unspecified). An error occurs if Count * RecSize is greater
than 65,535 (64K).

Result is an optional parameter. If the entire block was transferred, Result


will be equal to Count on return. Otherwise, if Result is less than Count, the
disk became full before the transfer was completed. In that case, if the
file's record size is greater than I, Result returns the number of complete
records written.

14

Programmer's Reference

BlockWrite procedure

II

The current file position is advanced by Result records as an effect of the


BlockWrite.
Witl). {$I-}, IOResult returns 0 if the operation succeeded; otherwise, it
returns a nonzero error code.
Restrictions

File must be open.

See also

BlockRead

Example

See example for BlockRead.

System

Break procedure
Purpose
Declaration

Terminates a for, while, or repeat statement.


procedure Break;

Remarks

Break exits the innermost enclosing for, while, or repeat statement


immediately. Break is analogous to a goto statement addressing a label
just after the end of the innermost enclosing repetitive statement. The
compiler reports an error if Break is not enclosed by a for, while, or repeat
statement.

See also

Continue, Exit, Halt

Example

var 8: string;

begin
while True do

begin
Readln(S) ;
if S =
then Break;
Writeln(S);
II

end;
end.

ChDir procedure
Purpose
Declaration
Remarks

System

Changes the current directory.


procedure ChDir (8: String);

The string-type expression changes the current directory to the path


specified by S. If S specifies a drive letter, the current drive is also
changed.

Chapter 7, Library reference

15

ChOir procedure

With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it


returns a nonzero error code.
See also

GetDir, MkDir, RmDir. SetCurDir performs the same function, but it takes
a null-terminated string as an argument rather than a Pascal-style string.

Example

begin
{$I-}
{ Get directory n~me from command line }
ChDir(ParamStr(l));
,
if IOResult <> 0 then
Writeln(/Cannot find directory/);
end.

CheckBreak variable
Purpose
Declaration

Crt

Enables and disables checks for Ctrl+Break.


var CheckBreak: Boolean;

Remarks

When CheckBreak is True, pressing Ctrl+Break aborts the program when it


next writes to the display. When CheckBreak is False, pressing Ctrl+Break,
has no effect. CheckBreak is True by default. (At run time, Crt stores the old
Ctrl+Break interrupt veCtor, $lB, in a global pointer variable called
SavelntlB.)
/

See also

KeyPressed, ReadKey, SavelntlB

CheckEOF variable
Purpose
Declaration
Remarks

Crt

Enables and disables the end-of-file character.


var CheckEOF: Boolean;

When CheckEOF is True, an end-of-file character is generated if you press


Ctrl+Zwhile reading from a file assigned to the screen. When CheckEOF is
False, pressing Ctrl+Zhas no effect. CheckEOF is False by default.

CheckSnow variable
Purpose
Declaration

16

Crt

Enables and disables "snow-checking" on eGA video adapters.


var CheckSnow: Boolean;

Programmer's Reference

CheckSnow variable

Remarks

On most CGAs, interference will result if characters are stored in video


memory outside the horizontal retrace intervals. This does not occur with
monochrome adapters, EGAs, or VGAs.
When a color text mode is selected, CheckS now is set to True, and direct
video-memory writes will occur only during the horizontal retrace
intervals. If you are running on a newer CGA, you might want to set
CheckS now to False at the beginning of your program and after each call to
TextMode. This will disable snow-checking, resulting in significantly
higher output speeds.

Restrictions
See also

CheckS now has no effect when Direct Video is False.


Direct Video

Chr function
Purpose
Declaration

System
Returns a character with a specified ordinal number.
function Chr (X: Byte): Chari

Remarks

Returns the character with the ordinal value (ASCII value) of the bytetype expression, X.

See also

Ord

Example

var I: Integer i
begin
for I := 32 to 255 do Write(Chr(I))i
end.

Circle procedure
Purpose
Declaration
Remarks
Restrictions
See also

Graph

Draws a circle using (X, Y) as the center point.


procedure Circle (X, Y: Integer i Radius: Word) i

Draws a circle in the current color set by SetColor. Each graphics driver
contains an aspect ratio used by Circle, Arc, and PieS lice.
Must be in graphics mode.

Arc, Ellipse, FillEllipse, GetArcCoords, GetAspectRatio, PieS lice, Sector,


SetAspectRatio

Chapter 7, Library reference

17

Circle procedure

Example

uses Graph;
var
Gd, Gm: Integer;
Radius: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);
for Radius := 1 to 5 do
Circle(100, 100, Radius * 10);
Readlni
CloseGraph;
end.

ClearDevice procedure
Purpose
Declaration
Remarks
Restrictions

18

Graph

Clears the graphics screen and prepares it for output.


procedure ClearDevice;

ClearDevice moves the current pointer to (0,0), clears the screen using th~
background color set by SetBkColor, and prepares it for output.
Must be in graphics mode.

See also

Clear ViewPort, CloseGraph, GraphDefaults, InitGraph, RestoreCrtMode,


SetGraphMode

Example

uses Crt, Graph;


var Gd, Gm: Inte~er;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt(l);
Randomize;
repeat
LineTo(Random(200), Random(200));
until KeyPressed;
ClearDevice;
Readln;
CloseGraph;
end.

Programmer's Reference

ClearViewPort procedure

ClearViewPort procedure
Purpose
Declaration
Remarks
Restrictions

Graph

Clears the current viewport.


procedure ClearViewPort;

Sets the fill color to the background color (Palette[O]) and moves the
current pointer to (0, 0).
Must be in graphics mode.

See also

ClearDevice, GetViewsettings, Set ViewPort

Example

uses Graph;
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);

Rectangle (19, 19, GetMaxX - 19, GetMaxY - 19);


SetViewPort(20, 20, GetMaxX - 20, GetMaxY - 20, ClipOn);
OutTextXY(O, 0, '<ENTER> clears viewport:');
Readln;
ClearViewPort;
OutTextXY(O, 0, '<ENTER> to quit:');
Readln;
CloseGraph;
end.

Clipping constants
Purpose
Remarks

See also

Graph

Constants that control clipping; used with SetViewPort.


With clipping on, graphics output is clipped at the viewport boundaries:
Constant

Value

ClipOn
ClipOfJ

False

True

Set ViewPort

Chapter 1, Library reference

19

Close procedure

System

Close procedure
Purpose
Declaration
Remarks

Closes an open file.


procedure Close (var F);

F is a file variable of any file type previously opened with Reset, Rewrite,
or Append. The external file associated with F is completely updated and
then closed, freeing its DOS file handle for reuse.
With {$I-}, IOResult returns a if the operation was successful; otherwise, it
returns a nonzero error code.

See also

Append, Assign, Reset, Rewrite

Example

var F: file;
begin
Assign(F, '\AUTOEXEC.BAT');
Reset(F,l);
Writeln('File size = " FileSize(F));
Close(F);
end.

CloseGraph procedure
Purpose
Declaration
Remarks

Restrictions

{ Open file }

{ Close file }

Graph

Shuts down the graphics system.


procedure CloseGraph;

CloseGraph restores the original screen mode before graphics was


initialized and frees the memory allocated on the heap for the graphics
scan buffer. Close Graph also de allocates driver and font memory buffers if
they were allocated by calls to GraphGetMem and GraphFreeMem.
Must be in graphics mode.

See also

DetectGraph, GetGraphMode, InitGraph, RestoreCrtMode, SetGraphMode

Example

uses Graph;
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;

Line(O, 0, GetMaxX, GetMaxY);

20

Programmer's Reference

CloseGraph procedure

Readlni
CloseGraphi
end.

{ Shut down graphics}

Crt

ClrEol procedure
Purpose
Declaration
Remarks

Clears all characters from the cursor position to the end of the line
without moving the cursor.
procedure ClrEol i

All character positions are set to blanks with the currently defined text
attributes. Thus, if TextBaekground is not black, the current cursor position
to the right edge becomes the background color.

ClrEol is window-relative. The following program lines define a text


window and clear the current line from the cursor position (1, 1) to the
right edge of the active window (60, 1).
Window(I, I, 60, 20)i
ClrEoli

See also

ClrSer, Window

Example

uses Crt i
begin
TextBackground(LightGray)
ClrEoli
end.

ClrScr procedure
Purpose
Declaration
Remarks

{ Changes cleated columns to LightGray background}

Crt

Clears the active window and places the cursor in the upper left corner.
procedure ClrScr i

Sets all character positions to blanks with the currently defined text
attributes. Thus, if TextBaekground is not black, the entire screen becomes
the background color. This also applies to characters cleared by ClrEol,
InsLine, and DelLine, and to empty lines created by scrolling.

Chapter 1, Library reference

21

I!IIII

ClrScr procedure

ClrSer is window-relative. The following program lines define a text


window and clear a 60x20 rectangle beginning at (1,1).
Window(l, 1, 60, 20);
ClrScr;

See also

ClrEol, Window

Example

uses Crt;
begin
TextBackground(LightGray);
ClrScr;
end.

{ Changes entire window to LightGray background }

Color constants
Purpose
Remarks

Graph

Color constants used by SetPalette and SetAllPalette.


Constant

Black
Blue
Green
Cyan
Red
AJagenta
Brown
LightGray
DarkGray
LightBlue
LightGreen
LightCyan
LightRed
LightAJagenta
Yellow
White

See also

Value

0
1
2
3
4

5
6
7
8
9
10

11
12
13

14
15

SetAllPalette, SetPalette, SetColor

Color.constants for SetRGBPalette

22

Graph

Purpose

Constants that can be used with SetRGBPalette to select the standard EGA
colors on an IBM 8514 graphics adapter.

Remarks

The following EGA color constant values are defined:

Programmer's Reference

Color constants for SetRGBPalette

Constant
EGABlack
EGABlue
EGAGreen
EGACyan
EGARed
EGAMagenta
EGABrown
EGALightGray
EGADarkGray
EGALightBlue
EGALight Green
EGALightCyan
EGALightRed
EGALightMagenta
EGAYellow
EGA White

See also

o (dark colors)
1
2
3
4

20
7

56 (light colors)

57
58

59
60
61

62
63

SetRGBPalette

Concat function
Purpose
Declaration
Remarks

Value

System

Concatenates a sequence of strings.


function Concat (Sl [ , S2' ... , SN

l: String): String;

Each parameter is a string-type expression. The result is the concatenation


of all the string parameters. If the resulting string is longer than 255
characters, it is truncated after the 255th character. Using the plus (+)
operator returns the same result as using the Concat function:
S := 'ABC' + 'DEF';

See also

Copy, Delete, Insert, Length, Pos

Example

var S: String;
begin
S := Concat('ABC', 'DEF');
end.

Continue procedure
Purpose
Declaration

{ , ABCDEF' }

System

Continues a for, while, or repeat statement.


procedure Continue;

Chapter 7, Library reference

23

Continue procedure

Remarks

Continue causes the innermost enclosing for, while, or repeat statement to


immediately proceed with the next iteration. The compiler will report an
error if a call to Continue is not enclosed by a for, while, or repeat
statement.

See also

Break, Exit, Halt

Example

var
I: Integer;
Name: string[79];
F: file;
begin
for I := 1 to ParamCount do
begin
Name := ParamStr(I);
Assign(F, Name);
{$I-}
Reset(F,l);
{$It}
if IOResult <> 0 then
begin
Writeln('File not found: ' Name);
Continue;
end;
Writeln(Name, ': " FileSize(F) , ' bytes');
Close(F) ;
end;
end.

Copy function
Purpose
Declaration

24

System
Returns a substring of a string.
function Copy (S: String; Index: Integer; Count: Integer): String;

Remarks

S is a string-type expression. Index and Count are integer-type expressions.


Copy returns a string containing Count characters starting with the Indexth
character in S. If Index is larger than the length of S, Copy returns an empty
string. If Count specifies more characters than remain starting at the
Indexth position, only the remainder of the string is returned.

See also

Concat, Delete, Insert, Length, Pos

Programmer's Reference

Copy function

Example

var S: string;
begin
S : =: 'ABCDEF';
{ 'BCD' }

S := Copy(S, 2, 3);

end.

Cos function
Purpose
Declaration

System
Returns the cosine of the argument.
function Cos (X: Real): Real;

Remarks

X is a real-type expression. The result is the cosine of X where X


represents an angle in radians.

See also

ArcTan, Sin

Example

var R: Real;
begin
R := Cos(Pi);
end.

CreateDir procedure
Purpose
Declaration

WinDos

Creates a new subdirectory.


procedure CreateDir (Dir: PChar);

Remarks

The subdirectory to be created is specified in Dir. Errors are reported in


DosError. MkDir performs the same function as CreateDir, but it takes a
Pascal-style string as an argument rather than a null-terminated string.

See also

GetCurDir, SetCurDir, RemoveDir

Crt mode constants


Purpose

Crt

Used to represent Crt text and line modes.

Remarks BW40, C040, BW80, and C080 represent the four color text modes

supported by the IBM PC Color/Graphics Adapter (CGA). The Mono


constant represents the single black-and-white text mode supported by
the IBM PC Monochrome Adapter. Font8x8 represents EGA/VGA 43- and
50-line modes and is used with C080 or LastMode. LastMode returns to the
last active text mode after using graphics.

Chapter 7, Library reference

25

Crt mode constants

Constant
BW40
BWBO

Mono
C040
COBO

FontBxB
C40
CBO

See also

Value

o
2
7
1
3
256
C040
C080

Description
40x25 B /W on color adapter
80x25 B /W on color adapter
80x25 B/W on monochrome adapter
40x25 color on color adapter
80x25 color on color adapter
For EGA/VGA 43 and 50 line
For Turbo Pascal 3.0 compatibility
For Turbo Pascal3.0 compatibility

TextMode

CSeg function
Purpose
Declaration

System
Returns the current value of the CS register.
function CSeg: Word;

Remarks

The result of type Word is the segment address of the code segment within
which CSeg was called.

See also

DSeg, SSeg

.DateTime type
Purpose

Declaration

26

Dos

UnpackTime and PackTime use variables of DateTime type to examine and


construct 4-:byte, packed date-and-time values for the GetFTime, SetFTime,
FindFirst, and FindNext procedures.
type
DateTirne = record
Year, Month, Day, Hour, Min, Sec: Word;
end;

Remarks

Valid ranges are Year 1980 .. 2099, Month 1..12, Day 1..31, Hour 0.. 23, Min
0..59, and Sec 0..59.

See also

FindFirst, FindNext, GetFTime, SetFTime

Programmer's Reference

Dec procedure

Dec procedure
Purpose
Declaration
Remarks

System

Decrements a variable.
procedure Dec (var X [ ; N: Longint 1 );

X is an ordinal-type variable or a variable of type PChar if the extended


syntax is enabled, and N is an integer-type expression. X is decremented
by 1, or by N if N is specified; that is, Dee(X) corresponds to X := X-I,
and Dee(X, N) corresponds to X := X - N.

Dec generates optimized code and is especially useful in a tight loop.


See also

Inc, Pred, Suee

Example

var
IntVar: Integer;
LongintVar: Longint;

begin
Dec (IntVar) ;
Dec (LongintVar, 5);

{ IntVar := IntVar - 1
{ LongintVar := LongintVar - 5

end.

Delay procedure
Purpose
Declaration
Remarks

Crt

Delays a specified number of milliseconds.


procedure Delay (Ms: Word);

Ms specifies the number of milliseconds to wait.


Delay is an approximation, so the delay period will not last exactly Ms
milliseconds.

Delete procedure
Purpose
Declaration
Remarks

System

Deletes a substring from a string.


procedure Delete (var S: String; Index: Integer; Count: Integer);

5 is a string-type variable. Index and Count are integer-type expressions.


Delete deletes Count characters from 5 starting at the Indexth position. If
Index is larger than the length of 5, no characters are deleted. If Count

Chapter 7, Library reference

27

II

Delete procedure

specifies more characters than remain starting at the Indexth position, the
remainder of the string is deleted.
See also

Concat, Copy, Insert, Length, Pos

DelUne procedure
Purpose
Declaration
Remarks

Crt

Deletes the line containing the cursor:


procedure DelLine i

The line containing the cursor is deleted, and all lines below are moved
one line up (using the BIOS scroll routine). A new line is added at the
bottom.
All charader positions .are set to blanks with the currently defined text
attributes. Thus, if TextBackground is not black, the new line becomes the
background color.

Example

DelLine is window-relative. The following example will delete the first line
in the window, which is the tenth line on the screen.
Window(l, 10, 60, 20) i
DelLinei

See also

InsLine, Window

DetectGraph procedure
Purpose
Declaration
Remarks

Graph

Checks the hardware and determines which graphics driver and mode to
use.
procedure DetectGraph (var GraphDriver, GraphMode: Integer) i

Returns the detected driver and mode value that can be passed to
InitGraph, which will then load the correct driver. If no graphics hardware
was detected, the GraphDriver parameter and GraphResult returns a value
of grNotDetected. See page 33 for a list of driver and mode constants.
Unless instructed otherwise, In it Graph calls DetectGraph, finds and loads
the correct driver, and initializes the graphics system. The only reason to
call DetectGraph directly is to override the driver that DetectGraph recommends. The example that follows identifies the system as a 64K or 256K
EGA, and loads the CGA driver instead. When you pass InitGraph a
GraphDriver other than Detect/you must also pass in a valid GraphMode for
the driver requested.
.

28

Programmer's Reference

DetectGraph procedure

Restrictions

You should not use DetectGraph (or Detect with InitGraph) with the IBM
8514 unless you want the emulated VGA mode.

See also

CloseGraph, Driver and mode, GraphResult, InitGraph

Example

uses Graph;
var GraphDriver GraphMode: Integer;
begin
DetectGraph(GraphDriver GraphMode);
if (GraphDriver = EGA) or
(GraphDriver = EGA64) then
begin
GraphDriver := CGA;
GraphMode := CGAHi;
end;
InitGraph(GraphDriver GraphMode II);
if GraphResult <> grOk then
Halt (1);
Line(OI 0 GetMaxX I GetMaxY);
Readln;
CloseGraph;
end.

DirectVideo variable
Purpose
Declaration
Remarks

Crt

Enables and disables direct memory access for Write and Writeln
statements that output to the screen.
var DirectVideo: .Boolean;

When DirectVideo is True, Writes and Writelns to files associated with the
CRT will store characters directly in video memory instead of calling the
BIOS to display them. When DirectVideo is False, all characters are written
through BIOS calls, which is a significantly slower process.

DirectVideo always defaults to True. If, for some reason, you want
characters displayed through BIOS calls, set DirectVideo to False at the
beginning of your program and after each call to TextMode.
See also

CheckS now

Chapter 7, Library reference

29

DiskFree function

DiskFree function
Purpose
Declaration

Dos, WinDos

Returns the number of free bytes on a specified disk drive.


function DiskFree(Drive: Byte): Longinti

Remarks

A Drive of Dindicates the default drive, 1 indicates drive Af 2 indicates Bf


and so on. DiskFree returns -1 if the drive number is invalid.

See also

DiskSize, GetDir

Example

uses Dos i
begin
Writeln(DiskFree(O) div 1024, , Kbytes free')i
end.

{ or WinDos }

DiskSize function
Purpose
Declaration

Dos, WinDos

Returns the total size in bytes on a specified disk drive.


function DiskSize(Drive: Byte): Longinti

Remarks

A Drive ofD indicates the default drive, 1 indicates drive Af 2 indicates Bf


and so on. DiskSize returns -1 if the drive number is invalid.

See also

DiskFree GetDir

Example

uses Dos i
begin
Writeln(DiskSize(O) div 1024, , Kbytes capacity') i
end.

Dispose procedure
Purpose
Declaration
Remarks

{ or WinDos }

System

Disposes of a dynamic variable.


procedure Dispose (var, P: ,Pointer [ , Destructor] ) i

P is a variable of any pointer type previously assigned by the New


procedure or assigned a meaningful value by an assignment statement.
Dispose destroys the variable referenced by P and returns its memory
region to the heap. After a call to Dispose, the value of P becomes ,
undefined and it is an error to subsequently reference PA.

Dispose allows a destructor call as a second parameter, for disposing a


dynamic object type variable. In this case, P is a pointer variable pointing

30

Programmer's Reference

Dispose procedure

to an object type, and Destructor is a call to the destructor of that object


type.
Restrictions

If P does not point to a memory region in the heap, a run-time error


occurs.

For a complete discussion of this topic, see "The heap manager" in


Chapter 19 of the Language Guide.
See also

FreeMem, GetMem, New

Example

type Str18 = string[18];


var P: "Str18;
begin
New(P) ;
P" := INow you see it .. . 1;
Dispose(P) ;
end.

DosError variable.
Purpose
Declaration
Remarks

{ Now you don/t ... }

Dos, WinDos

Used by many Dos and WinDos routines to report errors.


var DosError: Integer;

The values stored in DosError are DOS error codes. A value of 0 indicates
no error; other possible error codes include the following:
DOS error code

2
3

5
6

8
10
11

18

Meaning

File not found


Path not found
Access denied
Invalid file handle
Not enough memory
Invalid environment
Invalid format
No more files

See Chapter 4, "Error messages/' for a detailed description of DOS error


messages.
See also

CreateDir, Exec, FindFirst, FindNext, GetCurDir, GetFAttr, GetFTime,


RemoveDir, SetCurDir, SetFAttr, SetFTime

Chapter 7, Library reference

31

DosExitCode fun~tion

DosExitCode function
Purpose
Declaration
Remarks

Dos

Returns the exit code of a subprocess.


function DosExi tCode: Wo~d;

The low byte is the code sent by the terminating process. The high byte is
set to
0 for normal termination
1 if terminated by Ctr/+C
.2 if terminated due to a device error
3 if terminated by the Keep procedure

See also

Exec, Keep

DosVersionfunction
Purpose
Declaration

Dos, WinDos

Returns the DOS version number.


function DosVersion: Word;

Remarks

Dos Version returns the DOS version number. The low byte of the result is
the major version number, and the high byte is the minor version number.
For example, DOS 3.20 returns 3 in the low byte, and 20 in the high byte.

Example

uses Dos;
var Ver: Word;
begin
Ver := DosVersion;
Writeln('This is DOS version', Lo(Ver),
end.

See also

{ or WinDos }

Hi (Ver));

Hi, Lo

DrawPoly procedure
Purpose
Declaration
Remarks

32

Graph

Draws the outline of a polygon using the current line style and color.
procedure DrawPoly (NumPoints: Word; var PolyPoints);

PolyPoints is an untyped parameter that contains the coordinates of each


intersection in the polygon. NumPoints specifies the number of coordinates in PolyPoints. A coordinate consists of two words, an X and a Y
value.

Programmer's Reference

DrawPoly procedure

DrawPoly uses the current line style and color. Use SetWriteMode to
determine whether the polygon is copied to or XORed to the screen.
Note that in order to draw a closed figure with N vertices, you must pass
N + 1 coordinates to DrawPoly, where

PolyPoints[N + 1] = PolyPoints[l]
In order to draw a triangle, for example, four coordinates must be passed
to DrawPoly.
Restrictions

Must be in graphics mode.

See also

FillPoly, GetLineSettings, GraphResult, SetColor, SetLineStyle, SetWriteMode

Example

uses Graph;
const
Triangle: array [1. .4] of PointType = ((X: 50; Y: 100), (X: 100; Y: 100),
(X: 150; Y: 150), (X: 50; Y: 100));
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);
DrawPoly(SizeOf(Triangle) div SizeOf(PointType), Triangle);
Readln;
CloseGraph;
end.

Driver and mode constants

Graph

Purpose

Used with routines that call graphics drivers and color palettes.

Remarks

The following tables list graphics drivers and color palettes.

Table 1.1
Graph unit driver
constants

Driver Constant

Detect
CGA
MCGA
EGA
EGA64
EGAMono
IBM8514
HercMono

Chapter 7, Library reference

{ 4 }

Value

0
1
2
3
4
5
6
7

Meaning

Requests autodetection
CGAmode
MCGAmode
EGA mode
EGA64 mode
EGAMono mode
IBM8514 mode
HercMono mode

33

Driver and mode constants

Table 1.1: Graph unit driver constants (continued)

ATT400
VGA
PC3270
CurrentDriver

8
9
10
-128

ATT400mode
VGAmode
PC3270mode
Passed to GetModeRange

Table 1.2: Graph unit mode constants


Constant
Name

Column
Value

Palette

Colors

Pages

ATT400CO
ATT400Cl
ATT400C2
ATT400C3
ATT400Med
ATT400Hi

0
1
2
3
4
5

320x200
320x200
320x200
320x200
640x200
640x400

0
1
2
3

LightGreen, LightRed, Yellow


LightCyan, LightMagenta, White
Green, Red, Brown
Cyan, Magenta, LightGray

1
1
1
1

CGACO
CGACl
CGAC2
CGAC3
CGAHi

0
1
2
3
4

320x200
320x200
320x200
320x200
640x200

0
1
2
3

LightGreen, LightRed, Yellow


LightCyan, LightMagenta, White
Green, Red, Brown
Cyan, Magenta, LightGray

1
1
1
1

EGALo
EGAHi
EGA64Lo
EGA64Hi
EGAMonoHi

0
1
0
1
3

640x200
640x350
640x200
640x350
640x350

16 color
16 color
16 color
4 color
64Kon catd,
256K on card

4
2
1
1
1
2

HercMonoHi

720x348

IBM8514Lo
IBM8514Hi

0
1

640x480
1024x768

MCGACO
MCGACl
MCGAC2
MCGAC3
MCGAMed
MCGAHi

0
1
2
3
4
5

320x200
320x200
320x200
320x200
640x200
640x480

PC3270Hi

720x350

VGALo
VGAMed
VGAHi

0
1
2

640x200
640x350
640x480

See also

34

x Row

256 colors
256 colors
0
1
2
3

LightGreen, LightRed, Yellow


LightCyan, LightMagenta, White
Green, Red, Brown
Cyan, Magenta, LightGray

1
1
1
1

16 color
16 color
16 color

4
2
1

DetectGraph, GetModeRange, InitGraph

Programmer's Reference

DSeg function

DSeg function
Purpose
Declaration

System
Returns the current value of the DS register.
function DSeg: Word;

Remarks

The result of type Word is the segment address of the data segment.

See also

CSeg, SSeg

Ellipse procedure
Purpose
Declaration
Remarks

Graph

Draws an elliptical arc from start angle to end angle, using (X, Y) as the
center point.
procedure Ellipse(X, Y: Integer; StAngle, EndAngle: Word;
YRadius, YRadius: Word);

Draws an elliptical arc in the current color using (X, Y) as a center point,
and XRadius and YRadius as the horizontal and vertical axes travelling
from StAngle to EndAngle.
A start angle of 0 and an end angle of 360 draws a complete oval. The
angles for Are, Ellipse, and PieS lice are counterclockwise with 0 degrees at
3 o'clock, 90 degrees at 12 0' clock, and so on. Information about the last
call to Ellipse can be retrieved by GetArcCoords.

Restrictions

Must be in graphics mode.

See also

Are, Circle, FillEllipse, GetArcCoords, GetAspectRatio, PieS lice, Sector,


SetAspectRatio

Example

uses Graph;
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);

Ellipse(100, lOa, a, 360, 30, 50);


Ellipse(100, lOa, a, 180, 50, 30);
Readln;
CloseGraph;
end.

Chapter 7, Library reference

35

EnvCount function

EnvCount function
Purpose
Declaration
Remarks

Dos

Returns the number of strings contained in the DOS environment.


function EnvCount: Integer i

EnvCount returns the number of strings contained in the DOS


environment. Each environment string is of the form V AR= V ALUE. The
strings can be examined with the EnvStr function.

For more information about the DOS environment, see your DOS
manuals.
See also

EnvStr, GetEnv

Example

uses Dos i
var I: Integeri
begin
for I := 1 to EnvCount do
Writeln(EnvStr(I)) i
end.

EnvStr function
Purpose
Declaration
Remarks

Dos

Returns a specified environment string.


function EnvStr (Index: Integer): String i

EnvStr returns a specified string from the DOS environment. The string
EnvStr returns is of the form VAR= VALUE. The index of the first string is
one. If Index is less than one or greater than EnvCount, EnvStr returns an

empty string.
For more information about the DOS environment, see your DOS
manuals.
See also

EnvCount, GetEnv

Eaf function (text files)


Purpose
Declaration
Remarks

36

System

Returns the end-of-file status of a text file.


function Eof [ (var F: Text) l: Booleani

F, if specified, is a text file variable. If F is omitted, the standard file


variable Input is assumed. Eof(F) returns True if the current file position is

Programmer's Reference

Eof function (text files)

beyond the last character of the file or if the file contains no components;
otherwise, Eof(F) returns False.
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.
See also

Eoln,SeekEof

Example

var
F: Text;
Ch: Char;
begin
{ Get file to read from command line }
Assign(F, ParamStr(l));
Reset(F);
while not Eof(F) do
begin
Read (F, Ch);
Write (Ch) ;
end;
end.

Eof function (typed, untyped files)


Purpose
Declaration
Remarks

{ Dump text file }

System

Returns the end-of-file status of a typed or untyped file.


function Eof (var F): Boolean;

F is a file variable. Eof(F) returns True if the current file position is beyond
the last component of the file or if the file contains no components;
otherwise, Eof(F) returns False.
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.

Eoln function
Purpose
Declaration
Remarks

System
Returns the end-of-line status of a text file.
function Eoln [(var F: Text) 1: Boolean;

F, if specified, is a text file variable. If F is omitted, the standard file


variable Input is assumed. Eoln(F) returns True if the current file position
is at an end-of-line marker or if Eof(F) is True; otherwise, Eoln(F) returns
False.

Chapter 7, Library reference

37

Eoln function

With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it


returns a nonzero error code.
See also

Eof, SeekEoln

Erase procedure
Purpose
Declaration
Remarks

System

Erases an external file.


procedure Erase (var F);

F is a file variable of any file type. The external file associated with F is
erased.
With {$I.;.}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.

Restri~tions

38

Never use Erase on an open file.

See also

Rename

Example

var
F: file;
Ch: Char;
begin
{ Get file to delete from command line }
Assign(F, ParamStr(l));
{$I-}
Reset(F);
{$It}
if IOResult <> 0 then
Writeln('Cannot find' ParamStr(l))
else
begin
Close (F) ;
Write('Erase " ParamStr(l) , '? ');
Readln (Ch) ;
if UpCase(Ch) = 'Y' then
Erase (F) ;
end;
end.

Programmer's Reference

ErrorAddr variable

ErrorAddr variable
Purpose
Declaration
Remarks

System

Contains the address of the statement causing a run-time error.


var ErrorAddr: Pointer;

If a program terminates normally or stops due to a call to Halt, ErrorAddr


~s nil. If a program ends because of a run-time error, ErrorAddr contains

the address of the statement in error. For additional information, see "Exit
procedures" in Chapter 20 in the Language Guide.
See also

ExitCode, ExitProc

Exclude procedure
Purpose
Declaration
Remarks

System

Excludes an element from a set.


procedure Exclude (var S: set of T; I: T);

5 is a set type variable, and I is an expression of a type compatible with


the base type of S. The element given by I is excluded from the set given
by S. The construct
Exclude (S, I)

corresponds to
S:=S-[1]

but the Exclude procedure generates more efficient code.


See also

Include

Dos

Exec procedure
Purpose
Declaration
Remarks

Executes a specified program with a specified command line.


procedure Exec (Path, CmdLine: String);

The program name is given by the Path parameter, and the command line
is given by c,mdLine. To execute a DOS internal command, run '
COMMAND. COM; for instance,
Exec('\COMMAND.COM', , IC D1R *.PAS');

Chapter 7, Library reference

39

II

Exec procedure

The Ie in front of the command is a requirement of COMMAND.COM


(but not of other applications). Errors are reported in DosError. The exit
c~de of any child process is reported by the Dos Exit Code function.
It is recommended that Swap Vectors be called just before and just after the

call toExec. Swap Vectors swaps the contents of the SavelntXX pointers in
the System unit with the current contents of the interrupt vectors. This
ensures that the Exec'd process does not use any interrupt handlers
installed by the current process, and vice versa.

Exec does not change the memory allocation state before executing the
program. Therefore, when compiling a program that uses Exec, be sure to
reduce the maximum heap size using a $M compiler directive; otherwise,
there won't be enough memory (DosError = 8).
See also

DosError, DosExitCode, SavelntXX, Swap Vectors

Example

{$M $4000,O,O}
{ 16K stack, no heap required or reserved }
uses Dos;
var ProgramName, CmdLine: String;
begin
Write('Program to Exec (include full path): ');
Readln(ProgramName) ;
write('Command line to pass to " ProgramName, ': ');
Readln(CmdLine);
writeln('About to Exec ... ');
SwapVectors;
Exec (ProgramName, CmdLine);
SwapVectors;
Writeln(' ... back from Exec');
{ Error? }
if DosError <> 0 then
Writeln('Dos error #', DosError)
else
Writeln('Exec successful. Child process exit code =' DosExitCode);
end.

Exit procedure
Purpose
Declaration
Remarks

40

System

Exits immediately from the current block.


procedure Exi t ;

Executed in a subroutine (procedure or function), Exit causes the


subroutine to return. Executed in the statement part of a program, Exit
causes the program to terminate. A call to Exit is analogous to a goto
statement addressing a label just before the end of a block.

Programmer's Reference

Exit procedure

See also

Halt

Example

procedure WasteTime;
begin
repeat
if KeyPressed then Exit;
Write('Xx');
until False;
end;

II

begin
WasteTime;
end.

ExitCode variable
Purpose
Declaration

System

Contains the application's exit code.


var ExitCode: Integer;

Remarks

An exit procedure can learn the cause of termination by examining


ExitCode.1f a program terminates normally, ExitCode is zero. If a program
stops through a call to Halt, ExitCode contains the value passed to Halt. If a
program ends due to a run-time error, ExitCode contains the error code.

See also

ErrorAddr, ExitProc, and Chapter 20, "Control issues," in the Language


Guide for more information about exit procedures.

ExitProc variable
Purpose
Declaration

System

Implements an application's exit procedure list.


var ExitProc: Pointer;

Remarks

ExitProc lets you install an exit procedure to be called as part of a


program's termination, whether it is a normal termination, a termination
through a call to Halt, or a termination due to a run-time error.

See also

ErrorAddr, ExitCode, and Chapter 20, "Control issues," in the Language


Guide for more information about exit procedures.

Chapter 7, Library reference

41

Expfunction

Exp function
Purpose
Declaration

System
Returns the exponential of the argument.
function Exp (X: Real): Reali

Remarks

X is a real-type expression. The result is the exponential of X; that is, the


value e raised to the power of X, where e is the base of the natural
logarithms.

See also

Ln

WinDos

fcXXXX flag constants


Purpose
Remarks

See also

Return flags used by the function FileSplit.


The followingfxXXXX constants are defined:
Constant

Value

fcExtension
fcFileName
fcDirectory
fcWildcards

$0001
$0002
$0004
$0008

FileSplit

Dos

FExpand function
Purpose
Declaration
Remarks

Expands a file name into a fully qualified file name.


function FExpand(Path: PathStr): PathStri

Expands the filename in Path into a fully qualified file name. The
resulting name is converted to uppercase and consists of a drive letter, a
colon, a root relative directory path, and a file name. Embedded '.' and ' .. '
directory references are removed.
The PathStr type is defined in the Dos unit as string[79].
Assuming that the current drive and directory is C: \ SOURCE \ PAS, the
following FExpand calls would produce these values:
FExpand('test.pas')
FExpand(' .. \*.TPU')
FExpand('c:\bin\turbo.exe')

42

'C:\SOURCE\PAS\TEST.PAS'
'C:\SOURCE\*.TPU'
'C:\BIN\TURBO.EXE'

Programmer's Reference

FExpand function

FSplit can separate the result of FExpand into a drivel directory string, a
file-name string, and an extension string.
See also

FileExpand, FindFirst, FindNext, FSplit, File-handling string types

Dos, WinDos

File attribute constants


Purpose

Used to construct file attributes in connection with the GetFAttr, SetFAttr,


FindFirst, and FindNext procedures.

Remarks

These are the file attribute constants defined in the Dos and WinDos units.
Dos Constant

WinDos Constant

Value

ReadOnly
Hidden
SysFile
VolumeID
Directory
Archive
AnyFile

faReadOnly
faHidden
faSysFile
faVolumeID
faDirectory
faArchive
faAnyFile

$01
$02
$04
$08
$10
$20
$3F

The constants are additive, that is, the statement


FindFirst('*.*', ReadOnly + Directory,

S)i

{ Dos }

or
FindFirst('*.*', faReadOnly + faDirectory, S) i

{ WinDos }

will locate all normal files as well as read-only files and subdirectories in
the current directory. The AnyFile (orfaAnyFile) constant is simply the
sum of all attributes.
See also

FindFirst, FindNext, GetFAttr, SetFAttr

File name length constants


Purpose
Remarks

WinDos

Contain the maximum file name component string lengths used by the
functions FileSearch and FileExpand.
The following file name length constants are defined:

Chapter 7, Library reference

43

File name length constants

Constant

fsPathName
fsDirectory
fsFileName
fsExtension
See also

Value

79

67
8

FileSearch, FileSplit

WinDos

FileExpand function
Purpose
Declaration
Remarks

Expands a file name into a fully qualified file name.


function FileExpand(Dest, Name: PChar): PChari

Expands the file name in Name into a fully qualified file name. The
resulting name is converted to uppercase and consists of a drive letter, a
colon, a root relative directory path, and a file name. Embedded '.' and ' .. '
directory references are removed, and all name and extension components
are truncated to 8 and 3 characters respectively. The returned value is
Dest. Dest and Name can refer to the same location.
Assuming that the current drive and directory is C: \SOURCE\PAS, the
following FileExpand calls would produce these values:
'test.pas') = 'C: \SOURCE\PAS\TEST. PAS'
FileExpand(S, ' .. \*.TPW') = 'C:\SOURCE\*.TPW'
FileExpand(S, 'c:\bin\turbo.exe') = 'C:\BIN\TURBO.EXE'

FileExp~nd(S,

The FileSplit function can be used to split the result of FileExpand into a
drive / directory string, a file-name string, and an extension string.
See also

FExpand, FindFirst, File name lengths, FindNext, FileSplit

File-handling string types


Purpose

String types are used by various procedures and functions in the Dos unit.

Remarks

The following string types are defined:


ComStr = string[127] i
PathStr = string[79] i
DirStr = string[67]i
NameStr::: string[8];
ExtStr = string[4];

See also

44

Dos

{ Command-line
{ Full file path
{ Drive and directory
{ File-name
{ File-extension

string}
string }
string }
string }
string }

FExpand, FSplit

Programmer's Reference

File Mode variable

FileMode variable
Purpose
Declaration
Remarks

System

Determines the access code to pass to DOS when typed and untyped files
are opened using the Reset procedure.
var FileMode: Byte;

The range of valid FileMode values depends on the version of DOS in use.
For all versions, however, the following modes are defined:

o
1
2

Read only
Write only
Read/Write

The default value, 2, allows both reading and writing. Assigning another
value to FileModecauses all subsequent Resets to use that mode. New files
using Rewrite are always opened in read/write mode (that is,
FileMode = 2).
DOS version 3.x and higher defines additional modes, which are
primarily concerned with file-sharing on networks. For more details, see
your DOS programmer's reference manual.
See also

Rewrite

FilePos function
Purpose
Declaration
Remarks

System

Returns the current file position of a file.


function FilePos (var F): Longinti

F is a file variable. If the current file position is at the beginning of the file,
FilePos(F) returns O. If the current file position is at the end of the file-that
is, if Eof(F) is True-FilePos(F) is equal to FileSize(F).
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.

Restrictions
See also

Cannot be used on a text file. File must be open.

FileSize, Seek

Chapter 7, Library reference

45

FileRec type

FileRec type

Dos

Purpose

Record definition used internally by Turbo Pascal and also declared in the
Dos unit.

Declaration

type

FileRec = record
Handle: Word;
Mode: Word;
RecSize: Word;
Private: array[1 .. 26] of Byte;
UserData: array[l .. 16] of Byte;
Name: array[O .. 79] of Char;
end;

Remarks

FileRec defines the internal data format of both typed and untyped files.

See also

.TextRec

FileSearch function
Purpose
Declaration
Remarks

WinDos

Searches for a file in a list of directories.


function FileSearch(Dest, Name, List: PChar): PChar;

Searches for the file given by Name in the list of directories given by List.
The directories in List must be separated by semicolons, just like the
directories specified in a PATH command in DOS. The search alw~ys
starts with the current directory of the current drive. If the file is found,
FileSearch stores a concatenation of the directory path and the file name in
Dest. Otherwise, FileSearch stores an empty string in Dest. ~e returned
value is Dest. Dest and Name must not refer to the same location.
The maximum length of the result is defined by the fsPathName constant,
which is 79.
To search the PATH used by DOS to locate executable files, call
GetEnv Var('P ATH') and pass the result to FileSearch as the List parameter.
The result of FileSearch can be passed to FileExpand to convert it into a
fully qualified file name; that is, an uppercase file name that includes both
a drive letter and a root-relative directory path. In addition, you can use
FileSplit to split the file name into a drivel directory string, a file-name
string, and an extension string ..

46

Programmer's Reference

FileSearch function

See also

File name lengths, FileExpand, FileSplit, FSearch

Example

uses WinDos;
var
8: array[O .. fsPathName] of Char;
begin
File8earch(8, , TURBO. EXE' , GetEnvVar('PATH'));
if 8[0] = #0 then
Writeln('TURBO.EXE not found')
else
Writeln('Found as " FileExpand(S, 8));
end.

FileSize function
Purpose
Declaration
Remarks

II
System

Returns the current size of a file.


function FileSize (var F): Longint i

F is a file variable. FileSize(F) return~ the number of components in F. If


the file is empty, FileSize(F) returns O.
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.

Restrictions

Cannot be used on a text file. File must be open.

See also

FilePos

Example

var F: file of Byte;


begin
{ Get file name from command line }
Assign(F,ParamStr(l)) ;
Reset (F) ;
Writeln (' File size in bytes: ' FileSize (F) ) ;
Close(F);
end.

FileSplit function
Purpose
Declaration
Remarks

WinDos

Splits a file name into its three components.


function FileSplit (Path, Dir, Name, Ext: PChar): Word;

Splits the file name specified by Path into its three components. Dir is set
to the drive and directory path with any leading and trailing backslashes,
Name is set to the file name, and Ext is set to ~he extension with a

Chapter 7, Library reference

47

FileSplit function

preceding period. If a component string parameter is nil, the


corresponding part of the pathis not stored. If the path does not contain a
given component, the returned component string is empty. The maximum
string lengths returned in Dir, Name, and Ext are defined by the
fsDirectory, fsFileName, and fsExtension constants.
The returned value is a combination of the fcDirectory, fcFileName, and
fcExtension bit masks, indicating which components were present in the
path. If the name or extension contains any wildcard characters (* or ?),
the fcWildcards flag is set in the returned value.
See page 42 for a list of fcXXXX flag constants and page 43 for a list of
fsXXXX file name length constants.
See also

FileExpand, FindFirst, FindNext, FSplit

Example

uses Strings, WinDos;


var
Path: array[O .. fsPathName] of Char;
Dir: array[O .. fsDirectory] of Char;
Name: array[O .. fsFileName] of Char;
Ext: array[O .. fsExtension] of Char;
begin
Write('Filename (WORK. PAS) : ');
Readln (Path) ;
FileSplit(Path, Dir, Name, Ext);
if Name[O] = #0 then StrCopy(Name, 'WORK');
if Ext [0] = #0 then StrCopy (Ext, '. PAS' ) i
StrECopy (StrECopy(StrECopy (Path, Dir), Name), Ext)
Writeln('Resulting name is " Path) i
end.

Graph

Fill pattern constants

48

Purpose

Constants that determine the pattern used to fill an area.

Remarks

Use SetFillPattern to define your own fill pattern, then call


SetFillStyle(UserFill, SomeColor) and make your fill pattern the active style.
Constant

Value

Description

EmptyFill
SolidFill
LineFill
LtSlashFill
SlashFill
BkSlashFill
LtBkSlashFill

Fills area in background color


Fills area in solid fill color
-fill
III fill
/ / / fill with thick lines
\ \ \ fill with thick lines
\\\fi11

1
2

3
4
5
6

Programmer's Reference

Fill paffern constants

HatchFill
XHatchFill
InterleaveFill
WideDotFill
CloseDotFill
UserFill
See also

8
9
10
11
12

Light hatch fill


Heavy cross hatch fill
Interleaving line fill
Widely spaced dot fill
Closely spaced dot fill
User-defined fill

FillPatternType, GetFillSettings, SetFillStyle

System

FiliChar procedure
Purpose
Declaration
Remarks

Fills a specified number of contiguous bytes with a specified value.


procedure FillChar (var X; Count: Word; Value);

Xis a variable reference of any type. Count is an expression of type Word.


Value is any ordinal-type expression. FillChar writes Count contiguous
bytes of memory into Value, starting at the first byte occupied by X. No
range.,.checking is performed, so be careful to specify the correct number
of bytes.
Whenever possible, use the SizeD! function to specify the count parameter.
When using FillChar on strings, remember to set the length byte
afterward.

See also
Example

Move
var

s:

string [ 80] ;

begin

{ Set a string to all spaces


FillChar(S, SizeOf(S}, , '};
S[O] := #80;

{ Set length byte }

end.

FiliEilipse procedure
Purpose
Declaration
Remarks

Restrictions

Graph

Draws a filled ellipse.


procedure FillEllipse (X, Y: Integer; XRadius, YRadius: Word);

Draws a filled ellipse using (X, Y) as a center point, and XRadius and
YRadius as the horizontal and vertical axes. The ellipse is filled with the
current fill color and fill style, and is bordered with the current color.
Must be in graphics mode.

Chapter 7, Library reference

49

FiliEllipse procedure

See also

Are, Circle, Ellipse, GetArcCoords, GetAspectRatio, PieS lice, Sector,


SetAspectRatio

Example

uses Graph;
const R = 30;
var
Driver, Mode: Integer;
Xasp, Yasp: Word;
begin
Driver := Detect;
InitGraph(Driver, Mode, ");
if GraphResult < 0 then

{ Put in graphics mode }

Halt (1);

{ Draw ellipse }
FillEllipse(GetMaxX div 2, GetMaxY div 2, 50, 50);
GetAspectRatio(Xasp, Yasp);
{ Circular ellipse }
FillEllipse(R, R, R, R * Longint(Xasp) div Yasp);
Readln;
CloseGraphi
end.

FiliPatternType type
Purpose
Declaration
See also

Graph

Record that defines a user-defined fill pattern.


FillPatternType = array [1. .8] of Byte;

Fill pattern constants, GetFillPattern, SetFillPattern

FiliPoly procedure
Purpose
Declaration
Remarks

Graph

Draws and fills a polygon, using the scan converter.


procedure FillPoly (NumPoints: Word; var PolyPoints);

PolyPoints is an untyped parameter that contains the coordinates of each


intersection in the polygon. NumPoints specifies the number of coordinates in PolyPoints.A coordinate consists of two words, an X and a Y
value.
FillPoly calculates all the horizontal intersections, and then fills the
polygon using the current fill style and color defined by SetFillStyle or
SetFillPattern. The outline of the polygon is drawn in the current line style
and color as set by SetLineStyle.

50

Programmer's Reference

FiliPoly procedure

If an error occurs while filling the polygon, GraphResult returns a value of


-6 (grNoScanMem).
Restrictions

Must be in graphics mode.

See also

DrawPoly, GetFillSettings, GetLineSettings, GraphResult, SetFillPattern,


SetFillStyle, SetLineStyle

Example

uses Graph;
const
Triangle: array[1 .. 3J of PointType = ((X:
(X: 100; Y: 100), (X: 150; Y: 150));
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then

II

50; Y: 100),

Halt (1);

FillPoly(SizeOf(Triangle) div SizeOf(PointType), Triangle);


Readln;
CloseGraph;
end.

FiliSettingsType type
Purpose
Declaration

See also

The record that defines the pattern and color used to fill an area.
type
FillSettingsType = record
Pattern: Word;
Color: Word;
end;

GetFillSettings

FindFirst procedure
Purpose
Declaration

Remarks

Graph

Dos, WinDos

Searches the specified (or current) directory for the first entry matching
the specified file name and set of attributes.
procedure FindFirst(Path: String; Attr: Word; var S: SearchRec);

{ Dos

procedure FindFirst(Path: PChar; Attr: Word; var S: TSearchRec);

{ WinDos }

Path is the directory mask (for example, * . *). The Attr parameter specifies
the special files to include (in addition to all normal files). See page 43 for
a list of Dos and WinDos file attribute constants.

Chapter 7, Library reference

51

FindFirst procedure

The result of the directory search is returned in the specified search


record. See page 147 for a declaration of SearchRec and page 199 for a
declaration of TSearchRec.
Errors are reported in DosError; possible error codes are 3 (Path not
found) and 18 (No more files).
See also

DosError, FExpand, File attribute constants, FileExpand, FindNext, SearchRec,


TSearchRec

Example

uses Dos;
var DirInfo: SearchRec;
begin
FindFirst('*.PAS', Archive, DirInfo);
while DosError = 0 do
begin
Writeln(DirInfo.Name);
FindNext(DirInfo);
end;
end.

FindNext procedure
Purpose
Declaration

}
}
}
}

Dos, WinDos

Returns the next entry that matches the name and attributes specified in a
previous call to FindFirst.
procedure FindNext (var S: SearchRec);
procedure FindNext(var S: TSearchRec)

52

{ or WinDos
{ or TSearchRec
{ or faArchive
{ Same as DIR *.PAS

{ Dos
{ WinDos

Remarks

The search record must be the same search record passed to FindFirst.
Errors are reported in DosError; the only possible error code is 18 (No
more files).

See also

Dos Error, File attribute, FExpand, FileExpa.nd, FindFirst, SearchRec,


TSearchRec

Example

See the example for FindFirst.

Programmer's Reference

Flag constants

Flag constants
Purpose

Dos, WinDos

Used to test individual flag bits in the Flags register after a call to Intr or

MsDos.
Remarks

Constants

Value

FCarry
FParity
FAuxiliary
FZero
FSign
FOverflow

$0001
$0004
$0010
$0040
$0080
$0800

For instance, if R is a register record, the tests


R.Flags and FCarry <> 0
R.Flags and FZero = 0

are True respectively if the Carry flag is set and if the Zero flag is clear.
See also

Intr, MsDos

FloodFili procedure
Purpose
Declaration
Remarks

Graph

Fills a bounded region with the current fill pattern.


procedure FloodFill (X, Y: Integer; Border: Word);

Fills an enclosed area on bitmap devices. (X, Y) is a seed within the


enclosed area to be filled. The current fill pattern, as set by SetFillStyle or
SetFillPattern, is used to flood the area bounded by Border color. If the seed
point is within an enclosed area,'then the inside will be filled. If the seed is
outside the enclosed area, then the exterior will be filled.
If an error occurs while flooding a region, GraphResult returns a value of

grNoFloodMem.
Note that FloodFill stops after two blank lines have been output. This can
occur with a sparse fill pattern and a small polygon. In the following
program, the rectangle is not completely filled:
program StopFill;
uses Graph;

var Driver, Mode: Integer;

Chapter 7, Library reference

53

FloodFili procedure

begin
Driver := Detecti
InitGraph(Driver, Mode, 'c:\bgi') i
if GraphResult <> grOk then
Halt(l) i
SetFillStyle(LtSlashFill, GetMaxColor)i
Rectangle (0, 0, 8, 20) i
FloodFill(l, 1, GetMaxColor)i
Readlni .
CloseGraphi
end.

In this case, using a denser fill pattern like SlashFill will completely fill the
figure.
Restrictions

Use FillPoly instead of FloodFill whenever possible so you can maintain


code compatibility with future versions. Must be in graphics mode. This
procedure is not available when using the IBM 8514 graphics driver
(IBM8514.BGI).

See also

FillPoly, GraphResult, SetFillPattern, SetFillStyle

Example

uses Graphi
var Gd, Gm: Integeri
begin
Gd := Detect;
InitGraph(Gd, Gm, ")i
if GraphResult <> grOk then
Halt(l)i
SetColor(GetMaxColor)i
Circle(50, 50, 20) i
FloodFill(50, 50, GetMaxColor)
Readlni
CloseGraphi
end.

Flush procedure
Purpose
Declaration
Remarks

System

Flushes the buffer of a text file open for output.


procedure Flush(var F: Text) i

F is a text file variable.


When a text file has been opened for output using Rewrite or Append, a call
to Flush will empty the file's buffer. This guarantees that all characters
written to the file at that time have actually been written to the external
file. Flush has no effect on files opened for input.

54

Programmer's Reference

fmXXXX constants

With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it


returns a nonzero error code.

Dos, WinDos

fmXXXX constants
Purpose

Defines the allowable values for the Mode field of a TextRec and TFileRec
text file record.

Remarks

The Mode fields of Turbo Pascal's file variables contain one of the values
specified here:

See also

Constant

Value

fmClosed
fmlnput
fmOutput
fmlnOut

$D7BO
$D7Bl
$D7B2
$D7B3

TextRec, TFileRec

Graph

Font control constants


Purpose
Remarks

See also

Constants that identify fonts.


Constant

Value

DefaultFont
TriplexFont
SmallFont
SansSerifFont
GothicFont

a (8x8 bit mapped font)

HorizDir
VertDir

a (left to right)

UserCharSize

a (user-defined Char size)

1 ("stroked" fonts)
2
3 '

4
1 (bottom to top)

GetTextSettings, SetTextStyle, TextSettingsType

Frac function
Purpose
Declaration

II

System
Returns the fractional part of the argument.
function Frac (X: Real): Real i

Chapter 7, Library reference

55

Frac function

Remarks

X is a real-type expression. The result is the fractional part of X; that is,


Frac(X) = X - Int(X).
.

See also

Int

Example

var R: Real;
begin

R
R

:=
:=

Frac(123.456);
Frac(-123.456);

{ 0.456 }
{ -0.456 }

end.

FreeList variable
Purpose
Declaration

Points to the first free block in the heap.


var FreeList: Pointer;

Remarks

The FreeList variable points to the first free block in the heap. This block
contains a pointer to the next free block, which contains a pointer to the
next free block, and so forth. The last free block contains a pointer to the
'top of the heap. If there are no free blocks on the free list, FreeList will be
equal to HeapPtr. See Chapter 12, "Standard procedures and functions,"
in the Language Guide for more information.

See also

Dispose, FreeMem, HeapPtr

FreeMem procedure
Purpose
Declaration

56

System

System

Disposes of a dynamic variable. of a given size.


procedure FreeMern(var P: Pointer; Size: Word);

Remarks

P is a variable of any pointer type previously assigned by the GetMem


procedure or assigned a meaningful value by an assignment statement.
Size is an expression specifying the size in bytes of the dynamic variable to
dispose of; it must be exactly the number of bytes previously allocated to
that variable by GetMem. FreeMem destroys the variable referenced by P
and returns its memory region to the heap. If P does not point to a
memory region in the heap, a run-time error occurs. After a call to
FreeMem, the value of P becomes undefined, and an error occurs if you
subsequently reference PA.

See/also

Dispose, FreeMem, HeapError, New

Programmer's Reference

FSearch function

FSearch function
Purpose
Declaration
Remarks

Dos

Searches for a file in a list of directories.


function FSearch (Path: PathStri DirList: String): PathStri

Searches for the file given by Path in the list of directories given by DirList.
The directories in DirList must be separated by semicolons, just like the
directories specified in a PATH command in DOS. The search always
starts with the current directory of the current drive. The returned value is
a concatenation of one of the directory paths and the file name, or an
empty string if the file could not be located.
To search the PATH,used by DOS to locate executable files, call
GetEnv('PATH') and pass the result to FSearch as the DirList parameter.
The result of FSearch can be passed to FExpand to convert it into a fully
qualified file name, that is, an uppercase file name that includes both a
drive letter and a root-relative directory path. In addition, you can use
FSplit to split the file name into a drivel directory string, a file-name
string, and an extension string.

See also

FExpand, FSplit, GetEnv

Example

uses Dos i
var S: PathStri
begin
S := FSearch('TURBO.EXE', GetEnv('PATH'))i
if S = " then
Writeln( 'TURBO.EXE not found')
else
Wri teln ( , Found as " FExpand (S)) i
end.

FSplit procedure
Purpose
Declaration
Remarks

Dos

Splits a file name into its three components.


procedure FSplit (Path: PathStri var Dir: DirStri var Name: NameStri
var Ext: ExtStr) i

Splits the file name specified by Path into its three components. Dir is set
to the drive and directory path with any leading and trailing backslashes,
Name is set to the file name, and Ext is set to the extension with a

Chapter 7, Library reference

57

II

FSpiit procedure

preceding dot. Each of the component strings might possibly be empty, if


Path contains no such component.

FSplit never adds or removes characters when it splits the file name, and
the concatenation of the resulting Dir, Name, and Ext will always equal the
specified Path.
See page 44 for a list of File-handling string types.
See also

FExpand, File-handling string types

Example

uses
var
P:
D:
N:
E:

Dos;
PathStr;
DirStr;
NameStr;
ExtStr;

begin

Write('Filename (WORK. PAS) : ');


Readln(P) ;
FSplit(p, D, N, E);
if N

="

then

N .- 'WORK';
if E = "

then

E . - '. PAS';
P

:=

D + N + E;

Writeln('Resulting name is'


end.

P);

GetArcCoords procedure
Purpose
Declaration
Remarks

Restrictions

58

Graph

Lets the user inquire about the coordinates of the last Arc command.
procedure GetArcCoords (var ArcCoords: ArcCoordsType);

GetArcCoords returns a variable of type ArcCoordsType. GetArcCoords


returns a variable containing the center point (X, Y), the starting position
(Xstart, Ystart), and the ending position (Xend, Yend) of the last Arc or
Ellipse command. These values are useful if you need to connect a line to
the end of an ellipse.
Must be in graphics mode.

See also

Arc, Circle, Ellipse, FillEllipse, PieS lice, PieSliceXY, Sector

Example

uses Graph;
var
Gd, Gm: Integer;

Programmer's Reference

GetArcCoords procedure

ArcCoords: ArcCoordsType;
begin
Gd := Detect;
InitGraph (Gd, Gm, ");
if GraphResuIt <> grOk then
HaItH) ;
Arc ( 100, 100, 0, 270, 30);
GetArcCoords(ArcCoords);
with ArcCoords do
Line (Xstart, Ystart, Xend, Yend);
ReadIn;
CIoseGraph;
end.

GetArgCount function
Purpose
Declaration
See also

Declaration

WinDos

Returns the number of parameters passed to the program on the


command line.
function GetArgCount: Integer

GetArgStr, ParamCount, ParamStr

GetArgStr function
Purpose

I
WinDos

Returns the command-line parameter specified by Index.


function GetArgStr (Dest: PChar; Index: Integer; MaxLen: Word): PChar;

Remarks

If Index is less than zero or greater than GetArgCount, GetArgStr returns an


empty string. If Index is zero, GetArgStr returns the file name of the
current module. Dest is the returned value. The maximum length of the
returned string is specified by the MaxLen parameter.

See also

GetArgCount, ParamCount, ParamStr

GetAspectRatio procedure
Purpose
Declaration

Graph

Returns the effective resolution of the graphics screen from which the
aspect ratio (Xasp:Yasp) can be computed.
procedure GetAspectRatio (var Xasp, Yasp: Word);

Chapter 7, Library reference

59

GetAspectRatio procedure

Remarks

Restrictions

Each driver and graphics mode has an aspect ratio associated with it
(maximum Y resolution divided by maximum X resolution). This ratio
can be computed by making a call to GetAspectRatio and then dividing the
Xasp parameter by the Yasp parameter. This ratio is used to make circles,
arcs, and pie slices round.
Must be in graphics mode.

See also

Arc, Circle, Ellipse, GetMaxX, GetMaxY, PieS lice, SetAspectRatio

Example

uses Graph;

var
Gd, Gm: Integer;
Xasp, Yasp: Word;
XSideLength, YSideLength: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Ha1t(1);

GetAspectRatio(Xasp, Yasp);
XSideLength := 20;
{ Adjust Y length for aspect ratio
YSideLength := Round((Xasp I Yasp) * XSideLength);
{ Draw a "square" rectangle on the screen}
Rectangle (0, 0, XSideLength, YSideLength);
Readln;
CloseGraph;
end.

Graph

GetBkColor function
Purpose
Declaration
Remarks

Returns the index into the palette of the current background color.
function GetBkColor: Word;

Background colors range from 0 to 15, depending on the current graphics


driver and current graphics mode.

GetBkColor returns 0 if the Oth palette entry is changed by a call to


SetPalette or SetAllPalette.
Restrictions
See also

60

Must be in graphics mode.

GetColor, GetPalette, InitGraph, SetAllPalette, SetBkColor, SetColor, SetPalette

Programmer's Reference

GetBkColor function

Example

uses Crt Graph;


var
Gd , Gm: Integer;
Color: Word;
Pal: PaletteType;
begin
Gd := Detect;
InitGraph(Gd , Gm , ");
if GraphResult <> grOk then
I

Halt (1);

Randomize;
GetPalette(Pal);
if Pal.Size <> 1 then
begin
repeat
Color := Succ(GetBkColor);
if Color> Pal.Size-l then
Color := 0;
SetBkColor(Color);
LineTo(Random(GetMaxX) Random(GetMaxY));
until KeyPressed;
end
else
Line(O, 0, GetMaxX , GetMaxY);
Readln;
CloseGraph;
end.

{ Cycle through colors }

GetCBreak procedure
Purpose
Declaration

Dos, WinDos

Gets Ctrl+Break checking.


procedure GetCBreak(var Break: Boolean);

Remarks

GetCBreak sets the value of Break depending on the state of Ctrl+Break


checking in DOS. When off (False), DOS only checks for Ctrl+Break during
I/O to console, printer, or communication devices. When on (True), checks
are made at every system call.

See also

SetCBreak

Chapter 7, Library reference

61

GetColor function

GetColor function
Purpose
Declaration
Remarks
Restrictions

Graph

Returns the color value passed to the previous successful call to SetColor.
function GetColor: Word;

Drawing colors range from 0 to 15, depending on the current graphics


driver and current graphics mode.
Must be in graphics mode.

See also

GetBkColor, GetPalette, InitGraph, SetAllPalette, SetColor, SetPalette

Example

uses Graph;
var
Gd, Gm: Integer;
Color: Word;
Pal: PaletteTypei
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);

Randomize;
GetPalette (Pal) ;
repeat
Color := Succ(GetColor);
if Color> Pal.Size - 1 then
Color := 0;
SetColor(Color);
LineTo(Random(GetMaxX), Random(GetMaxY));
until KeYPressed;
CloseGraphi
end.

GetCurDir function
Purpose
Declaration
Remarks

WinDos

Returns the current directory of a specified drive.


function GetCurDir (Dir: PChar ; Drive: Byte): PChar

The string returned in Dir always starts with a drive letter, a colon, and a
backslash. Drive = 0 indicates the current drive, 1 indicates A, 2 indicates
B, and so on. The returned value is Dir. Errors are reported in DosError.
If the drive specified by Drive is invalid, Dir returns 'X:\', as if it were the

root directory of the invalid drive.

62

Programmer's Reference

GetCurDir function

The maximum length of the resulting string is defined by the fsDirectory


constant.
See also

SetCurDir, CreateDir, RemoveDir. GetDir returns the current directory of a


specified drive as a Pascal-style string.

GetDate procedure
Purpose

Returns the current date set in the operating system.

Declaration

procedure GetDate (var Year, Month, Day, DayofWeek: Word);

Dos, WinDos

Remarks

Ranges of the values returned are Year 1980 .. 2099, Month 1..12, Day 1..31,
and DayOfWeek 0.. 6 (where 0 corresponds to Sunday).

See also

Get Time, SetDate, SetTime

GetDefaultPalette function
Purpose
Declaration
Remarks
Restrictions

Graph

Returns the palette definition record.


function GetDefaultPalette(var Palette: PaletteType): PaletteType;

GetDefaultPalette returns a PaletteType record, which contains the palette as


the driver initialized it during InitGraph.
Must be in graphics mode.

See also

InitGraph, GetPalette, SetAllPalette, SetPalette

Example

uses Crt, Graph;


var
Driver, Mode, I: Integer;
MYPal, OldPal: PaletteType;
begin
DirectVideo := False;
Randomize;
Driver := Detect;
InitGraph(Driver, Mode, ");
if GraphResult < 0 then
Halt (1);
GetDefaultPalette(OldPal) ;
MyPal := OldPal;
{ Display something }

Chapter 7, Library reference

{ Put in graphics mode }

{ Preserve old one }


{ Duplicate and modify }

63

GetDefaultPalette function

for I := 0 to MyPal.Size - 1 do
begin
SetColor(I) ;
OutTextXY(10, I * 10, ' ... Press any key ... ');
end;
repeat
{ Change palette until a key is pressed }
with MyPal do
Colors[Randorn(Size)] := Randorn(Size + 1);
SetAllPalette(MyPal);
until KeyPressed;
SetAllPalette(OldPal);
{ Restore original palette}
ClearDevice;
OutTextXY(10, 10, 'Press <Return> ... ');
Readln;
CloseGraph;
end.

GetDir procedure
Purpose
Declaration
Remarks

System

Returns the current directory of a specified drive.


procedure GetDir (D: Byte; var S: String);

D is an integer-type expression, and S is a string-type variable. The


current directory of the drive specified by D is returned in S. D = 0 indicates the current drive, 1 indicates drive A, 2 indicates drive B, and so on.
GetDir performs no error-checking. If the drive specified by D is invalid, S
returns 'X:V, as if it were the root directory of the ihvalid drive.

See also

ChDir, MkDir, RmDir. GetCurDir performs the same function as GetDir,


but it takes a null-terminated string as -an argument instead of a Pascalstyle string.

Graph:

GetDriverName function
Purpose
Declaration
Remarks
Restrictions
See also

64

Returns a string containing the name of the current driver.


function GetDri verNarne: String;

After a call to InitGraph, returns the name of the active driver.


Must be in graphics mode.
GetModeName, InitGraph

Programmer's Reference

GetDriverNome function

Example

uses Graph;
var Driver, Mode: Integer;
begin
Driver := Detect;
InitGraph(Driver, Mode, ");
if GraphResult < 0 then

{ Put in graphics mode }

Halt (1);

OutText('Using driver' + GetDriverName);


Readln;
CloseGraph;
end.

GetEnv function
Purpose
Declaration
Remarks

I
Dos

Returns the value of a specified environment variable.


function GetEnv(EnvVar: String): String;
GetEnv returns the value of a specified variable. The variable name can be
either uppercase or lowercase, but it must not include the equal sign (=)
character. If the specified environment variable does not exist, GetEnv
returns an empty string.

For more information about the DOS environment, see your DOS
manuals.
See also
Example

EnvCount, EnvStr
{$M 8192,O,O}

uses Dos;
var Command: string[79];
begin
Write('Enter DOS command: ');
Readln (Command) ;
if Command <> " then
Command := ' IC ' + Command;
SwapVectors;
Exec(GetEnv('COMSPEC'), Command);
SwapVectors;
if Dos Error <> 0 then
Writeln('Could not execute COMMAND.COM');
end.

Chapter 7, Library reference

65

GetEnvVor function

GetEnvVar function
Purpos~

Declaration

WinDos

Returns a pointer to the value of a specified environment variable.


function GetEnvVar (VarN-ame: PChar): PChar
i

Remarks

GetEnv Var returns a pointer to the value of a specified variable; for


example, a pointer to the first character after the equals sign (=) in the
environment entry given by VarName. The variable name can be in either
uppercase or lowercase, but it must not include the equal sign (=)
character. If the specified environment variable does not exist, GetEnvVar
returns nil.

Example

uses WinDos;
begin
Writeln{/The current PATH is
end.

GetEnvVar{/PATH/));

Dos, WinDos

GetFAttr procedure
Purpose
Declaration
Remarks

Returns the attributes of a file.


procedure GetFAttr (var F; var Attr: Word);
Fmust be a file variable (typed; untyped, or text file) that has been
assigned but not opened. The attributes are examined by anding them

with the file attribute masks defined as constants in the Dos unit. See.
page 43 for a list of file attribute constants for Dos and WinDos units.
Errors are reported in DosError; possible error codes are
.3 (Invalid path)
.5 (File access denied)
Restrictions

F cannot be open.

See also

DosError, File attribute constants, GetFTime, SetFAttr, SetFTime

Example

uses Dos;
var
F: file;
Attr: Word;
begin
{ Get file name from command line }
Assign{F ParamStr{l));
GetFAttr{F Attr);
Writeln{ParamStr{l)) ;

{ or WinDos }

66

Programmer's Reference

GetFAttr procedure

if DosError <> 0 then


Writeln('DOS error code =' DosError)
else
begin
Write('Attribute = " Attr);
{ Determine attribute type using File attribute constants in Dos or WinDos
unit }
if Attr and ReadOnly <> 0 then
Writeln('Read only file');
if Attr and Hidden <> 0 then
Writeln( ',Hidden file');
if Attr and SysFile <> 0 then
Writeln('System file');
if Attr and VolumeID <> 0 then
Writeln('Volume ID');
if Attr and Directory <> 0 then
Writeln('Directory name');
if Attr an~ Archive <> 0 then
Writeln('Archive (normal file) ');
end; { else}
end.

GetFiliPattern procedure
Purpose
Declaration
Remarks
Restrictions
See also

Declaration
Remarks

Graph

Returns the last fill pattern set by a previous call to SetFillPattern.


procedure GetFillPattern(var FillPattern: FillPatternType);

If no user call has been made to SetFillPattern, GetFillPattern returns an


array filled with $FF.
Must be in graphics mode.

GetFillSettings, SetFillPattern, SetFillStyle

GetFiliSettings procedure
Purpose

Graph

Returns the last fill pattern and color set by a previous call to SetFillPattern
or SetFillStyle.
procedure GetFillSettings (var Filllnfo: FillSettingsType);

The Pattern field reports the current fill pattern selected. The Color field
reports the current fill color selected. Both the fill pattern and color can be
changed by calling the SetFillStyle or SetFillPattern procedure. If Pattern is

Chapter 7, Library reference

67

GefFiliSettings procedure

equal to UserFill, use GetFillPattern to get the user-defined fill pattern that
is selected.
Restrictions

Must-be in grap~ics mode.

See also

FillPoly, GetFillPattern, SetFillPattern, SetFillStyle

Example

uses Graph;
var
Gd, Gm: Integer;
FillInfo: FillSettingsType;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);
GetFillSettings(Filllnfo);
Bar (0, 0, 50, 50);
SetFillStyle(XHatchFill, GetMaxColor);
Bar (50, 0, 100, 50);
with FillInfo do
SetFillStyle(Pattern, Color);
Bar (100, 0, 150, 50);
Readln;
CloseGraph;
end.

GetFTime procedure
Purpose
Declaration
Remarks

Restrictions
See also

68

Save fill style and color }


{ New style }

{ Restore old fill style }

005 , WinDos

Returns the date and time a file was last written.


procedure GetFTime(var F; var Time: Longint);

F must be a file variable (typed,untyped, or text file) that has been


assigned and opened. The time returned in the Time parameter can be
unpacked through a call to UnpackTime. Errors are reported in Dos Error;
the only possible error code is 6 (Invalid file handle).
Fmust be open.

Dos Error, PackTime, SetFTime, UnpackTime

Programmer's Reference

GetGraphMode function

GetGraphMode function
Purpose
Declaration
Remarks

Graph

Returns the current graphics mode.


function GetGraphMode: Integer;

GetGraphMode returns the current graphics mode set by InitGraph or


SetGraphMode. The Mode value is an integer from 0 to 5, depending on the
current driver.
The following mode constants are defined:
Graphics
driver

Constant
name

Value

Column
x row

Palette

Pages

CGA

CGACO
CGAC1
CGAC2
CGAC3
CGAHi

0
1
2
3
4

320x200
320x200
320x200
320x200
640x200

CO
C1
C2
C3
2 color

1
1
1
1
1

MCGA

MCGACO
MCGAC1
MCGAC2
MCGAC3
MCGAMed
MCGAHi

0
1
2
3
4
5

320x200
320x200
320x200
320x200
640x200
640x480

CO
C1
C2
C3
2 color
2 color

1
1
1
1
1
1

EGA

EGALo
EGAHi

0
1

640x200
640x350

16 color
16 color

4
2

EGA64

EGA64Lo
EGA64Hi

0
1

640x200
640x350

16 color
4 color

1
1

EGA-MONO

EGAMonoHi
EGAMonoHi

3
3

640x350
640x350

2 color
2 color

1*
2**

HERC

HercMonoHi

720x348

2 color

ATT400

ATT400CO
ATT400C1
ATT400C2
ATT400C3
ATT400Med
ATT400Hi

0
1
2
3
4
5

320x200
320x200
320x200
320x200
640x200
640x400

CO
C1
C2
C3
2 color
2 color

1
1
1
1
1
1

VGA

VGALo
VGAMed
VGAHi

0
L
2

640x200
640x350
640x480

16 color
16 color
16 color

2
2
1

Chapter 7, Library reference

69

GetGraphMode function

PC3270

PC3270Hi

720x350

2 color

IBM8514
IBM8514

IBM8514Lo
IBM8514Hi

0
0

640x480
1024x768

256 color
256 color

1
1

* 64K on EGAMono card


** 256K on EGAMono card

Restrictions

Must be in graphics mode.

See also

ClearDevice, DetectGraph, InitGraph, RestoreCrtMode, SetGraphMode

Example

uses Graph;
var
Gd, Gm: Integer;
Mode: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt(l);
Out Text ('<ENTER> to leave graphics:');
Readln;
RestoreCrtMode;
Writeln('Now in text mode');
Write('<ENTER> to enter graphics mode:');
Readln;
SetGraphMode(GetGraphMode) ;
OutTextXY(O, 0, 'Back in graphics mode');
OutTextXY(O, TextHeight('H'), '<ENTER> to quit:');
Readln;
CloseGraphi
end.

Graph

Getlmage procedure
Purpose
Declaration
Remarks

Saves a bit image of the specified region into a buffer.


procedure GetImage (Xl, Yl, X2, Y2: Integer; var BitMap);

Xl, Yl, X2, and Y2 define a rectangular region on the screen. BitMap is an
untyped parameter that must be greater than or equal to 6 plus the
amount of area defined by the .region. The first two words of BitMap store
the width and height of the region. The third word is reserved.

The remaining part of BitMap is used to save the bit image itself. Use the
ImageSize function to determine the size requirements of BitMap.

70

Programmer's Reference

Getlmage procedure

Restrictions

Must be in graphics mode. The memory required to save the region must
be less than 64K.

See also

ImageSize, PutImage

Example

uses Graph;
var
Gd, Gm: Integer;
P: Pointer;
Size: Word;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then

Halt (1) ;

Bar(O, 0, GetMaxX, GetMaxY);


Size := ImageSize(10, 20, 30, 40);
GetMem(P, Size);
GetImage(10, 20, 30, 40, PA ) ;
Readln;
ClearDevice;
Put Image (100, 100, pAl NormalPut);
Readln;
. CloseGraph;
end ..

{ Allocate memory on heap }

GetlntVec procedure
Purpose
Declaration

Dos , WinDos

Returns the address stored in a specified interrupt vector.


procedure GetIntVec (IntNo: Byte; var Vector: Pointer);

Remarks

IntNo specifies the interrupt vector number (0 .. 255), and the address is
returned in Vector.

See also

SetIntVec

GetLineSettings procedure
Purpose
Declaration
Remarks
Restrictions

Graph

Returns the current line style,line pattern, and line thickness as set by
SetLineStyle.
procedure GetLineSettings (var LineInfo: LineSettingsType);

See page 103 for the declaration of LineSettingsType.


Must be in graphics mode.

Chapter 7, Library reference

71

GetLineSettings procedure

See also

DrawPoly, LineSettingsType, Line Style, SetLineStyle

Example

uses Graph;
var
Gd, Gm: Integer;
OldStyle: LineSettingsType;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;

Line (0, 0, 100, 0);


GetLineSettings(OldStyle);
SetLineStyle(DottedLn, A, ThickWidth);
Line(O, la, lOa, 10);
with OldStyle do
SetLineStyle(LineStyle, Pattern, Thickness);
Line(O, 20, lOa, 20);
Readln;
CloseGraph;
end.

GetMaxColor function
Purpose
Declaration
Remarks

Restrictions
See also

Declaration
Remarks

72

{ Restore old line style }

Graph

Returns the highest color that can be passed to the SetColor procedure.
function GetMaxColor: Word;

As an example, on a 256K EGA, GetMaxColor always returns IS, which


means that any call to SetColor with a value from 0..15 is valid. On a eGA
in high-resolution mode or on a Hercules monochrome adapter,
GetMaxColor returns a value of 1 because these adapters support only
draw colors of 0 or 1.
Must be in graphics mode.

SetColor

GetMaxMode function
Purpose

{ New style }

Graph

Returns the maximum mode number for the currently loaded driver.
function GetMaxMode: Word;

GetMaxMode lets you find out the maximum mode number for the current
driver, directly from the driver. (Formerly, GetModeRange was the only way

Programmer's Reference

GetMaxMode function

you could get this number; GetModeRange is still supported, but only for
the Borland drivers.)
The value returned by GetMaxMode is the maximum value that can be
passed to SetGraphMode. Every driver supports modes O.. GetMaxMode.
Restrictions

Must be in graphics mode.

See also

GetModeRange, SetGraphMode

Example

uses Graph;
var
Driver, Mode: Integer;
I: Integer;
begin
Driver := Detect;
InitGraph(Driver, Mode, ");
if GraphResult < 0 then

I
{ Put in graphics mode }

Halt (1) ;

for I := 0 to GetMaxMode do
OutTextXY(10, 10 * Succ(I), GetModeName(I));
Readln;
CloseGraph;
end.

GetMaxX function
Purpose
Declaration
Remarks

{ Display all mode names }

Graph

Returns the rightmost column (x resolution) of the current graphics driver


and mode.
function GetMaxX: Integer;

Returns the maximum X value for the current graphics driver and mode.
On a eGA in 320x200 mode, for example, GetMaxX returns 319.

GetMaxX and GetMaxY are invaluable for centering, determining the


boundaries of a region on the screen, and so on.
Restrictions

Must be in graphics mode.

See also

GetMaxY, GetX, GetY, MoveTo

Example

uses Graph;
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;

Chapter 7, Libraryreference

73

GetMaxX function

Rectangle (0, 0, GetMaxX, GetMaxY);


Readln;
CloseGraph;
end:

GetMaxY function
Purpose
Declaration
Remarks

{ Draw a full-screen box}

Gr.aph

Returns the bottommost row (y resolution) of the current graphics driver


and mode.
function GetMaxY: Integer;

Returns the maximum y value for the current graphics driver and mode.
On a CGA in 320x200 mode, for example, GetMaxY returns 199.

GetMaxX and GetMax Yare invaluable for centering, determining the


boundaries of a region on the screen, and so on.
Restrictions

Must be in graphics mode.

See also

GetMaxX, GetX, GetY, MoveTo

Example

uses Graph;
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph (Gd, Gm, ");
if GraphResult <> grOk then
Halt(l);
Rectangle (0, 0, GetMaxX, GetMaxY);
Readln;
CloseGraph;
end.

GetMem procedure .
Purpose
Declaration
Remarks

{ Draw a full-screen box}

System

Allocates a block of memory of a specified size.


procedure GetMem (var P: Pointer; Size: Word);

P is a variableofany pointer type. Size is an expression specifying the size


in bytes of the dynamic variable to allocate. The newly created variable
.
can be referenced as PA.
If there isn't enough free space in the heap to allocate the new variable, a
run-time error occurs. (It is possible to avoid a run-time error; see "The
HeapError variable" in Chapter 19 of the Language Guide.)

74

Programmer's Reference

GetMem procedure

Restrictions
See also

The largest block that can be safely allocated on the heap at one time is
65,528 bytes (64K-$8).

Dispose, FreeMem, HeapError, New

GetModeName function
Purpose
Declaration
Remarks

Restrictions

Returns a string containing the name of the specified graphics mode.


function GetModeName (ModeNumber: Integer): String;

The mode names are embedded in each driver. The return values (320x200
CGA PI, 640x200 CGA, and so on) are useful for building menus, display
status, and so forth.
Must be in graphics mode.

See also

GetDriverName, GetMaxMode, GetModeRange

Example

uses Graph;
var
Driver, Mode: Integer;
I: Integer;
begin
Driver := Detect;
InitGraph(Driver, Mode, ");
if GraphResult < 0 then
Halt (1);
for I := 0 to GetMaxMode do
OutTextXY(10, 10 * Succ(I), GetModeName(I));
Readln;
CloseGraph;
end.

GetModeRange procedure
Purpose
Declaration
Remarks

Graph

{ Put in graphics mode}

{ Display all mode names }

Graph

Returns the lowest and highest valid graphics mode for a given driver.
procedure GetModeRange (GraphDri ver: Integer; var LoMode, HiMode: Integer);

The output from the following program will be Lowest = 0 and Highest = 1:
uses Graph;
var Lowest, Highest: Integer;
begin
GetModeRange(EGA64, Lowest, Highest);

Chapter 1, Library reference

75

GetModeRange procedure

Write{'Lowest = " Lowest);


Write{' Highest = " Highest);
end.

If the value of GraphDriver is invalid, the LoMode and HiMode are set to-1.
See also

DetectGraph, GetGraphMode, InitGraph, SetGraphMode

GetPalette procedure
Purpose
Declaration

76

Graph

Returns the current palette and its size.


procedure Getpalette (var Palette: PaletteType);

Remarks

Returns the current palette and its size in a variable of type PaletteType.

Restrictions

Must be in graphics mode, and can only be used with EGA,EGA 64, or
VGA (not the IBM 8514 or the VGA in 256-color mode).

See also

GetDefaultPalette, GetPaletteSize, SetAllPalette, SetPalette

Example

uses Graph;
var
Gd, Gm: Integer;
Color: Word;
Palette:. PaletteType;
begin,
Gd := Detect;
InitGraph{Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);
GetPalette{Palette);
if Palette. Size <> 1 then
for Color := 0 to Pred{Palette.Size) do
begin
SetColor{Color);
Line{O, Color * 5, 100, Color * 5);
end
else
Line (0, 0, 100, 0);
Readln;
CloseGraph;
end.

Programmer's Reference

GetPaletteSize function

GetPaletteSize function
Purpose
Declaration
Remarks
Restrictions
See also

Returns the size of the palette color lookup table.


function GetpaletteSize: Integer;

GetPaletteSize reports how many palette entries can be set for the current
graphics mode; for example, the EGA in color mode returns a value of 16.
Must be in graphics mode.

GetDejaultPalette, GetMaxColor, GetPalette, SetPalette

GetPixel function
Purpose
Declaration
Remarks
Restrictions

Graph

Graph

Gets the pixel value at X, Y.


function Getpixel (X, Y: Integer): Word:

Gets the color of the pixel at (X, Y).


Must be in graphics mode.

See also

GetImage, PutImage, PutPixel, SetWriteMode

Example

uses Graph;
var
Gd, Gm: Integer;
PixelColor: Word;
begin
Gd := Detect;
InitGraph(Gd, Gm, "):
if GraphResult <> grOk then
Halt (1);

PixelColor := GetPixel(10, 10);


if Pixel Color = 0 then
PutPixel(10, 10, GetMaxColor):
Readln;
CloseGraph;
end.

Chapter 7, Library reference

77

GetTextSettings procedure

Graph

GetTextSettings procedure
Purpose
. Declaration
Remarks
Restrictions

Returns the current text font, direction, size, and justification as set by
SetTextStyle and SetTextJustify .
procedure GetTextSettings (var TextInfo: TextSettingsType);

See page 55 for the declaration of the Font control constants and page 196
for a declaration of the TextSettingsType record.
Must be in graphics mode.

See also

Font control constants, In it Graph, SetTextJustify, SetTextStyle, TextHeight,


TextSettingsType, Text Width

Example

uses Graph;
var
Gd, Gm: Integer;
OldStyle: TextSettingsType;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);
GetTextSettings(OldStyle) ;
OutTextXY(O, 0, 'Old text style');
SetTextJustify(LeftText, CenterText);
SetTextStyle(TriplexFont, VertDir, 4);
. OutTextXY(GetMaxX div 2, GetMaxY div 2, 'New Style');
with OldStyle do
{ Restore old text style }
begin
SetTextJustify(Horiz, Vert);
SetTextStyle(Font, Direction, CharSize);
end;
OutTextXY(O, TextHeight('H'), 'Old style again');
Readln;
CloseGraph;
end.

Dos, WinDos

GetTime procedure

78

Purpose

Returns the current time set in the operating system.

Declaration

procedure GetTime(var Hour, Minute, Second, Sec100: Word);

Programmer's Reference

GetTime procedure

Remarks

Ranges of the values returned are Hour 0.. 23, Minute 0..59, Second 0.. 59,
and Sec100 (hundredths of seconds) 0.. 99.

See also

GetDate, SetDate, SetTime, UnpackTime

GetVerify procedure
Purpose
Declaration

Dos, WinDos

Returns the state of the verify flag in DOS.


procedure GetVerify (var Verify: Boolean);

Remarks

GetVerify returns the state of the verify flag in DOS~ When off (False), disk
writes are not verified. When on (True), all disk writes are verified to
ensure proper writing.

See also

Set Verify

GetViewSettings procedure
Purpose
Declaration
Remarks
Restrictions

Graph

Returns the current viewport and clipping parameters, as set by


SetViewPort.
procedure GetViewSettings (var ViewPort: ViewPortType);

GetViewSettings returns a variable of ViewPortType. See page 202 for a


declaration of the record ViewPort Type.
Must be in graphics mode.

See also

Clear ViewPort, Set ViewPort, ViewPortType

Example

uses Graph;
var
Gd, Gm: Integer;
ViewPort: ViewPortType;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);

GetViewSettings(ViewPort);
with ViewPort do
begin
Rectangle (0, 0, X2 - Xl, Y2 - Y1);
if Clip then
OutText('Clipping is active.')

Chapter 7, Library reference

79

GetViewSettings procedure

else
Out Text ('No clipping today.');
end;
Readln;
CloseGraph;
end.

GetX function
Purpose
'Declaration
Remarks

Graph
Returns the X coordinate of the current position (CP).
function GetX: Integer;

The value ofGet X is relative to the dimensions of the active viewport, as


the following examples illustrate.
SetViewPort (0, 0, GetMaxX,

Get~axY,

True);

Moves CP to absolute (0, 0), and GetX returns a value of 0.


MoveTo (5, 5);

Moves CP to absolute (5,5), and GetX returns a value of 5 .


SetViewPort (10, la, 100 j lOa, True);

Moves CP to absolute (10, 10), but GetX returns a value of 0.


MoveTo (5, 5);

Moves CP to absolu!e (15, 15), but GetX returns a value of 5.


Restrictions
See also
Example

Must be in graphics mode.

GetViewsettings, GetY, InitGraph, MoveTo, Set ViewPort


uses Graph;

var
Gd, Gm: Integer;
X, Y: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;

OutText('Starting here. ');


X := GetX;
Y := Gety;
OutTextXY(20, 10, 'Now over here .... ');
OutTextXY(X, Y, 'Now back over here.');
Readln;
CloseGraph;
end.

80

Programmer's Reference

GetV function

GetV function
Purpose
Declaration
Remarks

Graph
Returns the Y coordinate of the current position (CP).
function GetY: Integer;

The value ofGet X is relative to the dimensions of the active viewport as


the following examples illustrate.
SetViewPort (0,

a,

GetMaxX, GetMaxY, True);

Moves CP to absolute (a, a), and GetY returns a value of o.


MoveTo (5, 5)

Moves CP to absolute (5,5), and GetY returns a value of 5 .


SetViewPort (10, 10, lOa, lOa, True);
Moves CP to absolute (la, 10), but GetY returns a value of o.
MoveTo (5, 5);

Moves CP to absolute (IS, IS), but GetY returns a value of 5.


Restrictions
See also
Example

Must be in graphics mode.

GetViewSettings, GetX, InitGraph, MoveTo, Set ViewPort


uses Graph;

var
Gd, Gm: Integer;
X, Y: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);

OutText('Starting here. ');


X := GetX;
Y := Gety;
OutTextXY(20, 10, 'Now over here ... ');
OutTextXY(X, Y, 'Now back over here.');
Readln;
CloseGraph;
end.

GotoXV procedure
Purpose
Declaration

Crt

Moves the cursor to the given coordinates.


procedure GotoXY(X, Y: Byte);

Chapter 7, Library reference

81

GotoXY procedure

Remarks

Moves the cursor to the position within the current window specified by
X and Y (X.is the column, Yis the row). The upper left corner is (I, 1).
This procedure is window-relative. The following example moves the
cursor to the upper left corner of the active window (absolute coordinates
(I, 10)):
Window(l, 10, 60, 20);
GotoXY(l, 1);

Restrictions
See also

If the coordinates are in any way invalid, the call to GataXY is ignored.

WhereX, Where Y, Window

GraphDefaults procedure
Purpose
Declaration
Remarks

Graph

Resets the graphics settings.


procedure GraphDefaul ts i

Homes the current pointer (CP) and resets the graphics system to the
default values for
Viewport

Restrictions
See also

Palette
Draw and background colors
Line style and line pattern
Fill style, fill color, and fill pattern
Active font, text style, text justification, and user Char size

Must be in graphics mode.

InitGraph

GraphErrorMsg function
Purpose
Declaration
Remarks

82

Graph

Returns an error message string for the specified ErrorCade.


function GraphErrorMsg (ErrorCode: Integer): String;

This function returns a string containing an error message that


corresponds with the error codes in the graphics system. This makes it
easy for a user program to display a descriptive error message ("Device
driver not found" instead of "error code -3").

Programmer's Reference

GraphErrorMsg function

See also

DetectGraph, GraphResult, InitGraph

Example

uses Graph;
var
GraphDriver, GraphMode: Integer;
ErrorCode: Integer;
begin
GraphDriver := Detect;
InitGraph(GraphDriver, GraphMode, ");
ErrorCode := GraphResult;
if ErrorCode <> grOk then
begin
Writeln('Graphics error: ' GraphErrorMsg(ErrorCode));
Readln;

Halt (1);

end;
Line(O, 0, GetMaxX, GetMaxY);
Readln;
CloseGraph;
end.

GraphFreeMemPtr variable
Purpose
Declaration
Remarks

Holds the address of the heap deallocation routine.


var GraphFreeMemPtr: Pointer;

Initially GraphFreeMemPtr points to the Graph unit's heap deallocation


routine. If your program does its own heap management, assign the
address of your de allocation routine to this variable. See Chapter 17,
"Using the Borland Graphics Interface," in the Language Guide for
additional information about this routine.

GraphGetMemPtr variable
Purpose
Declaration
Remarks

Graph

Graph

Holds the address of the heap allocation routine.


var GraphGetMemPtr: Pointer;

Initially GraphGetMemPtr points to the Graph unit's heap allocation


routine. If your program does its own heap management, assign the
address of your allocation routine to this variable. See 17, "Using the
Borland Graphics Interface," in the Language Guide for additional
information about this routine.

Chapter 1, Library reference

83

GraphResult function

Graph

GraphResultfunction
Purpose
Declaration
Remarks

Returns an error code for the last graphics operation.


function GraphResult: Integer;

See page 85 for a list of the grXXXX constant values.


The following routines set GraphResult:

Ear
Bar3D
ClearViewPort
CloseGraph
DetectGraph
DrawPoly
FillPoly
FloodFill

GetGraphMode
Imagesize
InitGraph
InstallUserDriver
InstallUserFont
PieS lice
RegisterBGldriver
RegisterBGIfont

setAllPalette
setFillPattern
setFillStyle
setGraphBufsize
setGraphMode
setLinestyle
setPalette
setTextJustify
setTextstyle

Note that GraphResult is reset to zero after i~ has been called (similar to
IOResult). Therefore, the user should store the value of GraphResult into a
temporary variable and then test it.
A string function, GraphErrorMsg, is provided to return a string that
corresponds with each error code.
See also
Example

GraphErrorMsg, grXXXX constants


uses Graph;
val,'

ErrorCode: Integer;
GrDriver , GrMode: Integer;
begin
GrDriver := Detect;
InitGraph(GrDriver , GrMode , ");
ErrorCode := GraphResu1t;
if ErrorCode <> grOk then
begin
Write1n('Graphics error: ');
Write1n(GraphErrorMsg(ErrorCode)) ;
Write1n(IProgram aborted .. . ');
Halt (1) ;
end;

84

{ Check for errors }

Programmer's Reference

GraphResult function

{ Do some graphics ... }


ClearDevicei
Rectangle(O, 0, GetMaxX, GetMaxY)i
Readln;
CloseGraph;
end.

Graph

grXXXX constants
Purpose

Used by the GraphResult function to indicate the type of error that


occurred.

Remarks

See also

Constant

Value

grOk
grNolnitGraph
gr Not Detected
grFileNotFound
grlnvalidDriver
grNoLoadMem
grNoScanMem
grNoFloodMem
grFontNotFound
grNoFontMem
grlnvalidMode
grError

-11

grIOerror
grlnvalidFont
grlnvalidFontNum

-12
-13
-14

-1

-2
-3
-4

-5
-6
-7
-8
-9
-10

Description

No error.
(BGI) graphics not installed (use InitGraph).
Graphics hardware not detected.
Device driver file not found.
Invalid device driver file.
Not enough memory to load driver.
Out of memory in scan fill.
Out of memory in flood fill.
Font file not found.
Not enough memory to load font.
Invalid graphics mode for selected driver.
Graphics error (generic error); there is no room in
the font table to register another font. (The font
table holds up to 10 fonts, and only 4 are
provided, so this error should not occur.)
Graphics 1/ a error.
Invalid font file; the font header isn't recognized.
Invalid font number; the font number in the font
header is not recognized.

GraphResult

Halt procedure
Purpose
Declaration
Remarks

System

Stops program execution and returns to the operating system.


procedure Hal t [ ( Exi tCode: Word ) 1i

ExitCode is an optional expression of type Word that specifies the


program's exit code. Halt without a parameter corresponds to Halt(D).

Chapter 7, Library reference

85

Halt procedure

Note that Halt initiates execution of any Exit procedures. See


Chapter 20, UControl issues," in the Language Guide for more information.
See also

Exit, RunError

System

HeapEnd variable
Purpose
Declaration
,Remarks
See also

Points to the end of DOS memory used by programs.


var HeapEnd: Pointer;

HeapEnd is initialized by the system unit when your program begins. See
Chapter 19, UMemory issues," in the Language Guide for more information.
HeapOrg, HeapPtr

HeapError variable
Purpose
Declaration
Remarks

System

Points to the heap error function.


var HeapError: Pointer;

HeapError contains the address of a heap error function that is called


whenever the heap manager can't complete an alloc~tion request. Install a
heap error function by assigning its address to HeapError:
HeapError := @HeapFunc;

See Chapter 19, "Memory issues," in the Language Guide for more
information about using heap error functions.
See also

GetMem, New

HeapOrg variable
Purpose
.Declaration

86

System

Points to the bottom of the heap .


var HeapOrg: Pointer;

Remarks

HeapOrg contains the address of the bottom of the heap. See Chapter 19,
"Memory issues," in the Language Guide for more information.

See also

HeapEnd, HeapPtr

Programmer's Reference

HeapPtr variable

HeapPtr variable
Purpose
Declaration

System

Points to the top of the heap.


var HeapPtr: Pointer;

Remarks

HeapPtr contains the address of the top of the heap, that is, the bottom of
free memory. Each time a dynamic variable is allocated on the heap, the
heap manager moves HeapPtr upward by the size of the variable. See
Chapter 19, "Memory issues," in the Language Guide for more information.

See also

HeapOrg, HeapEnd

Hi function
Purpose
Declaration

System
Returns the high-order byte of the argument.
function Hi (X): Byte;

Remarks

X is an expression of type Integer or Word. Hi returns the high-order byte


of X as an unsigned value.

See also

La, Swap

Example

var B: Byte;

begin
B := Hi($1234);
end.

High function
Purpose
Declaration
Result type
Remarks

{ $12 }

System
Returns the highest value in the range of the argument.
function High (X) ;

X, or the index type of X.


X is either a type identifier or a variable reference. The type denoted by X,
or the type of the variable denoted by X, must be an ordinal type, an array
type, or a string type. For an ordinal type, High returns the highest value
in the range of the type. For an array type, High returns the highest value
within the range of the index type of the array. For a string type, High
returns the declared size of the string. For an open array or string

Chapter 7, Library reference

87

High function

parameter, High returns a value of type Word, giving the number of


elements in the actual parameter minus one element.
See also

Low

Example

function Sum(var X: array of Real): Real;


var
I: Word;
S: Real;
begin
S : = 0;
for I := 0 to High(X) do S := S + X[I];
Sum := S;
end;

HighVideo procedure
Purpose
Declaration

Selects high-intensity characters.


procedure HighVideo;

Remarks

There is a Byte variable in Crt-TextAttr-that is used to hold the current


video attribute. High Video sets the high intensity bit of TextAttr's foreground color, thus mapping colors 0-7 onto colors 8-15.

See also

LowVideo, NormVideo, TextBackground, TextColor

Example

uses Crt;
begin
TextAttr := LightGray;
HighVideo;
end.

ImageSize function
Purpose
Declaration
Remarks

88

Crt

{ Color is now white }

Graph

Returns the number of bytes required to store a rectangular region of the


screen.
function ImageSize(Xl, Yl, X2, Y2: Integer): Word;

Xl, Yl, X2, and Y2 define a rectangular region on the screen. ImageSize
determines the number of bytes necessary for GetImage to save the
specified region of the screen. The image size includes space for several
words. The first stores the width of the region, and the second stores the
height. The next words store the attributes of the image itself. The last
word is reserved.

Programmer's Reference

ImageSize function

If the memory required to save the region is greater than or equal to 64K,

a value of 0 is returned and GraphResult returns -11 (grError).


Restrictions

Must be in graphics mode.

See also

GetImage, PutImage

Example

uses Graph;
var
Gd, Gm: Integer;
P: Pointer;
Size: Word;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then

II

Halt (1);

Bar(O, 0, GetMaxX, GetMaxY);


Size := ImageSize(10, 20, 30, 40);
GetMem(P, Size);
Get Image (10, 20, 30, 40, PAl;
Readln;
ClearDevice;
Put Image (100, 100, pA, NormalPut);
Readln;
CloseGraph;
end.

Inc procedure
Purpose
Declaration
Remarks

{ Allocate memory on heap }

System

Increments a variable ..
procedure Inc (var X [ ; N: Longint 1 );

X is an ordinal-type variable or a variable of type PChar if the extended


syntax is enabled and N is an integer-type expression. X is incremented by
1, or by N if N is specified; that is, Inc(X) corresponds to X := X + 1, and
Inc(X, N) corresponds to X := X + N.

Inc generates optimized code and is especially useful in tight loops.


See also

Dec, Pred, Succ

Example

var
IntVar: Integer;
LongintVar: Longint;

Chapter 7 Library reference


I

89

Inc procedure

begin
Inc (IntVar) ;
Inc (LongintVar, 5);
end.

{ IntVar := IntVar + 1 }
{ LongintVar := LongintVar + 5 }

Include procedure
Purpose
Declaration
Remarks

System

Includes an element in a set.


procedure Include (var 8: set of T; I: T);

S is a set type variable, and I is an expression of a type compatible with


the base type of S. The element given by I is included in the set given by S.
The construct
Include (8, I)

corresponds to
8:=8+[I]

but the Include procedure generates more efficient code.


See also

Exclude

Graph

InitGraph procedure
Purpose
Declaration
Remarks

Initializes the graphics system and puts the hardware into graphics mode.
procedure InitGraph(var GraphDriver: Integer; var GraphMode: Integer;
PathToDriver: 8tring);

If GraphDriver is eq-q.al to Detect, a call is made to any user-defined


auto detect routines (see InstallUserDriver) and then DetectGraph. If
graphics hardware is detected, the appropriate graphics driver is
initialized, and a graphics mode is selected.
If GraphDriver is not equal to 0, the value of GraphDriver is assumed to be
a driver number; that driver is selected, and the system is put into the
mode specified'by GraphMode. If you override auto detection in this
manner, you must supply a valid GraphMode parameter for the driver
'
requested.

PathToDriver specifies the directory path where the graphics drivers can
be found. If PathToDriver is null, the driver files must be in the current
directory.

90

Programmer's Reference

InitGraph procedure

Normally, InitGraph loads a graphics driver by allocating memory for the


driver (through GraphGetMem), then loads the appropriate .BGI file from
disk. As an alternative to this dynamic loading scheme, you can link a
graphics driver file (or several of them) directly into your executable
program file. You do this by first converting the .BGI file to an .OBJ file
(using the BINOBJ utility), then placing calls to RegisterBGldriver in your
source code (before the call to InitGraph) to register the graphics driver(s).
When you build your program, you must link the .OBJ files for the
registered drivers. You can also load a BGI driver onto the heap and then
register it using RegisterBGldriver.
If memory for the graphics driver is allocated on the heap using
GraphGetMem, that memory is released when a call is made to CloseGraph.

After calling InitGraph, GraphDriver is set to the current graphics driver,


and GraphMode is set to the current graphics mode.
If an error occurs, both GraphDriver and GraphResult (a function) return
one of the following grXXXX constant values: grNotDetected,
grFileNotFound, grlnvalidDriver, grNoLoadMem, grlnvalidMode. See page 85
for a complete list of graphics error constants.

InitGraph resets all graphics settings to their defaults (current pointer,


palette, color, viewport, and so on).
You can use InstallDriver to install a vendor-supplied graphics driver (see
InstallUserDriver for more information).
Restrictions

See also

Example

Must be in graphics mode. If you use the Borland Graphics Interface (BGI)
on a Zenith Z-449 card, Turbo Pascal's autodetection code will always
select the 640x480 enhanced EGA mode. If this mode isn't compatible
with your monitor, select a different mode in the InitGraph call. Also,
Turbo Pascal cannot autodetect the IBM 8514 graphics card (the
autodetection logic recognizes it as VGA). Therefore, to use the IBM 8514
card, the GraphDriver variable must be assigned the value IBM8514 (which
is defined in the Graph unit) when InitGraph is called. You should not use
DetectGraph (or Detect with InitGraph) with the IBM 8514 unless you want
the emulated VGA mode.

CloseGraph, DetectGraph, GraphDefaults, GraphResult, grXXXX constants,


InstallUserDriver, RegisterBGldriver, RegisterBGIfont, RestoreCrtMode,
SetGraphBufSize, SetGraphMode
uses Graph;

var
grDriver: Integer;
grMode: Integer;

Chapter 7, Library reference

91

InitGraph procedure

ErrCode: Integer;
begin
grDriver := Detect;
InitGraph(grDriver, grMode, ");
ErrCode :~ GraphResult;
if ErrCode = grOk then
begin
Line(O, 0, GetMaxX, GetMaxY);
Readln;
CloseGraph;
end
else
Writeln('Graphics error:', GraphErrorMsg(ErrCode));
end.

{ Do graphics }

System

InOutRes variable
Purpose
.Declaration

Stores the value that the next call to IOResult returns .


var InOutRes: Integer;

Remarks

InOutRes is used by the built-in 1/ a functions.

See also

10Result

Input variable
Purpose
Declaration
Remarks

System
Standard input file.
var Input: Text;

Input is a read~only file associated with the operating system's standard


input file; usually this is the keyboard.
A number of Turbo Pascal's standard file handling procedures and

functions allow the file variable parameter to be omitted, in which case,


the procedure or function will instead operate on the Input or Output file
variable. For example, Read(X) corresponds to .Read(Input, X), and Write(X)
corresponds to Write(Output, X). The following standard file handling
procedures and functions operate on the Input file when no file parameter
is specified: Eof, Eoln, Read,
Readln, SeekEof, and SeekEoln.

92

Programmer's Reference

Input variable

See Chapter 13, "Input and output," in the Language Guide for details
about I/O issues.
See also

Output

System

Insert procedure
Purpose
Declaration

Inserts a substring into a string.


procedure Insert (Source: String; var S: String; Index: Integer);

Remarks

Source is a string-type expression. S is a string-type variable of any length.


Index is an integer-type expression. Insert inserts Source into S at the
Indexth position. If the resulting string is longer than 255 characters, it is
truncated after the 255th character.

See also

Concat, Copy, Delete, Length, Pos

Example

var S: string;

begin
S := 'Honest Lincoln';
Insert ( 'Abe " s, 8);

{ 'Honest Abe Lincoln' }

end.

InsLine procedure
Purpose
Declaration
Remarks

Crt

Inserts an empty line at the cursor position.


procedure Ins Line ;

All lines below the inserted line are moved down one line, and the bottom
line scrolls off the screen (using the BIOS scroll routine).
All character positions are set to blanks with the currently defined text
attributes. Thus, if TextBackground is not black, the new line becomes the
background color.

Example

InsLine is window-relative. The following example inserts a line 60


columns wide at absolute coordinates (1, 10):
Window(l, 10, 60, 20);
InsLine;

See also

DelLine, Window

Chapter 7, Library reference

93

II

InstaliUserDriver function

InstaliUserDriver function

Graph

Purpose

Installs a vendor-added device driver to the BGl device driver table.

Declaration

function InstallUserDri ver (Name: String; AutoDetectptr: Pointer): Integer;

Remarks

InstallUserDriver lets you use a vendor-added device driver. The Name


parameter is the file name of the new device driver. AutoDetectPtr is a
pointer to an optional autodetect function that can accompany the new
driver. This auto detect function takes no parameters and returns an
integer value.
If the internal driver table is full, InstallUserDriver returns a value of -11
(grError); otherwise InstallUserDriver assigns and returns a driver number
for the new device driver.

There are two ways to use this vendor-supplied driver. Let's assume you
have a new video card called the Spiffy Graphics Array (SGA) and that
the SGA manufacturer provided you with a BGl device driver (SGA.BGl).
The easiest way to use this driver is to install it by calling InstallUserDriver
and then passing the return value (the assigned driver number) directly to
InitGraph:
var Driver, Mode: Integer;
begin
Driver := InstallUserDriver('SGA', nil);
if Driver = grError then

{ Table full?

Halt (1);

Mode : = 0;
InitGraph(Driver, Mode, ");

{ Every driver supports mode of 0


{ Override autodetection }
{ Do graphics ... }

end.

The nil value for the AutoDetectPtr parameter in the InstallUserDriver call
indicates there isn't an autodetect function for the SGA.
The other, more general way to use this driver is to link in an autodetect
function that will be called by InitGraph as part of its hardware-detection
logic. Presumably, the manufacturer of the SGA gave you an autodetect
function that looks something like this:
{$F+}

function DetectSGA: Integer;


var Found: Boolean;
begin
DetectSGA := grError;
Found := '"

94

{ Assume it's not there}


{ Look for the hardware }

Programmer's Reference

InstaliUserDriver function

if not Found then


Exit;
DetectSGA := 3;
end;
{$F-}

{ Returns -11 }
{ Return recommended default video mode }

DetectSGA's job is to look for the SGA hardware at run time. If an SGA
isn't detected, DetectSGA returns a value of -11 (grError); otherwise, the
return value is the default video mode for the SGA (usually the best mix
of color and resolution available on this hardware).
Note that this function takes no parameters, returns a signed, integer-type
value, and must be a far call. When you install the driver (by calling
InstallUserDriver), you pass the address of DetectSGA along with the
device driver's file name:
var Driver, Mode: Integer;
begin
Driver := InstallUserDriver('SGA', @DetectSGA);
if Driver = grError then
Ha1t(l) ;
Driver := Detect;
InitGraph(Driver, Mode, ");
{ Discard SGA driver #; trust autodetection }

{ Table full? }

end.

After you install the device driver file name and the SGA auto detect
function, you call InitGraph and let it go through its normal autodetection
process. Before InitGraph calls its built-in autodetection function
(DetectGraph), it first calls DetectSGA. If DetectSGA doesn't find the SGA
hardware, it returns a value of -11 (grError) and InitGraph proceeds with
its normal hardware detection logic (which might include calling any
other vendor-supplied auto detection functions in the order in which they
were "installed"). If, however, DetectSGA determines that an SGA is
present, it returns a nonnegative mode number, and InitGraph locates and
loads SGA.BGl, puts the hardware into the default graphics mode recommended by DetectSGA, and finally returns control to your program.
See also

GraphResult, InitGraph, InstallUserFont, RegisterBGldriver, RegisterBGIfont

Example

uses Graph;
var
Driver, Mode,
TestDriver,
ErrCode: Integer;
{$F+}

Chapter 7, Library reference

95

III

InstaliUserDriver function

function TestDetect: Integer;


{ Autodetect function: assume hardware is always present; return value =
recommended default mode }
begin
{ Default mode = 1 }
TestDetect := 1;
end;
{$F-}
begin
{ Install the driver
TestDriver := InstallUserDriver(/TEST ' @TestDetect};
if GraphResult <> grOk then
begin
Writeln(/Error installing TestDriver / };
Halt (1) ;
end;
{ Put in graphics mode }
Driver := Detect;
InitGraph(Driver , Mode, "J;
ErrCode := GraphResult;
if ErrCode <> grOk then
I

begin
Writeln(/Error during Init:
ErrCode};
Halt (1);
end;
OutText(/Installable drivers supported . .. /};
Readln;
CloseGraph;
end.
I

Graph

InstaliUserFont function
Purpose
Declaration

96

Installs a new font not built into the BGI system.


function InstallUserFont (FontFileName: String): Integer;

Remarks

FontFileName is the file name of a stroked font. InstallUserFont returns the


font ID number that can be passed to SetTextStyle to select this font. If the
internal font table is full, a value of DefaultFont will be returned.

See also

InstallUserDriver, RegisterBGldriver, RegisterBGIfont, SetTextStyle

Example

uses Graph;
var
Driver , Mode: Integer;
TestFont: Integer;

Programmer's Reference

InstaliUserFont function

begin
{ Install the font}
TestFont := InstallUserFont(/TEST / );
if GraphResult <> grOk then
begin
Writeln(/Error installing TestFont (using DefaultFont) ');
Readln;
end;
Driver := Detect;
{ Put in graphics mode }
InitGraph(Driver , Mode, ");
if GraphResult <> grOk then
Halt (1);
SetTextStyle(TestFont , HorizDir , 2);
{ Use new font }
OutText(/Installable fonts supported ... ');
Readln;
CloseGraph;
end.

Int function
Purpose
Declaration

System
Returns the integer part of the argument.
function Int (X: Real): Real;

Remarks

X is a real-type expression. The result is the integer part of X; that is, X


rounded toward zero.

See also

Frac, Round, Trunc

Example

var R: Real;
begin
R := Int(123.456);
R := Int(-123.456);
end.

Intr procedure
Purpose
Declaration

Dos WinDos
1

Executes a specified software interrupt.


procedure Intr (IntNo: Byte; var Regs: Registers);
procedure Intr(IntNo: Byte; var Regs: TRegisters);

Remarks

{ 123.0
{ -123.0

{Dos}
{WinDos}

IntNo is the software interrupt number (0 .. 255). Registers is a record


defined in the Dos unit; TRegisters is a record defined in the WinDos unit.
See page 141 for the declaration of Registers and page 198 for the
declaration of TRegisters.

Chapter 7, Library reference

97

Intr procedure

Before executing the specified software interrupt, Intr loads the 8086
CPU's AX, BX, CX, DX, BP, 51, DI, DS, and ES registers from the Regs
record. When the interrupt completes, the contents of the AX, BX, CX, DX,
BP, 51, DI, DS, ES, and Flags registers are stored back into the Regs record.
For details on writing interrupt procedures, see the section "Interrupt
handling" in Chapter 20 of the Language Guide.
Restrictions
See also

Software interrupts that depend on specific values in SP or 55 on entry, or


modify SP and 55 on exit, cannot be executed using this procedure.

Flag constants, MsDos, Register, TRegister

System

IOResult function
Purpose
Declaration
Remarks

Returns the status of the last 1/ a operation performed.


function IOResult: Integer;

I/O-checking must be off-{$I-}-in order to trap I/O errors using


IOResult. If an I/O error occurs and I/O-checking is off, all subsequent
I/O operations are ignored until a call is made to IOResult. A call to
IOResult clears the internal error flag.
The codes returned are summarized in Chapter 4. A value of 0 reflects a
successful 1/ a operation.

Example

See also

98

var F: file of Byte;


begin
{ Get file name command line }
Assign(F, ParamStr(l));
{$I-}
Reset(F);
{$It}
if IOResult = 0 then
Writeln('File size in bytes: '
else
Writeln('File not found');
end.

FileSize(F))

InOutRes

Programmer's Reference

Justification constants

Justification constants
Purpose

Graph

Constants that control horizontal and vertical justification.

Remarks
Constant

Value

LeftText
CenterText
RightText

BottomText
CenterText
Top Text
See also

1
2

SetTextJustify

Keep procedure
Purpose
Declaration
Remarks

Restrictions

See also

Declaration

Dos

Keep (or terminate and stay resident) terminates the program and makes it
stay in memory.
procedure Keep (Exi tCode: Word);

The entire program stays in memory-including data segment, stack


segment, and heap-so be sure to specify a maximum size for the heap
using the $M compiler directive. The ExitCode corresponds to the one
passed to the Halt standard procedure.
Use with care! Terminate-and-stay-resident (TSR) programs are complex
and no other support for them is provided. See the MS-DOS technical
documentation for more information.

Dos Exit Code

KeyPressed function
Purpose

III

1
2

Crt

Returns True if a key has been pressed on the keyboard; False otherwise.
function KeyPressed: Boolean;

Remarks

The character (or characters) is left in the keyboard buffer. KeyPressed does
not detect shift keys like Shift, Aft, NumLock, and so on.

See also

ReadKey

Chapter 7, Library reference

99 .

KeyPressed function

Example

uses' Crt;
begin
repeat
Write( 'Xx');

{ Fill the screen until a key is typed }

until KeYPressed;
end.

LastMode variable
Purpose
Declaration

Crt

Stores current video mode each time TextMode is called.


var LastMode: Word;

Remarks

At program startup, LastMode is initialized to the then-active video mode.

See also

TextMode

Length function
Purpose
Declaration

System

Returns the dynamic length of a string.


function Length (S: String): Integer;

Remarks

Returns the length of the String S.

See also

Concat, Copy, Delete, Insert, Pos

Example

var S: String;
begin
Readln(S) ;
Writeln('II', S, '"');
Writeln('length = " Length(S));

end.

Line procedure
Purpose
Declaration
Remarks

100

Graph

Draws a line from the (Xl, Yl) to (X2, Y2).


procedure Line (Xl, Yl, X2, Y2: Integer);

Draws a line in the style and thickness defined by SetLineStyle and uses
the color set bySetColor. Use SetWriteMode to determine whether the line
is copied or XORed to the screen.

Programmer's Reference

Line procedure

Note that
MoveTo(100, 100);
LineTo(200, 200);

is equivalent to
Line(100, 100, 200, 200);
MoveTo(200, 200);

Use LineTo when the current pointer is at one endpoint of the line. If you
want the current pointer updated automatically when the line is drawn,
use LineRel to draw a line a relative distance from the CPo Note that Line
doesn't update the current pointer.
Restrictions

Must be in graphics mode. Also, for drawing a horizontal line, Bar is faster
than Line.

See also

GetLineStyle, LineRel, LineTo, MoveTo, Rectangle, SetColor, SetLineStyle,


Set WriteMode

Example

uses Crt, Graph;


var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then

Halt(l);

Randomize;
repeat
Line (Random(200), Random(200) , Random(200) , Random(200));
until KeyPressedi
Readlni
CloseGraph;
end.

Line style constants


Purpose
Remarks

Graph

Constants used to determine a line style and thickness; used with


GetLineSettings and SetLineStyle.
The following Line style constants are defined:
Constant

Value

SolidLn
DottedLn
CenterLn
DashedLn

Chapter 7, Library reference

2
3

101

Line style constants

4 (user-defined line style)


1 .
3,

UserBitLn
Norm Width
ThickWidth

See also

LineSettingsType

Graph

LineRel procedure
Purpose

Draws a line to a point that is a relative distance from the current pointer
(CP).

Declaration
Remarks

procedure LineRel (Dx,

Dy:

Integer);

LineRel will draw a line from the current pomter to a point that is a
relative (Dx, Dy) distance from the current pointer. The current line style
and pattern, as set by SetLineStyle, are used for drawing the line and uses
the color set by SetColor. Relative move and line commands are useful for
drawing a shape on the screen whose starting point can be changed to
draw the same shape in a different location on the screen. Use
SetWriteMode to determine whether the line is copied or XORed to the
screen.
The current pointer is set to the last point drawn by LineRel.

Restrictions

Must be in graphics mode.

See also

GetLineStyle, Line, LineTo, MoveRel, MoveTo, SetLineStyle, SetWriteMode

Example

uses Graph;
var Gd, Gm: Integer;
begin
Gd :=Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;

MoveTo(l, 2);
LineRel(100, 100);
Readln;
CloseGraph;
end.

102

{ Draw to the point (101,102) }

Programmer's Reference

LineSeHingsType type

LineSettingsType type
Purpose
Declaration

Graph

The record that defines the style, pattern, and thickness of a line.
type
LineSettingsType= record
LineStyle: Word;
Pattern: Word;
Thickness: Word;
end;

Remarks

See Line style constants for a list of defined line styles and thickness values.

See also

GetLineSettings, SetLineStyle

_Li_n_e_To__p_ro__
c_e_d_u_re______________________________~__G
__ra_p__h
Purpose
Declaration
Remarks

Draws a line from the current pointer to (X, Y).


procedure LineTo(X, Y: Integer);

Draws a line in the style and thickness defined by SetLineStyle and uses
the color set by SetColor. Use SetWriteMode to determine whether the line
is copied or XORed to the screen.
Note that
MoveTo(100, 100);
LineTo(200, 200);

is equivalent to
Line(100, 100, 200, 200);

The first method is slower and uses more code. Use LineTo only when the
current pointer is at one endpoint of the line. Use LineRel to draw a line a
relative distance from the CPo Note that the second method doesn't
change the value of the current pointer.

LineTo moves the current pointer to (X, Y).


Restrictions

Must be in graphics mode.

See also

GetLineStyle, Line, LineRel, MoveRel, MoveTo, SetLineStyle, SetWriteMode

Example

uses Crt, Graph;


var Gd, Gm: Integer;

Chapter 7, Library reference

103

LineTo procedure

begin
Gd : = Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;

Randomize;
repeat
LineTo(Random(200) , Random(200));
until KeyPressed;
Readln;
CloseGraph;
end.

Ln function
Purpose
Declaration

System
Returns the natural logarithm of the argument.
function Ln(X: Real): Real;

Remarks

Returns the natural logarithm of the real-type expression X.

See also

Exp

Lo function
Purpose
Declaration

System
Returns the low-order byte of the argument.
function Lo (X): Byte;

Remarks

X is an expression of type Integer or Word. Lo returns the low-order byte of


X as an unsigned value.

See also

Hi, Swap

Example, var B: Byte;


begin
B
end.

:=

Lo($1234);

{$34}

Low function
Purpose
Declaration
Result type

104

System
Returns the lowest value in the range of the argument.
function Low (X) ;

X, or the index type of X.

Programmer's Reference

Low function

Remarks

X is either a type identifier or a variable reference. The type denoted by X,


or the type of the variable denoted by X, must be an ordinal type, an array
type, or a string type. For an ordinal type, Low returns the lowest value in
the range of the type. For an array type, Low returns the lowest value
within the range of the index type of the array. For a string type, Low
returns O. For an open array or string parameter, Low returns O.

See also

High

Example

var
A: array[l .. 100] of Integeri
I: Integer;
begin
for I := Low(A) to High(A) do A[I] := Oi
end.
type
TDay = (Monday, Tuesday, Wednesday, Thursday,
Friday, Saturday, SundaY)i
const
DayNarne: array [TDay] of string[3] = (
'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
var
Day: TDaYi
Hours: array [TDay] of 0 .. 24i
begin
for Day := Low (TDay) to High (TDay) do
begin
Write('Hours worked on " DayNarne[Day] , '7 ')i
Readln(Hours[Day]) i
endi
end.

LowVideo procedure
Purpose
Declaration

Crt

Selects low-intensity characters.


procedure Lowvideoi

Remarks

There is a Byte variable in Crt-TextAttr-that holds the current video


attribute. LowVideo clears the high-intensity bit of TextAttr's foreground
color, thus mapping colors 8 to 15 onto colors 0 to 7.

See also

HighVideo, NormVideo, TextBackground, TextColor

Chapter 7, Library reference

105

LowVideo procedure

Example

uses Crt;
begin
TextAttr := White;
LowVideo;
end.

{ Color is now light gray }

Printer

Lst variable
Purpose
Declaration

Stores the standard output as a text file.


var Lst: Text;

Remarks

Use Lst to send the output of your program to the printer.

See also

Assign, Rewrite

Example

program Print It ;
var
Lst: Text;
begin
Assign(Lst, 'LPT1');
Rewrite (Lst) ;
Writeln(Lst, 'Hello printer.');
Close(Lst)
end.

MaxAvail function
Purpose

Declaration
Remarks

{ Declare Lst as text file variable


{ Assign text file to standard output
{ Call Rewrite to send text file to printer }
{ Close text file }

System

Returns the size of the largest contiguous free block in the heap,
corresponding to the size of the largest dynamic variable that can be
allocated at that time.
function MaxAvail: Longint;

MaxAvail returns the size of the largest contiguous free block in the heap,
corresponding to the size of the largest dynamic variable that can be
allocated at that time using New or GetMem. To find the total amount of
free memory in the heap, call MemAvail.
MaxAvail compares the size of the largest free block below the heap
pointer to the size of free memory above the heap pointer, and returns the
larger of the two values. Your program can specify minimum and
maximum heap requirements using the $M directive.

See also

106

MemAvail

Programmer's Reference

MaxAvaii function

Example

type
PBuffer = ATBuffer;
TBuffer = array[O .. 163831 of Char;
var Buffer: PBuffer;
begin
if MaxAvail < SizeOf(TBuffer) then OutOfMernory else
begin
New (Buffer) ;
end;
end.

MaxColors constant
Purpose
Declaration
See also

Graph

The constant that determines the maximum number of colors.


const MaxColors

= 15;

GetDefaultPalette, GetPalette, SetAllPalette

MemAvail function
Purpose
Declaration
Remarks

System

Returns the amount of free memory in the heap.


function MernAvail: Longint;

MernAvail returns the sum of the sizes of all free blocks in the heap. Note
that a contiguous block of storage the size of the returned value is
unlikely to be available due to fragmentation of the heap. To find the
largest free block, call MaxAvail.

MemAvail is calculated by adding the sizes of all free blocks below the
heap pointer to the size of free memory above the heap pointer. Your
program can specify minimum and maximum heap requirements using
the $M directive.
See also

MaxAvail

Chapter 7, Library reference

107

II

MemAvaii function

Example

begin
Writeln(MemAvail, , bytes available');
Writeln('Largest free block is " MaxAvail, , bytes');
end.

System

MkDir procedure
Purpose
Declaration
Remarks

Creates a subdirectory.
procedure MkDir (S: String);

Creates a new subdirectory with the path specified by string S. The last
item in the path cannot be an existing file name.
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.

See also

ChDir, GetDir, RmDir. CreateDir performs the same function as MkDir, but
it takes a null-terminated string rather than a Pascal-style string.

Example

begin
{$I-}
MkDir(ParamStr(l)) ;
if IOResult <> 0 then
Wri teln,( , Cannot create directory')
else
Writeln('New directory created');
end.

{ Get directory name from command line }

System

Move procedure
Purpose
Declaration
Remarks

Copies a specified number of contiguous bytes from a source range to a


destination range.
procedure Move (var Source, Dest; Count: Word);

Source and Dest are variable references of any type. Count is an expression
of type Word. Move copies a block of Count bytes from the first byte
occupied by Source to the first byte occupied by Dest. No checking is
performed, so be careful with this procedure.
I

When Source and Dest are in the same segment, that is, when the segment
parts of their addresses are equal, Move automatically detects and
compensates for any overlap. Intrasegment overlaps never occur on

108

Programmer's Reference

Move procedure

statically and dynamically allocated variables (unless they are deliberately


forced); therefore, such deliberately forced overlaps are not detected.
Whenever possible, use SizeO! to determine Count.
See also

FillChar

Example

var
A: array[l .. 4J of Char;
B: Longint;
begin
Move (A, B, SizeOf(A));
end.

{ SizeOf = safety! }

Graph

MoveRel procedure
Purpose
Declaration
Remarks

Moves the current pointer (CP) a relative distance from its current
location.
procedure MoveRel (Dx,

Dy:

Integer);

MoveRel moves the current pointer (CP) to a point that is a relative


(Dx, Dy) distance from the current pointer. Relative move and line

commands are useful for drawing a shape on the screen whose starting
point can be changed to draw the same shape in a different location on the
screen.
Restrictions

Must be in graphics mode.

See also

GetMaxX, GetMaxY, GetX, GetY, LineRel, Line To, MoveTo

Example

uses Graph;
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);

MoveTo(l, 2);
MoveRel(lO, 10);
Put Pixel (GetX, Gety, GetMaxColor);
Readln;
CloseGraph;
end.

Chapter 7, Library reference

{ Move to the point (11, 12) }

109

MoveTo procedure

Graph

MoveTo procedure
Purpose
Declaration
Remarks

Moves the current pointer (CP) to (X, Y).


procedure MoveTo(X, Y: Integer);

The CP is similar to a text mode cursor except that the CP is not visible.
The following routines move the CP:

Clear Device
Clear ViewPort
GraphDefaults
InitGraph

OutText
SetGraphMode
Set ViewPort

LineRel
LineTo
MoveRel
MoveTo

If a viewport is active, the CP will be viewport-relative (the X and Y


values will be added to the viewport's Xl and Yl values). The CP is never

clipped at the current viewport's boundaries.


See also

GetMaxX, GetMaxY, GetX, GetY, MoveRel

Example

uses Graph;
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);

MoveTo(O, 0);
LineTo(GetMaxX, GetMaxY);
Readln;
CloseGraph;
end.

MsDos procedure
Purpose
Declaration

110

Dos, WinDos

Executes a DOS function call.


procedure MsDos (var Regs: Registers);
procedure MsDos(var Regs: TRegisters);

Remarks

{ Upper left corner of viewport }

{Dos}
{WinDos}

The effect of a call to MsDos is the same as a call to Intr with an IntNo of
$21. Registers is a record defined in the Dos unit. TRegisters is defined in
the WinDos unit. See page 141 for the declaration of Registers and page 198
for the declaration of TRegisters.

Programmer's Reference

MsDos procedure

Restrictions
See also

Software interrupts that depend on specific calls in SP or SS on entry or


modify SP and SS on exit cannot be executed using this procedure.

Intr, Registers, TRegisters

System

New procedure
Purpose
Declaration
Remarks

Creates a new dynamic variable and sets a pointer variable to point to it.
procedure New(var P: Pointer [

Init: Constructor 1 )i

P is a variable of any pointer type. The size of the allocated memory block
corresponds to the size of the type that P points to. The newly created
variable can be referenced as PA. If there isn't enough free space in the
heap to allocate the new variable, a run-time error occurs. (It is possible to
avoid a run-time error in this case; see "The HeapError variable" in
Chapter 19 in the Language Guide.)

New allows a constructor call as a second parameter for allocating a


dynamic object type variable. P is a pointer variable, pointing to an object
type, and Init refers to a constructor of that object type.
An additional extension allows New to be used as a function, which
allocates and returns a dynamic variable of a specified type. If the call is of
the form New(T), T can be any pointer type. If the call is of the form
New(T, Init), T must be a pointer to an object type, and Init must refer to a
constructor of that object type. In both cases, the type of the function
result is T.
See also

Dispose, FreeMem,GetMem, HeapError

NormVideo procedure
Purpose
Declaration

Crt

Selects the original text attribute read from the cursor location at startup.
procedure NorrnVideo i

Remarks

There is a Byte variable in Crt-TextAttr-that holds the current video


attribute. NormVideo restores TextAttr to the value it had when the
program was started.

See also

HighVideo, LowVideo, TextBackground, TextColor

Chapter 7, Library reference

111

II

NoSound procedure

NoSound procedure
Purpose
Declaration
Remarks

Crt

Turns off the internal speaker..


procedure NoSound;

The following program fragment emits a 440-hertz tone for half a second:
Sound(440);
Delay(500);
NoSound;

See also

Sound

Odd function
Purpose
Declaration
Remarks

System
Tests if the argument is an odd number.
function Odd (X: Longint): Boolean;

X is an integer-type expression. The result is True if X is an odd number,


and False if X is an even number.

Ofs function
Purpose
Declaration

System
Returns the offset of a specified object.
function Ofs (X): Word;

Remarks

X is any variable, or a procedure or function identifier. The result of type


Word is the offset part of the address of X.

Restrictions

In protected-mode programs, Gfs should be used only on valid pointer


addresses; pointing to an invalid pointer address will generate a general
protection fault error message.

See also

Addr, Seg

Ord function
Purpose
Declaration

112

System
Returns the ordinal value of an ordinal-type expression.
function Ord (X): Longint;

Programmer's Reference

Ord function

Remarks

X is an ordinal-type expression. The result is of type Longint and its value


is the ordinality of X.

See also

Chr

Output variable
Purpose
Declaration
Remarks

System

Standard output file.


var Output: Text i

Output is a write-only file associated with the operating system's standard


output file, which is usually the display.
A number of Turbo Pascal's standard file handling procedures and
functions allow the file variable parameter to be omitted, in which case
the procedure or function will instead operate on the Input or Output file
variable. For example, Read(X) corresponds to Read(Input, X), and Write(X)
corresponds to Write(Output, X). The following standard file handling
procedures and functions operate on the Output file when no file
parameter is specified: Write, Writeln. See Chapter 13 "Input and output,"
in the Language Guide for details about 110 issues.

See also

Input

OutText procedure
Purpose
Declaration
Remarks

Graph

Sends a string to the output device at the current pointer.


procedure OutText (TextString: String)

Displays TextString at the current pointer using the current justification


settings. TextString is truncated at the viewport border if it is too long. If
one of the stroked fonts is active, TextString is truncated at the screen
boundary if it is too long. If the default (bit-mapped) font is active and the
string is too long to fit on the screen, no text is displayed.

OutText uses the font set by SetTextStyle. In order to maintain code compatibility when using several fonts, use the TextWidth and TextHeight calls
to determine the dimensions of the string.
OutText uses the output options set by SetTextJustify (justify, center, rotate
90 degrees, and so on).
The current pointer (CP) is updated by OutText only if the direction is
horizontal, and the horizontal justification is left. Text output direction is

Chapter 7, Library reference

113

OutText procedure

set by SetTextStyle (horizontal or vertical); text justification is set by


SetTextJustify (CP at the left of the string, centered around CP, or CP at the
right of the string-written above CP, below CP, or centered around CP).
In the following example, block #1 outputs ABCDEF and moves CP (text
is both horizontally output and left-justified); block #2 outputs ABC with
DEF written right on top of it because text is right-justified; similarly,
block #3 outputs ABC with DEF written right on top of it because text is
written vertically.,
program CPupdate;
uses Graph;
var Driver, Mode: Integer;
begin
Driver := Detect;
InitGraph(Driver, Mode, _");
if GraphResult < 0 then
Halt(l) ;
{ #1 }

MoveTo(O, 0);
SetTextStyle(DefaultFont, HorizDir, 1);
SetTextJustify(LeftText, TopTe~t);
OutText (' ABC') ;
OutText ('DEF') ;

{ CharSize = 1 }
{ CP is updated }
{ CP is updated }

{ #2 }

MoveTo(100, 50);
SetTextStyle(DefaultFont, HorizDir, 1);
SetTextJustify(RightText, TopText);
OutText (' ABC') ;
OutText ('DEF') ;

{ CharSize = 1 }
{ CP is updated }
{ CP is updated }

{ #3 }

MoveTo(100, 100);
SetTextStyle(DefaultFont, VertDir, 1);
SetTextJustify(LeftText, TopText)i
OutText (' ABC') i
OutText ( 'DEF') i
Readlni
CloseGraphi
end.

{ CharSize = 1 }
{ CP is NOT updated }
{ CP is NOT updated }

The CP'is never updated by OutTextXY.


The default font (8x8) is not clipped at the screen edge. Instead, if any part
of the string would go off the screen, no text is output. For example, the
following statements would have no effect:

114

Programmer's Reference

OutText procedure

SetViewPort(O, 0, GetMaxX, GetMaxY, ClipOn);


SetTextJustify(LeftText, TopText);
OutTextXY(-5, 0);
OutTextXY(GetMaxx - 1, 0, 'ABC');

{ -5,0 not onscreen }


{ Part of 'A', }
{ All of 'BC' off screen}

The stroked fonts are clipped at the screen edge, however.


Restrictions

Must be in graphics mode.

See also

GetTextSettings, OutTextXY, SetTextfustify, SetTextStyle, SetUserCharSize,


TextHeight, TextWidth

Example

uses Graph;
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);

OutText('Easy to use');
Readln;
CloseGraph;
end.

OutTextXy procedure
Purpose
Declaration
Remarks

Graph

Sends a string to the output device.


procedure OutTextXY(X, Y: Integer; TextString: String);

Displays TextString at (X, Y). TextString is truncated at the viewport


border if it is too long. If one of the stroked fonts is active, TextString is
truncated at the screen boundary if it is too long. If the default (bitmapped) font is active and the string is too long to fit on the screen, no
text is displayed.
Use OutText to output text at the current pointer; use OutTextXY to output
text elsewhere on the screen.
procedure, OutTextXY and In order to maintain code compatibility when
using several fonts, use the TextWidth and TextHeight calls to determine
the dimensions of the string.
OutTextXYuses the output options set by SetTextJustify (justify, center,
rotate 90 ,degrees, and so forth).

Restrictions

Must be in graphics mode.

Chapter 1, Library reference

115

OutTextXY procedure

See also

GetTextSettings, OutText, SetTextJustify, SetTextStyle, SetUserCharSize,


TextHeight, TextWidth

Example

uses Graph;
var
Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;

MoveTo(O, 0);
OutText('Inefficient');
Readln;
OutTextXY(GetX, GetY, 'Also inefficient');
Readln;
ClearDevice;
OutTextXY(O, 0, 'Perfect!');
Readln;
CloseGraph;
end.

OvrClearBuf procedure
Purpose
Declaration
Remarks

{ Replaces above }

Overlay

Clears the overlay buffer.


procedure OvrClearBuf;

Disposes of all currently loaded overlays from the overlay buffer. This
forces subsequent calls to overlaid routines to reload the overlays from
the overlay file (or from EMS). If OvrClearBufis called from an overlay,
that overlay will immediately be reloaded upon return from OvrClearBuf
The overlay manager never requires you to call OvrClearBuf; in fact, doing
so will decrease performance of your application, since it forces overlays
to be reloaded. OvrClearBufis solely intended for special use, such as
temporarily reclaiming the memory occupied by the overlay buffer.

See also

OvrGetBuf, OvrSetBuf

OvrCodeList variable
Purpose
Declaration

116

System

Overlay code segment list.


var OvrCodeList: Word;

Programmer's Reference

OvrCodeList variable

Remarks

OvrCodeList is initialized at link time by Turbo Pascal's linker and used


internally by the overlay manager. It is zero if the program contains no
overlays, or nonzero otherwise. You should never modify OvrCodeList.

OvrDebugptr variable
Purpose
Declaration
Remarks

Overlay debugger hook.


var OvrDebugPtr: Pointer;

OvrDebugPtr is used by Turbo Pascal's integrated debugger and by Turbo


Debugger to implement debugging of overlaid programs. You should
never modify OvrDebugPtr.

OvrDosHandle variable
Purpose
Declaration
Remarks

See also

System

System

Overlay file handle.

var OvrDosHandle: Word;

OvrDosHandle stores the file handle of the program's overlay file.


OvrDosHandle is initialized by the Ovrlnit routine in the Overlay unit. A
value of zero in OvrDosHandle indicates that the overlay file is not
currently open. You should never modify OvrDosHandle.
Overlnit

OvrEmsHandle variable
Purpose

Overlay EMS handle.

Declaration

var OvrEmsHandle: Word;

System

Remarks

OvrEmsHandle stores the handle of the expanded memory block


containing the program's overlays. OvrEmsHandle is initialized by the
OverlnitEMS routine in the Overlay unit. A value of $FFFF in
OvrEmsHandle indicates that no expanded memory block has been.
allocated for overlays. You should never modify OvrEmsHandle.

See also

Overlnit,OverlnitEMS

Chapter 7, Library reference

117

OvrFileMode variable

OvrFileMode variable
Purpose
Declaration

Overlay

Determines the access code to pass to DOS when the overlay file is
opened.
var OvrFileMode: Byte;

Remarks

The default OvrFileMode is 0, corresponding to read-only access. By


assigning a new value to OvrFileMode before calling Ovrlnit, you can
change the access code. You might change it to allow shared access on a
network system, for example. For further details on access code values,
see your DOS programmer's reference manual.

See also

Ovrlnit

Overlay

OvrGetBuf function
Purpose
Declaration

Returns the current size of the overlay buffer.


function OvrGetBuf: Longint;

Remarks

The size of the overlay buffer is set through a call to OvrSetBuf Initially,
the overlay buffer is as small as possible, corresponding to the size of the
largest overlay. When an overlajd program is executed, a buffer of this
size is automatically allocated. Because it includes both code and fix-up
information for the largest overlay, however, the initial buffer size could
be larger than 64K.

See also

Ovrlnit, OvrlnitEMS, OvrSetBuf

Example

{$M 16384,65536,655360}
uses Overlay;
const ExtraSize = 49152; {48K}
begin
Ovrlnit('EDITOR.OVR');
Writeln('Initial size of overlay buffer is " OvrGetBuf,' bytes.');
OvrSetBuf(OvrGetBuf+ExtraSize);
Writeln('Overlay buffer now increased to " OvrGetBuf,' bytes.');
end.

OvrGetRetry function
Purpose
Declaration

118

Overlay

Returns the current size of the probation area.


function OvrGetRetry: Longint;

Programmer's Reference

OvrGetRetry function

Remarks

OvrGetRetry returns the current size of the probation area which is the
value last set with OvrSetRetry.

See also

OvrSetRetry

OvrHeapEnd variable
Purpose
Declaration

System

Overlay buffer end.


var OvrHeapEnd: Word;

Remarks

OvrHeapEnd stores the segment address of the end of the overlay buffer.
Except as specified in the description of OvrHeapOrg, you should never
modify OvrHeapEnd.

See also

OvrHeapOrg, OvrSetBuf

OvrHeapOrg variable
Purpose
Declaration
Remarks

System

Overlay buffer origin.


var OvrHeapOrg: Word;

OvrHeapOrg stores the segment address of the start of the overlay buffer.
The run-time library's start-up code initializes OvrHeapOrg, OvrHeapPtr,
and OvrHeapEnd to point to an overlay buffer between the program's stack
segment and heap. The size of this initial overlay buffer (in 16-byte
paragraphs) is given by the OvrHeapSize variable, and it corresponds to
the size of the largest overlay in the program, including fixup information
for the overlay.
.
It is possible for a program to move the overlay buffer to another location

in memory by assigning new values to OvrHeapOrg, OvrHeapPtr, and


OvrHeapEnd. Any such relocation should be done before the call to Ovrlnit
or right after a call to OvrClearBuf to ensure that the overlay buffer is
empty. To move the overlay buffer, assign the segment address of the start
of the buffer to OvrHeapOrg and OvrHeapPtr, and assign the segment
address of the end of the buffer to OvrHeapEnd. You must ensure that the
size of the buffer (calculated by OvrHeapEnd - OvrHeapOrg) is greater than
or equal to OvrHeapSize.
See also

OvrHeapEnd, OvrHeapPtr, OvrSetBuf

Chapter 1, Library reference

119

II

OvrHeapPtr variable

OvrHeapPtr variable
Purpose
Declaration
. Remarks
See also

System

Overlay buffer pointer.


var OvrHeapPtr: Word;

OvrHeapPtr is used internally by the overlay manager. Except as specified


in the description of OvrHeapOrg, you should never modify OvrHeapPtr.
OvrHeapOrg

OvrHeapSize variable
Purpose
Declaration

System

Minimum overlay heap size.


var OvrHeapSize:Word;

Remarks

OvrHeapSize contains the minimum size of the overlay buffer in 16-byte


paragraphs. OvrHeapSize is initialized at link time to contain the size of
the largest overlay in the program, including fixup information for the
overlay. It is zero if the program contains no overlays. You should never
modify OvrHeapSize.

See also

OvrHeapOrg

Ovrlnit procedure
Purpose
Declaration
Remarks

Overlay

Initializes the overlay manager and opens the overlay file.


procedure Ovrlnit(FileName: String);

If FileName does not specify a drive or asubdirectory, the overlay manager

searches for the file in the current directory, in the directory that contains
the .EXE file (if running under DOS 3.x or later), and in the directories
specified in the PATH environment variable.
Errors are reported in the OvrResult variable. ovrOk indicates success.
ovrError means that the overlay file is of an incorrect format, or that the
program has no overlays. ovrNotFound means that the overlay file could
not be located.
In case of error, the overlay manager remains uninstalled, and an attempt
to call an overlaid routine win produce run-time error 208 ("Overlay
manager not installed").

120

Programmer's Reference

Ovrlnit procedure

Ovrlnit must be called before any of the other overlay manager


procedures.
See also

OvrGetBuf, OvrlnitEMS, OvrSetBuf

Example

uses Over lay;


begin
OvrInit('EDITOR.OVR') ;
if OvrResult <> ovrOk then
begin
case OvrResult of
ovrError: Writeln('Program has no overlays.');
ovrNotFound: Writeln('Overlay file not found.');
end;
Halt (1) ;

end;
end.

OvrlnitEMS procedure
Purpose
Declaration
Remarks

Overlay

Loads the overlay file into EMS if possible.


procedure OvrIni tEMS;

If an EMS driver can be detected and if enough EMS memory is available,


OvrlnitEMS loads all overlays into EMS and closes the overlay file.
Subsequent overlay loads are reduced to fast in-memory transfers.
OvrlnitEMS installs an exit procedure, which automatically deallocates
EMS memory upon termination of the program.
Errors are reported in the OvrResult variable. ovrOk indicates success.
ovrError means that Ovrlnit failed or was not called. ovrIOError means that
an I/O error occurred while reading the overlay file. ovrNoEMSDriver
means that an EMS driver could not be detected. ovrNoEMSMemory
means that there is not enough free EMS memory available to load the
overlay file.
In case of error, the overlay manager will continue to function, but
overlays will be read from disk.
The EMS driver must conform to the Lotus/Intel/Microsoft Expanded
Memory Specification (EMS). If you are using an EMS-based RAM disk,
make sure that the command in the CONFIG.SYS file that loads the
RAM-disk driver leaves some unallocated EMS memory for your overlaid
applications.

See also

OvrGetBuf, Ovrlnit, OvrResult, OvrSetBuf

Chapter 7, Library reference

121

OvrlnitEMS procedure

Example

uses Overlay;
begin
OvrInit(/EDITOR.OVR / };
if OvrResult <> ovrOk then
begin
Writeln(/Overlay manager initialization failed. I};
Halt(l} ;
end;
OvrInitEMS;
case OvrResult of
ovrIOError: Writeln(/Overlay file I/O error. I};
ovrNoEMSDriver: Writeln( I EMS driver not installed. I};
ovrNoEMSMemory: Writeln(/Not enough EMS memory. I};
else Writeln(/Using EMS for faster overlay swapping. I};
end;
end;

OvrLoadCount variable
Purpose
Declaration
Remarks

Overlay

Overlay load count.


var OvrLoadCount: Word;

The initial value of OvrLoadCount is zero. The overlay manager increments


OvrLoadCount each time an overlay is loaded. By examining OvrTrapCount
and OvrLoadCount in the Debugger's Watch window during identical runs
of an application, you can monitor the effect of different probation area
sizes (set with OvrSetRetry) to find the optimal size for your particular
application.

See also . OvrTrapCount

OvrLoadList variable
Purpose
Declaration
Remarks

122

System

Loaded overlays list.


var OvrLoadList: Word;

OvrLoadList is used internally by the overlay manager. You should never


modify OvrLoadList.

Programmer's Reference

OvrReadBuf variable

OvrReadBuf variable
Purpose
Declaration
Remarks

Overlay read function pointer.


type OvrReadFunc = function (OvrSeg: Word): Integeri
var OvrReadBuf: OvrReadFunci

OvrLoadList lets you intercept overlay load operations to implement error


handling, for example, or to check that a removable disk is present.
Whenever the overlay manager needs to read an overlay, it calls the
function whose address is stored in OvrReadBuf If the function returns
zero, the overlay manager assumes that the operation was successful; if
the function result is nonzero, run-time error 209 is generated. The OvrSeg
parameter indicates what overlay to load, but you'll never need to access
this information. See Chapter 18, "Using overlays," in the Language Guide
for details about installing your own overlay read function.

OvrResult variable
Purpose
Declaration

Overlay

Overlay

Result code for last overlay procedure call.


var OvrResul t: Integer i

Remarks

Before returning, each of the procedure in the Overlay unit stores a result
code in the ovrResult variable. Possible OvrXXXX return codes are listed
on page 125. In general, a value of zero indicates success. The OvrResult
variable resembles the IOResult standard function except that OvrResult is
not set to zero once it is accessed. Thus, there is no need to copy OvrResult
into a local variable before it is examined.

See also

Ovrlnit, OvrlnitEMS, OvrSetBuf

OvrSetBuf procedure
Purpose
Declaration
Remarks

Overlay

Sets the size of the overlay buffer.


procedure OvrSetBuf (BufSize: Longint) i

BufSize must be larger than or equal to the initial size of the overlay buffer,
and less than or equal to MemAvail + OvrGetBuf The initial size of the
overlay buffer is the size returned by OvrGetBufbefore any calls to
OvrSetBuf

Chapter 7, Library reference

123

OvrSetBuf procedure

If the specified size is larger than the current size, additional space is
allocated from the beginning of the heap, thus decreasing the size of the
heap. Likewise, if the specified size is less than the current size, excess
space is returned to the heap.
OvrSetBuj requires that the heap be empty; an error is returned if dynamic
variables have already been allocated using New or GetMem. For this
reason, make sure to call OvrSetBujbefore the Graph unit's InitGraph
procedure; InitGraph allocates memory on the heap and-once it has done
so-all calls to OvrSetBuj will be ignored.
If you are using OvrSetBuj to increase the size of the overlay buffer, you
should also include a $M compiler directive in your program to increase
the minimum size of the heap accordingly.

Errors are reported in the OvrResult variable. ovrOk indicates success.


ovrError means that Ovrlnit failed or was not called, that BujSize is too
small, or that the heap is not empty. ovrNoMemory means that there is not
enough heap memory to increase the size of the overlay buffer.
See also

OvrGetBuf, Ovrlnit, OvrlnitEMS, OvrResult, ovrXXXX constants

Example

{$M 16384,65536, 655360}


uses Overlay;
const ExtraSize = 49152; {48K}
begin
Ovrlnit('EDITOR.OVR');
OvrSetBuf(OvrGetBuf + ExtraSize);
end.

Overlay

OvrSetRetry procedure
Purpose
Declaration
~emarks

Sets the size of the probation area in the overlay buffer.


procedure OvrSetRetry(Size: Longint);

If an overlay falls within the Size bytes before the overlay buffer tail, it is
automatically put on probation. Any free space in the overlay buffer is
considered part of the probation area. For reasons of compatibility with
earlier versions of the overlay manager, the default probation area size is
zero, which effectively disables the probation/reprieval mechanism.

There is no empirical formula for determining the optimal size of the


probationary area; however, experiments have shown that values ranging
from one-third to one-half of the overlay buffer size provide the best
results.

124

Programmer's Reference

OvrSetRetry procedure

See also

OvrGetRetry

Example

Here's an example of how to use OvrSetRetry:


Ovrlni t ( MYPROG. OVR
OvrSetBuf(BufferSize) ;
OvrSetRetry(BufferSize div 3);
I

I );

OvrTrapCount variable
Purpose
Declaration

Overlay

Overlay call interception count.


var OvrTrapCount: Word;

Remarks

Each time a call to an overlaid routine is intercepted by the overlay


manager, either because the overlay is not in memory or because the
overlay is on probation, the OvrTrapCount variable is incremented. The
initial value of OvrTrapCount is zero.

See also

OvrLoadCount

ovrXXXX constants
Purpose

Overlay

Return codes stored in the OvrResult variable.

Remarks
Constant

ovrOk
ovrError
ovrNotFound
ovrNoMemory
ovrIOError
ovrNoEMSDriver
ovrNoEMSMemory

Value

o
-1
-2
-3
-4
-5
-6

Meaning

Success
Overlay manager error
Overlay file not found
Not enough memory for overlay buffer
Overlay file 1/ 0 error
EMS driver not installed
Not enough EMS memory

PackTime procedure
Purpose
Declaration

Dos, WinDos

Converts a DateTime record into a 4-byte, packed date-and-time Longint


used by SetFTime.
procedure PackTime (var DT: DateTime; var Time: Longint);
procedure PackTime(var DT: TDateTime; var Time: Longint);

Chapter 7, Library reference

{Dos}
{WinDos}

125

PackTime procedure

Remarks

The fields of the DateTime record are not range-checked. DateTime is a


DOS record; use TDateTime if you are writing a program using WinDos.
See page 26 for the declaration of DateTime or page 189 for the TDateTime
declaration.

See also

GetFTime, GetTime, SetFTime, SetTime, UnpackTime

Graph

PaletteType type
Purpose
Declaration

The record that defines the size and colors of the palette; used by
GetPalette, GetDejaultPalette, and SetAllPalette.
type
PaletteType = record
Size: Byte;
Colors: array[O .. MaxColors] of Shortint;
end;

PaletteType is defined as follows:


const
MaxColors = 15;
type
PaletteType = record
Size: Byte;
Colors: array[O .. MaxColors] of Shortint;
end;

The size field reports the number of colors in the palette for the current
driver in the current mode. Colors contains the actual colors O.. Size - 1.

System

ParamCount function
Purpose
Declaration

126

Returns the number of parameters passed to the program on the


command line.
function ParamCount: Word;

Remarks

Blanks and tabs serve as separators.

See also

ParamStr

Programmer's Reference

ParamCount function

Example

begin
if ParamCount = 0 then
Writeln('No parameters on command line')
else
Writeln(ParamCount, , parameter(s)');
end.

ParamStr function
Purpose
Declaration

System

Returns a specified command-line parameter.


function ParamStr (Index): String;

Remarks

Index is an expression of type Word. ParamStr returns the Indexth


parameter from the command line, or an empty string if Index is greater
than ParamCount. ParamStr(O) returns the path and file name of the
executing program (for example, C: \ TP\MYPROG.EXE).

See also

ParamCount

Example

var I: Word;
begin
for I := 1 to ParamCount do
Writeln(ParamStr(I) );
end.

Pi function
Purpose
Declaration
Remarks

System
Returns the value of pi (3.1415926535897932385).
function Pi: Real;

Precision varies, depending on whether the compiler is in 80x87 or


software-only mode.

PieSlice procedure
Purpose
Declaration
Remarks

Graph

Draws and fills a pie slice, using (X, Y) as the center point and drawing
from start angle to end angle.
procedure PieS lice (X, Y: Integer; StAngle, EndAngle, Radius: Word);

The pie slice is outlined using the current color, and filled using the
patternand color defined by SetFillStyle or SetFillPattern.

Chapter 7, Library reference

127

PieSlice procedure /

Each graphics driver contains an aspect ratio that is used by Circle, Arc,
and PieS lice. A start angle of 0 and an end angle of 360 will draw and fill a
complete circle. The angles for Arc, Ellipse, and PieS lice are counterclockwise with 0 degrees at 3 a' clock, 90 degrees at 12 a' clock, and so on.
If an error occurs while filling the pie slice, GraphResuU returns a value of

grNoScanMem.
Restrictions

Must be in graphics mode.

See also

Arc, Circle, Ellipse, FillEllipse, GetArcCoords, GetAspectRatio, Sector,


SetFillStyle, SetFillPattern, SetGraphBujSize

Example

uses Graph;
const Radius = 30;
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;
PieSlice(100, 100, 0, 270, Radius);
Readln;
CloseGraph;
end.

PointType type
Purpose
Declaration

type
PointType = record
X, Y: Integer;
end;

System

Purpose

Searches for a substring in.a string.

D.eclaration

function Pos (Substr, S: String): Byte;

Remarks

Graph

A type defined for your convenience. Both fields are of type Integer rather
than Word.

Pas function

128

Substr and S are string-type expressions. Pos searches for Substr within S,
and returns an integer value that is the index of the first character of
Substr within S. If Substr is not found, Pos returns zero.

Programmer's Reference

Pos function

See also

Concat, Copy, Delete, Insert, Length

Example

var S: String i
begin
S .-

123.S ' i

while POS('
S) > 0 do
S[POS(' " S)] := 'O'i
end.

{ Convert spaces to zeros }

I I

Pred function
Purpose
Declaration

System
Returns the predecessor of the argument.
function Pred (X)

Remarks

X is an ordinal-type expression. The result, of the same type as X, is the


predecessor of X.

See also

Dec, Inc, Succ

PrefixSeg variable
Purpose
Declaration
Remarks

System

Contains the segment address of the Program Segment Prefix (PSP)


created by DOS when the application executes.
var PrefixSeg: Wordi

For a complete description of the Program Segment Prefix, see your DOS
manuals.

Ptr function
Purpose
Declaration
Remarks

System
Converts a segment base and an offset address to a pointer-type value.
function Ptr(Seg , Ofs: Word): Pointeri

Seg and Ofs are expressions of type Word. The result is a pointer that
points to the address given by Seg and Ofs. Like nil, the result of Ptr is
assignment compatible with all pointer types.
The function result can be dereferenced and typecast:
if Byte(Ptr(Seg0040 , $49)")

Writeln(/Video mode

See also

= 7 then

= mono/)i

Addr, Ofs, Seg

Chapter 7, Library reference

129

Ptr function

Example

var P: AByte;
begin
P := Ptr(Seg0040, $49);
Writeln('Current video mode is'
end.

PAl;

Putlmage procedure
Purpose
Declaration
Remarks

Graph

Puts a bit image onto the screen.


procedure PutImage (X, Y: Integer; var BitMap; BitBlt: Word);

(X, Y) is the upper left corner of a rectangular region on the screen. BitMap
is an untyped parameter that contains the height and width of the region,
and the bit image that will be put onto the screen. BitBlt specifies which
binary operator will be used to put the bit image onto the screen. See
page 12 for a list of BitBlt operators.
Each constant corresponds to a binary operation. For example,
PutImage(X, Y, BitMap, NorrnalPut) puts the image stored in BitMap at
(X, Y) using the assembly language MOV instruction for each byte in the
image.
Similarly, PutImage(X, Y, BitMap, XORPut) puts the image stored in
BitMap at (X, Y) using the assembly language XOR instruction for each
byte in the image. This is an often-used animation technique for
"dragging" an image around the screen.

PutImage(X, Y, BitMap, NotPut) inverts the bits in BitMap and then puts
the image stored in BitMap at (X, Y) using the assembly language MOV for
each byte in the image. Thus, the image appears in inverse video of the
original BitMap.
Note that PutImage is never clipped to the viewport boundary.
Moreover-with one exception-it is not actually clipped at the screen
edge either. Instead, if any part of the image would go off the screen, no
image is output. In the following example, the first image would be
output, but the middle three PutImage statements would have no effect:
program NoClipi
uses Graphi
var
Driver, Mode: Integer;
P: Pointer;

130

Programmer's Reference

Putlmage procedure

begin
Driver := Detect;
InitGraph(Driver, Mode, "};
if GraphResult < 0 then
Halt (1);
SetViewPort(O, 0, GetMaxX, GetMaxY, ClipOn};
GetMem(p, ImageSize(O, 0, 99, 49}};
PieSlice(50, 25, 0, 360, 45};
GetImage(O, 0, 99, 49, PAl;
ClearDevice;
PutImage(GetMaxX - 99, 0,
pA, NormalPut};
PutImage(GetMaxX - 98, 0,
pA, NormalPut};
PutImage (-1, 0,
pA, NormalPut);
PutImage (0, -1,
pA, NormalPut);
Put Image (0, GetMaxY - 30,
pA, NormalPut};
Readln;
CloseGraph;
end.

width = 100, height = 50


{ Will barely fit
{ X + Height > GetMaxX
-1,0 not onscreen
0,-1 not onscreen
Will output 31 "lines"

In the last PutImage statement, the height is clipped at the lower screen
edge, and a partial image is displayed. This is the only time any clipping
is performed on PutImage output.
Restrictions

Must be in graphics mode.

See also

BitBlt operators, GetImage, ImageSize

Example

uses Graph;

var
Gd, Gm: Integer;
P: Pointer;
Size: Word;
begin
Gd := Detect;
InitGraph(Gd, Gm, "};
if GraphResult <> grOk then
Halt(l} ;
Bar(O, 0, GetMaxX, GetMaxY};
Size := ImageSize(10, 20, 30, 40};
GetMem(P, Size};
Get Image (10, 20, 30, 40, PA};
Readln;
ClearDevice;

Chapter 7, Library reference

{Allocate memory on heap}

131

Putlmage procedure

PutImage(100, 100, pA, NormalPut);


Readln;
CloseGraph;
end ..

PutPixel procedure
Purpose
Declaration
Remarks
Restrictions

Graph

Plots a pixel at X, Y.
procedure Putpixel (X, Y: Integer; Pixel: Word);

Plots a point in the color defined by Pixel

~t (X,

Y).

Must be in graphics mode.

See also

GetImage, GetPixel, PutImage

Example

uses Crt, Graph;


var
Gd, Gm: Integer;
Color: Word;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;

Color := GetMaxColor;
Randomize;
repeat
PutPixel(Random(100), Random(100), Color);
Delay(10) ;
until KeyPressed;
Readln;
CloseGraph;
end.

Random function
Purpose
Declaration
Result type
Remarks

132

{ Plot "stars" }

System

Returns a random number.


function Random [ ( Range: Word) 1;

Real or Word, depending on the parameter


If Range'is not specified, the result is a Real-type random number within
the range 0 <= X < 1. If Range is specified, it must be an expression of

Programmer's Reference

Random function

type Word, and the result is a Word-type random number within the range
a <= X < Range. If Range equals 0, a value of ais returned.
The random number generator should be initialized by making a call to
Randomize, or by assigning a value to RandSeed.
See also

Randomize

System

Randomize procedure
Purpose
Declaration

Initializes the built-in random generator with a random value.


procedure Randomize;

Remarks

The random value is obtained from the system clock. The random number
generator's seed is stored in a predeclared Longint variable called
RandSeed.

See also

Random

System

RandSeed variable
Purpose
Declaration

Stores the built-in random number generator's seed.


var RandSeed: Longint;

Remarks

By assigning a specific value to RandSeed, a specific sequence of random


numbers can be generated over and over. This is particularly useful in
applications that deal with data encryption, statistics, and simulations.

See also

Random, Randomize

System

Read procedure (text files)


Purpose
Declaration
Remarks

Reads one or more values from a text file into one or more variables.
procedure Read ( [ var F: Text; 1 V1 [f V2f

f VN 1 );

F, if specified, is a text file variable. If F is omitted, the standard file

variable Input is assumed. Each V is a variable of type Char, Integer, Real,


or String .
With a type Char variable, Read reads one character from the file and
assigns that character to the variable. If Eof(F) was True before Read was
executed, the value Chr(26) (a Ctrl+Z character) is assigned to the
variable. If Eoln(F) was True, the value Chr(13) (a carriage-return

Chapter 7, Library reference

133

Read procedure (text files)

character) is assigned to the variable. The next Read starts with the next
character in the file.
With a type integer variable, Read expects a sequence of characters that
form a signed whole number according to the syntax illustrated in
section "Numbers" in Chapter 2 of the Language Guide. Any blanks,
.tabs, or end-of-line markers preceding the numeric string are skipped.
Reading ceases at the first blank, tab, or end-of-line marker following
the numeric string or if Eof(F) becomes True. If the numeric string does
not conform to the expected format, an I/O error occurs; otherwise; the
value is assigned to the variable. If Eof(F) was True before Read was
executed or if Eof(F) becomes True while skipping initial blanks, tabs,
and end~of-line markers, the value 0 is assigned to the variable. The
next Read will start with the blank, tab, or end-of-line marker that
terminated the numeric string.
With a type real variable, Read expects a sequence of characters that
form a signed whole number (except that hexadecimal notation is not
allowed). Any blanks, tabs, or end-of-line markers preceding the
numeric string are skipped. Reading ceases at the first blank, tab, or
end-of-line marker following the numeric string or if Eof(F) becomes
True. If the numeric string does not conform to the expected format, an
I/O error occurs; otherwise, the value is assigned to the variable. If
Eof(F) was True before Read was executed, or if Eof(F) becomes True
while skipping initial blanks, tabs, and end-of-line markers, the value 0
is assigned to the variable. The next Read will start with the blank, tab,
or end-of-line marker that terminated the numeric string.
With a type string variable, Read reads all characters up to, but not
including, the next end-of-line marker or until Eof(F) becomes True. The
resulting character string is assigned to the variable. If the resulting .
string is longer than the maximum length of the string variable, it is
truncated. The next Read will start with the end-of-line marker that
terminated the string.
When the extended syntax is enabled, Read can also be used to read
null-terminated strings into zero-based character arrays. With a
character array of the form array[O .. N] of Char, Read reads up to N
characters, or until Eoln(F) or Eof(F) become True, and then appends a
NULL (#0) terminator to the string.
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.
Restrictions

134

Re.ad with a type string variable does not skip to the next line after
reading. For this reason, you cannot use successive Read calls to read a
sequence of strings because you'll never get past the first line; after the

Programmer's Reference

Read procedure (text files)

first Read, each subsequent Read will see the end-of-line marker and return
a zero-length string. Instead, use multiple Readln calls to read successive
string values.
See also

Readln, Write, Writeln

Read procedure (typed files)


Purpose
Declaration
Remarks

System

Reads a file component into a variable.


procedure Read (F, V1

[,

V2'

, VN

1 )i

F is a file variable of any type except text, and each V is a variable of the
same type as the component type of F. For each variable read, the current
file position is advanced to the next component. An error occurs if you
attempt to read from a file when the current file position is at the end of
the file; that is, when Eof(F) is True.
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.

Restrictions
See also

File must be open.

Write

ReadKey function
Purpose
Declaration
Remarks

Crt

Reads a character from the keyboard.


function ReadKey: Char i

The character read is not echoed to the screen. If KeyPressed was True
before the call to ReadKey, the character is returned immediately.
Otherwise, ReadKey waits for a key to be typed.
The special keys on the PC keyboard generate extended scan codes.
Special keys are the function keys, the cursor control keys, Alt keys, and so .
on. When a special key is pressed, ReadKey first returns a null character
(#0), and then returns the extended scan code. Null characters cannot be
generated in any other way, so you are guaranteed the next character will
be an extended scan code.
The following program fragment reads a character or an extended scan
code into a variable called Ch and sets a Boolean variable called FuncKey
to True if the character is a special key:

Chapter 7, Library reference

135

ReadKey function

Ch : = ReadKey;
if Ch <> #0 then FuncKey := False else
begin
FuncKey : = True;
Ch : = ReadKey;
end;

The CheckBreak variable controls whether Ctrl+Break should abort the


program or be returned like any other key. When CheckBreak is False,
ReadKey returns a Ctrl+C (#3) for Ctrl+Break.
See also

Key Pressed

System

Readln procedure
Purpose
Declaration
Remarks

Executes the Read procedure then skips to the next line of the file.
procedure Readln ( [ var F: Text;

1 vi [, V2'

, VN

1 );

Readln is an extension to Read, as it is defined on text files. After executing


the Read, Readln skips to the beginning of the next line of the file.
Readln(F) with no parameters causes the current file position to advance to
the beginning of the next line if there is one; otherwise, it goes to the end
of the file. Readln with no parameter list corresponds to Readln(Input).
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.

Restrictions
See also

Works only on text files. File must be open for input.

Read

Graph

Rectangle procedure
Purpose
Declaration
Remarks

Draws a rectangle using the current line style and color.


procedure Rectangle (Xl, Y1, X2, Y2: Integer);

(Xl, Yl) define the upper left corner of the rectangle, and (X2, Y2)
define the lower right comer (0 <= Xl < X2 <= GetMaxX, and
o <= Yl < Y2 <= GetMaxY).
Draws the rectangle in the current line style and color, as set by
SetLineStyle and SetColor. Use SetWriteMode to determine whether the
rectangle is copied or XORed to the screen.

136

Programmer's Reference

Rectangle procedure

Restrictions

Must be in graphics mode.

See also

Bar, Bar3D, GetViewSettings, InitGraph, SetColor, SetLineStyle, Set ViewPort,


Set WriteMode

Example

uses Crt, Graph;


var
GraphDriver, GraphMode: Integer;
Xl, Y1, X2, Y2: Integer;
begin
GraphDriver := Detect;
InitGraph(GraphDriver, GraphMode, ");
if GraphResult<> grOk then
Halt (1) ;

Randomize;
repeat
Xl := Random(GetMaxX);
Y1 := Random(GetMaxY);
X2 := Random(GetMaxX - Xl) + Xl;
Y2 := Random(GetMaxY - Y1) + Y1;
Rectangle (Xl, Y1, X2, Y2);
until KeyPressed;
CloseGraph;
end.

RegisterBGldriver function
Purpose
Declaration
Remarks

Graph

Registers a user-loaded or linked-in BGI driver with the graphics system.


function RegisterBGIdriver (Driver: Pointer): Integer;

If an error occurs, the return value is less than 0; otherwise, the internal
driver number is returned.
This routine enables a user to load a driver file and "register" the driver
by passing its memory location to RegisterBGldriver. When that driver is
used by InitGraph, the registered driver will be used (instead of being
loaded from disk by the Graph unit). A user-registered driver can be
loaded from disk onto the heap, or converted to an .OBJ file (using
BINOBJ .EXE) and linked into the .EXE.
Returns grlnvalidDriver if the driver header is not recognized.
The following program loads the eGA driver onto the heap, registers it
with the graphics system, and calls InitGraph:

Chapter 1, Library reference

137

RegisterBGldriver function

program LoadDriv;
uses Graph;
var
Driver, Mode: Integer;
DriverF: file;
DriverP: Pointer;
begin
{ Open driver file, read into memory, register it }
Assign (DriverF, 'CGA.BGI'};
Reset (DriverF, 1};
GetMem(DriverP, FileSize(DriverF}};
BlockRead(DriverF, DriverP A , FileSize(DriverF}};
if RegisterBGldriver(DriverP} < 0 then
begin
Writeln('Error registering driver: '
GraphErrorMsg(GraphResult}};
Halt (1) ;
end;
{ Init graphics
Driver := CGA;
Mode : = CGAHi;
InitGraph(Driver, Mode, "} i
if GraphResul t < 0 then
Halt (1);
OutText('Driver loaded by user program'};
Readlni
CloseGraphi
end.

The program begins by loading the eGA driver file from disk and
registering it with the Graph unit~ Then a call is made to InitGraph to
initialize the graphics system. You might wish to incorporate one or more
driver files directly into your .EXE file. In this way, the graphics drivers
that your program needs will be built-in and only the .EXE will be needed
in order to run. The process for incorporating a driver file into your .EXE
is straightforward:
1. ~un BINOBJ on the driver file(s).
2. Link the resulting .OBJ file(s) into your program.
3. Register the linked-in driver file(s) before calling InitGraph.

For a detailed explanation and example of the preceding, see the


comments at the top of the BGILINK.PAS example program onthe
distribution disks. For information on the BINOBJ utility, see the file
UTILS. Doe (in ONLINE.ZIP) on your distrih~tion disks.

138

Programmer's Reference

RegisterBGldriver function

It is also possible to register font files; see the description of

RegisterBGIfont.
Restrictions

See also

Note that the driver must be registered before the call to InitGraph. If a call
is made to RegisterBGldriver once graphics have been activated, a value of
grError will be returned. If you want to register a user-provided driver,
you must first call InstallUserDriver, then proceed as described in the
previous example.

InitGraph, InstallUserDriver, RegisterBGIfont

RegisterBGlfont function
Purpose
Declaration
Remarks

Graph

Registers a user-loaded or linked-in BCI font with the graphics system.


function RegisterBGIfont(Font: Pointer): Integer;

The return value is less than 0 if an error occurs. Possible error codes are
grError, grlnvalidFont, and grlnvalidFontNum. If no error occurs, the
internal font number is returned. This routine enables a user to load a font
file and "register'~ the font by passing its memory location to
RegisterBGIfont. When that font is selected with a call to SetTextStyle, the
registered font will be used (instead of being loaded from disk by the
Graph unit). A user-registered font can be loaded from disk onto the heap,
or converted to an .OBJ file (using BINOBJ.EXE) and linked into the .EXE.
There are several reasons to load and register font files. First, Graph only
keeps one stroked font in memory at a time. If you have a program that
needs to quickly alternate between stroked fonts, you might want to load
and register the fonts yourself at the beginning of your program. Then
Graph will not load and unload the fonts each time a call to SetTextStyle is
made.
Second, you might wish to incorporate the font files directly into your
.EXE file. This way, the font files that your program needs will be built-in,
and only the .EXE and driver files will be needed in order to run. The
process for incorporating a font file into your .EXE is straightforward:
1. Run BINOBJ on the font file(s).

2. Link the resulting .OBJ file(s) into your program.


3. Register the linked-in font file(s) before calling InitGraph.
For a detailed explanation and example of the pre~eding, see the
comments at the top of the BCILINK.PAS example program on the

Chapter 7, Library reference

139

RegisterBGlfont function

distribution disks. Documentation on the BINOBJ utility is available in the


file UTILS.DOC (in ONLINE.ZIP) on your distribution disks.
Note that the default (8x8 bit-mapped) font is built into GRAPH.TPU, and
thus is always in memory. Once a stroked font has been loaded, your
program can alternate between the default font and the stroked font
without having to reload either one of them.
It is also possible to register driver files; see the description of

ReglsterBGldriver.
The following program loads the triplex font onto the heap, registers it
with the graphics system, and then alternates between using triplex and
another stroked font that Graph loads from disk (SansSerifFont):
program LoadFont;
uses Graph;
var
Driver, Mode: Integer;
FontF: file;
FontP: Pointer;
begin
{ Open font file, read into memory, register it }
Assign(FontF, 'TRIP.CHR');
Reset (FontF, 1);
GetMem(FontP, FileSize(FontF));
BlockRead(FontF, Fontp A , FileSize(FontF));
if RegisterBGIfont(FontP) < 0 then
begin
Writeln('Error registering font: ' GraphErrorMsg(GraphResult));
Halt (1) ;
end;
{ Init graphics
Driver := Detect;
InitGraph(Driver, Mode, ' .. \');
if GraphResult < 0 then
Halt(l) ;
Readln;
{ Select registered font
SetTextStyle(TriplexFont, HorizDir, 4);
OutText ('Triplex loaded by user program');
MoveTo(O, TextHeight('a'));
Readln;
{ Select font that must be loaded from disk }
SetTextStyle(SansSerifFont, HorizDir, 4);
OutText('Your disk should be spinning ... ');
MoveTo(O, Gety + TextHeight('a'));
Readln;

140

Programmer's Reference

RegisterBGlfont function

{ Reselect registered font (already in memory)


SetTextStyle(TriplexFont, HorizDir, 4);
OutText('Back to Triplex');
Readln;
CloseGraph;
end.

The program begins by loading the triplex font file from disk and
registering it with the Graph unit. Then a call to InitGraph is made to
initialize the graphics system. Watch the disk drive indicator and press
Enter. Because the triplex font is already loaded into memory and registered, Graph does not have to load it from disk (and therefore your disk
drive should not spin). Next, the program will activate the sans serif font
by loading it from disk (it is unregistered). Press Enter again and watch the
drive spin. Finally, the triplex font is selected again. Since it is in memory
and already registered, the drive will not spin when you press Enter.
See also

InitGraph, InstallUserDriver, InstallUserFont, RegisterBGIfont, SetTextStyle

Registers type
Purpose

Declaration

Dos
The Intr and MsDos procedures use a variable parameter of type Registers
to specify the input register contents and examine the output register
contents of a software interrupt.
type
Registers = record
case Integer of
0: (AX, BX, CX, DX, BP, SI, DI, DS, ES, Flags: Word);
1: (AL, AR, BL, BH, CL, CH, DL, DH: Byte);
end;

Notice the use of a variant record to map the 8-bit registers on top of their
16-bit equivalents.
See also

Intr, MsDos

RemoveDir procedure
Purpose
Declaration
Remarks

WinDos

Removes an empty subdirectory.


procedure RemoveDir (Dir: PChar);

The subdirectory with the path specified by Dir is removed. Errors, such
as a non-existing or non-empty subdirectory, are reported in the DosError
variable.

Chapter 7, Library reference

141

RemoveDir procedure

See also

GetCurDir, CreateDir, SetCurDir. RmDir removes an empty subdirectory


also, but it takes a Pascal-style string as the argument rather than a nullterminated string.

Rename procedure '


Purpose
Declaration
Remarks

System

Renames an external file.


procedure Rename (var F; Newname);

F is a variable of any file type. Newname is a string-type expression or an


expression of type PChar if the extended syntax is enabled. The external
file associated with F is renamed to Newname. Further operations on F
operate on the external file with the new name.
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.

Restrictions
See also

Never use Rename on an open file.

Erase

Reset procedure
Purpose
Declaration
Remarks

System

Opens an existing file.


procedure Reset (var F [: file; RecSize: word 1 );

F is a variable of any file type associated with an external file using Assign.
RecSize is an optional expression of type Word, which can be specified only
if F is an untyped file. If F is an untyped file, RecSize specifies the record
size to be used in data transfers. If RecSize is omitted, a default record size
of 128 bytes i~ assumed.

Reset opens the existing external file with the name assigned to F. An error
results if no existing external file of the given name exists. If F is already
open, it is first closed and then reopened. The current file position is set to
the beginning of the file.
If F is assigned an empty name, such as Assign(F, If), then after the call to
Reset, F refers to the standard input file (standard handle number 0).
If F is a text file, F becomes read-only. After a call to Reset, Eof(F) is True if
the file is empty; otherwise, Eof(F) is False. .
.

142

Programmer's Reference

Reset procedure

With {$I-}, IOResult returns 0 if the operation was, successful; otherwise, it


returns a nonzero error code.
See also

Append, Assign, Close, Rewrite, Truncate

Example

function FileExists (FileName: String): Booleani


{ Boolean function that returns True if the file existsi otherwise, it returns
False. Closes the file if it exists. }
var F: filei
begin
{$I-}
Assign(F, FileName) i
{ Set file access to read only. }
FileMode := Oi
Reset (F) i
Close (F) i
{$It }

FileExists := (IOResult
endi {FileExists}

0) and (FileName <> ")

begin
if FileExists(ParamStr(l)) then
Writeln('File e~ists')
else
Writeln('File not found') i
end.

{ Get file name from command line }

RestoreCrtMode procedure
Purpose
Declaration
Remarks

Restrictions

Graph

Restores the screen mode to its original state before graphics mode was
initialized.
procedure RestoreCrtMode i

Restores the original video mode detected by InitGraph. Can be used in


conjunction with SetGraphMode to switch back and forth between text and
graphics modes.
Must be in graphics mode.

See also

CloseGraph, DetectGraph, GetGraphMode, InitGraph, SetGraphMode

Example

uses Graphi
var
Gd, Gm: Integeri
Mode: Integeri
begin
Gd.:= Detecti
InitGraph(Gd, Gm,

Chapter 7, Library reference

")i

143

RestoreCrtMode procedure

if GraphResult <> grOk then


Halt (1) i
OutText('<ENTER> to leave graphics:') i
Readlni
RestoreCrtModei
Writeln('Now in text mode')i
Write('<ENTER> to enter graphics mode:') i
Readlni
SetGraphMode(GetGraphMode) i
OutTextXY(O, 0, 'Back in graphics mode')i
OutTextXY(O, TextHeight('H'), '<ENTER> to quit:')
Readlni
CloseGraphi
end.

Rewrite procedure
Purpose
Declaration
Remarks

System

Creates and opens a new file.


procedure Rewrite (var F [: file i RecSize: Word 1 ) i

F is a variable of any file type associated with an external file using Assign.
RecSize is an optional expression of type Word, which can only be specified
if F is an untyped file. If F is an untyped file, RecSize specifies the record
size to be used in data transfers. If RecSize is omitted, a default record size
of 128 bytes is assumed.

Rewrite creates a new external file with the name assigned to F. If an


external-file with the same name already exists, it is deleted and a new
empty file is created in its place. If F is already open, it is first closed and
then re-created. The current file position is set to the beginning of the
empty file.
If F was assigned an empty name, such as Assign(F, "), then after the call
to Rewrite, F refers to the standard output file (standard handle number 1).
If F is a text file, F becomes write-only. After a call to Rewrite, Eof(F) is
always True.

With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it


returns a nonzero error code.
See also

144

Append, Assign, FileMode, Lst, Reset, Truncate

Programmer's Reference

Rewrite procedure

Example

var F: Text;
begin
Assign(F, 'NEWFILE.$$$'};
Rewrite (F) ;
Writeln(F, 'Just created file with this text in it ... '};
Close (F) ;
end ..

RmDir procedure
Purpose
Declaration
Remarks

System

Removes an empty subdirectory.


procedure RmDir (S: String);

Removes the subdirectory with the path specified by S. If the path does
not exist, is non-empty, or is the currently logged directory, an IIO error
occurs.
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.

See also

MkDir, ChDir, GetDir.' RemoveDir performs the same function as RmDir,


but it takes a null-terminated string as an argument rather than a Pascalstyle string.

Example

begin
{$I-}
RmDir(PararnStr(l}};
if IOResult <> 0 then
Writeln('Cannot remove directory'}
else
Writeln('Directory removed'};
end.

{ Get directory name from command line }

Round function
Purpose
Declaration
Remarks

I
System

Rounds a real-type value to an integer-type value.


function Round (X: Real): Longint;

X is a real-type expression. Round returns a Longint value that is the value


of X rounded to the nearest whole number. If X is exactly halfway
between two whole numbers, the result is the number with the

Chapter 7, Library reference

145

Round function

greatest absolute magnitude. A run-time error occurs if the rounded value


of X is not within the Longint range.
See also

Int, Trunc

RunError procedure
Purpose
Declaration

System

Stops program execution and generates a run-time error.


procedure RunError [ ( ErrorCode: Byte ) 1i

Remarks

The RunError procedure corresponds to the Halt procedure, except in


addition to stopping the program, it generates a run-time error at the
current statement. ErrorCode is the run-time error number (0 if omitted). If
the current module is compiled with debug information on, and you're
running the program from the IDE, Turbo Pascal automatically takes you
to the RunError call, just as if an ordinary run-time error occurred.

See also

Exit, Halt

Example

{$IFDEF Debug}

if P = nil then
RunError(204) i
{$ENDIF}

SavelntXX variables
Purpose
Declaration

146

System

Stores interrupt vectors.


The System unit declares the following SaveIntXX variables.
Name

Type

Description

SavelntOO
Savelnt02
SavelntlB
SaveInt21
SaveInt23
Savelnt24
Savelnt34
Savelnt35
Saveint36
Savelnt37
Savelnt38
SaveInt39
Savelnt3A

Pointer
Pointer
Pointer
Pointer
Pointer
Pointer
Pointer
Pointer
Pointer
Pointer
Pointer
Pointer
Pointer

{ Saved interrupt $00 }


{ Saved interrupt $02 }
{ Saved interrupt $lB } .
{ Saved interrupt $21 }
{ Saved interrupt $23 }
{ Saved interrupt $24 }
{ Saved interrupt $34 }
{ Saved interrupt $35 }
{ Saved interrupt $36 }
{ Saved interrupt $37 }
{ Saved interrupt $38 }
{ Saved interrupt $39 }
{ Saved interrupt $3A }

Programmer's Reference

SavelntXX variables

Savelnt3B
Savelnt3C
Savelnt3D
SaveInt3E
Savelnt3F
Savelnt75

Remarks

Pointer
Pointer
Pointer
Pointer
Pointer
Pointer

{ Saved interrupt $3B }


{ Saved interrupt $3C }
{ Saved interrupt $3D }
{ Saved interrupt $3E }
{ Saved interrupt $3F }
{ Saved interrupt $75 }

The System unit and a number of other run-time library units take over
several interrupt vectors. The run.;.time library initialization code in the
System unit stores the old vectors in the SavelntXX variables before
installing any interrupt handling routines. Likewise, the run-time library
termination code restores the interrupt vectors using the SavelntXX
variables before returning to the operating system.
If an application needs to access the "original" interrupt vector (the one
that was in place before the run-time library installed a new interrupt
handler), it can access the corresponding SavelntXX variable. If there is no
SavelntXX variable for a particular interrupt vector, it is because the runtime library doesn't modify that vector.

See also

Exec, Swap Vectors

SearchRec type
Purpose
Declaration

Dos

The FindFirst and FindNext procedures use variables of type SearchRec to


scan directories.
type

SearchRec = record
Fill: array[l .. 21] of Byte;
Attr: Byte;
Time: Longint;
Size: Longint;
Name: string[12];
end;

The information for each file found by one of these procedures is reported
back in a SearchRec. The Aftr field contains the file's attributes (constructed
from file attribute constants), Time contains its packed date and time (use
UnpackTime to unpack), Size contains its size in bytes, and Name contains
its name. The Fill field is reserved by DOS and should never be modified.

Chapter 7, Library reference

147

Sector procedure

Sector procedure
Purpose
Declaration
Remarks

Graph.

Draws and fills an elliptical sector.


procedure Sector(X, Y: Integer; StAngle, EndA)1gle, XRadius, YRadius: Word);

Using (X, Y) as the center point, XRadius and YRadius specify the
horizontal and vertical radii, respectively; Sector draws from StAngle to
EndAngle, outlined in the current color and filled with the pattern and
color defined by SetFillStyle or SetFillPattern.
A start angle of 0 and an end angle of 360 will draw and fill a complete
ellipse. The angles for Arc, Ellipse, FillEllipse, PieS lice, and Sector are
counterclockwise with 0 degrees at3 o'clock, 90 degrees at 12 o'clock, and
soon.

If an error occurs while filling the sector, GraphResult returns a value of


grNoScanMem.
Restrictions

Must be in graphics mode.

See also

Arc, Circle, Ellipse, FillEllipse, GetArcCoords, GetAspectRatio, PieS lice,


SetFillStyle, SetFillPattern, SetGraphBufSize

Example

uses Graph;
const R = 50;
var
Driver, Mode: Integer;
Xasp, Yasp: Word;
begin
Driver := Detect;
InitGraph(Driver, Mode, ");
if GraphResult < 0 then

{ Put in graphics mode }

Halt (1);

Sector(GetMaxX div 2, GetMaxY div 2, 0, 45, R, R);


GetAspectRatio(Xasp, Yasp);
Sector(GetMaxX div 2, GetMaxY div 2,
180, US,

R, R * Longint(Xasp) div Yasp);


Readln;
CloseGraph;
end.

148

{ Draw circular sector


{ Center point
{ Mirror angle above
{ Circular

}
}
}
}

Programmer's Reference

Seek procedure

Seek procedure
Purpose
Declaration
Remarks

System

Moves the current position of a file to a specified component.


procedure Seek(var F; N: Longint);

F is any file variable type except text, and N is an expression of type


Longint. The current file position of F is moved to component number N.
The number of the first component of a file is O. To expand a file, you can
seek one component beyond the last component; thatis, the statement
Seek(F, FileSize(F)) moves the current file position to the end of the file.
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.

Restrictions
See also

Cannot be used on text files .. File must be open.

FilePos

SeekEof function
Purpose
Declaration
Remarks

System

Returns the end-of-file status of a file.


function SeekEof [ (var F: Text) l: Boolean;

SeekEof corresponds to Eof except that it skips all blanks, tabs, and end-ofline markers before returning the end-of-file status. This is useful when
reading numeric values from a text file.
.
With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it
returns a nonzero error code.

Restrictions
See also

Can be used only on text files. File must be open.

Eof, SeekEoln

SeekEoln function
Purpose
Declaration
Remarks

System

Returns the end-of-line status of a file.


function SeekEoln [ (var F: Text) l;

SeekEoln corresponds to Eoln except that it skips all blanks and tabs before
returning the end-of-line status. This is useful when reading numeric
values from a text file.
.

Chapter 7, Library reference

149

SeekEoln function

With {$I-}, IOResult returns 0 if the operation was successful; otherwise, it


returns a nonzero error code.
Restrictions
See also

Can be used only on text files. File must be open.

Eoln, SeekEof

Seg function
Purpose
Declaration

System
Returns the segment of a specified object.
function Seg (Xl: Word;

Remarks

X is any variable,or a procedure or function identifier. The result, of type


Word, is the segment part of the address of X.

See also

Addr,Ofs

Seg0040 variable
Purpose
Declaration

Selector for segment $0040.


var Seg0040: Word;

Remarks

Seg0040 contains a selector that can be used to access the ROM BIOS
workspace at segment address $0040. This variable is included for compatibility between DOS real and protected mode. In real mode Seg0040
always contains the value $0040, but in protected mode the actual value
can vary.

See also

SegAOOO, SegBOOO, SegBBOO

SegAOOO variable
Purpose
Declaration
Remarks

150

System

System

Selector for segment $AOOO.


var SegAO 00: Word;

SegAOOO contains a selector that can be used to access the EGA and VGA
graphics memory pages at segment address $AOOO. This variable is
included for compatibility between DOS real and protected mode. In

Programmer's Reference

SegAOOO variable

real mode SegAOOO always contains the value $AOOO, but in protected
mode the actual value can vary.
See also

Seg0040, SegBOOO, SegBBOO

System

Seg8000 variable
Purpose
Declaration

Selector for segment $BOOO.


var SegBOOO: Word;

Remarks

SegBOOO contains a selector that can be used to access the Monochrome


Adapter video memory at segment address $BOOO. This variable is
in<;luded for purposes of compatibility between DOS real and protected
mode. In real mode SegBOOO always contains the value $BOOO, but in
protected mode the actual value might vary.

See also

Seg0040, SegAOOO, SegBBOO

System

Seg8800 variable
Purpose
Declaration

Selector for segment $B800.


var SegB800: Word;

Remarks

SegBBOO contains a selector that can be used to access the Color Graphics
Adapter video memory at segment address $B800. This variable is
included for purposes of compatibility between DOS real and protected
mode. In real mode SegBBOO always contains the value $B800, but in
protected mode the actual value can vary.

See also

Seg~040,

SegAOOO, SegBOOO

Selectorlnc variable
Purpose
Declaration
Remarks

System

Selector increment value.


var Selectorlnc: Word;

Selectorlnc contains the value that must be added to or subtracted from the
selector part of a pointer to incrementor decrement the pointer by 64K
bytes. In real mode, Selectorlnc always contains $1000, but in protected
mode the actual value can vary.

Chapter 7, Library reference

151

SetActivePage procedure

Graph

SetActivePage procedure
Purpose
Declaration
Remarks

Set the active page for graphics output.


procedure SetActivePage (Page: Word);

Makes Page the active graphics page, directing all subsequent graphics
output to Page.
Multiple pages are supported only by the EGA (256K), VGA, and
Hercules graphics cards. With multiple graphics pages, a program can
direct graphics output to an off-screen page, then quickly display the offscreen image by changing the visual page with the SetVisualPage
procedure. This technique is especially useful for animation.

Restrictions

Must be in graphics mode.

See also

SetVisualPage

Example

uses Graph;
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);
if (Gd = HercMono) or (Gd = EGA) or (Gd = EGA64) or (Gd = VGA) then
begin
SetvisualPage(O);
SetActivePage(l);
Rectangle (10, 20, 30, 40);
SetVisualPage(l) ;
end
else
OutText('No paging supported.');
Readln;
CloseGraph;
end.

SetAIiPalette procedure
Purpose
Declaration

152

,Graph

Changes all palette colors as specified.


procedure SetAllPalette (var Palette) ;

Programmer's Reference

SetAIiPalette procedure

Remarks

Palette is an untyped parameter. The first byte is the length of the palette.
The next n bytes will replace the current palette colors. Each color might
range from -1 to 15. A value of -1 will not change the previous entry's
value.
Note that valid colors depend on the current graphics driver and current
, graphics mode.
If invalid input is passed to SetAllPalette, GraphResult returns a value of
-11 (grError), and no changes to the palette settings will occur.

Changes made to the palette are seen immediately onscreen. In the


example listed here, several lines are drawn onscreen, then the palette is
changed. Each time a palette color is changed, all onscreen occurrences of
that color will be changed to the new color value.
See Color constants for SetRGBPalette for a definition of color constants and
to PaletteType for a definition of PaletteType record.
Restrictions
See also
Example

Must be in graphics mode, and can be used only with EGA, EGA 64, or
VGA (not the IBM 8514 or the VGA in 256-color mode).

GetBkColor, GetColor, GetPalette, GraphResult, SetBkColor, SetColor,


SetPalette,SetRGBPalette
uses Graph;

var
Gd, Gm: Integer;
Palette: PaletteType;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;

Line(O, 0, GetMaxX, GetMaxY);


with Palette do
begin
Size := 4;
Colors [0] : = 5;
Colors [1] : = 3;
Colors[2] := 1;
Colors [3] : = 2;
SetAllPalette(Palette) ;
end;
Readln;
CloseGraph;
end.

Chapter 7, Library reference

153

SetAspectRatio procedure

SetAspectRatio procedure
Purpose
Declaration
Remarks

Restrictions

154

Graph

Changes the default aspect-ratio correction factor . .


procedure SetAspectRatio (Xasp, Yasp: Word): Word;

SetAspectRatio is used to change the default aspect ratio of the current


graphics mode. The aspect ratio is used to draw circles. If circles appear
elliptical, the monitor is not aligned properly. This can be corrected in the
hardware by realigning the monitor, or can be corrected in the software by
changing the aspect ratio using SetAspectRatio. To read the current aspect
ratio from the system, use GetAspectRatio.
Must be in graphics mode.

See also

GetAspectRatio

Example

uses Crt, Graph;


const R = 50;
var
Driver, Mode: Integer;
Xasp, Yasp: Word;
begin
DirectVideo := False;
{ Put in graphics mode }
Driver := Detect;
InitGraph(Driver, Mode, ");
if GraphResult < 0 then
Halt (1) ;
GetAspectRatio(Xasp, Yasp);
{ Get default aspect ratio }
if Xasp = Yasp then
{ Adjust for VGA and 8514. They have 1:1 aspect
Yasp := 5 * Xasp;
while (Xasp < Yasp) and not KeyPressed do
{ Keep modifying aspect ratio until 1:1 or key is pressed}
begin
SetAspectRatio(Xasp, Yasp);
Circle (GetMaxX div 2, GetMaxY div 2, R);
Inc(Xasp, 20);
end;
SetTextJustify(CenterText, CenterText);
OutTextXY(GetMaxX div 2, GetMaxY div 2, 'Donel');
Readln;
CloseGraph;
end.

Programmer's Reference

SetBkColor procedure

SetBkColor procedure
Purpose
Declaration
Remarks

Graph

Sets the current background color using the palette.


procedure SetBkColor (ColorNum: Word);

Background colors range from 0 to 15, depending on the current graphics


driver and current graphics mode. On a eGA, SetBkColor sets the flood
overscan color.

SetBkColor(N) makes the Nth color in the palette the new background
color. The only exception is SetBkColor(O), which always sets the
background color to black.
Restrictions

Must be in graphics mode.

See also

GetBkColor, GetColor, GetPalette, SetAllPalette, SetColor, SetPalette,


SetRGBPalette

Example

uses Crt Graph;


var
GraphDriver GraphMode: Integer;
Palette: PaletteType;
begin
GraphDriver := Detect;
InitGraph(GraphDriver GraphMode l II);
Randomize;
if GraphResult <> grOk then
Halt(l) ;
GetPalette(Palette);
repeat
if Palette. Size <> 1 then
SetBkColor(Random(Palette.Size)) ;
LineTo(Random(GetMaxX)/Random(GetMaxY));
until KeyPressed;
CloseGraph;
end.
l

SetCBreak procedure
Purpose
Declaration

I
Dos, WinDos

Sets the state of Ctrl+Break checking in DOS.


procedure SetCBreak(Break: Boolean);

Chapter 7, Library reference

155

-SetCBreak procedure

Remarks

SetCBreak sets the state of Ctrl+Break checking in DOS. When off (False),
DOS only checks for Ctrl+Break during I/O to console, printer, or communication devices. When on (True), checks are made at every system call.

See also

GetCBreak

Graph

SetColor procedure
Purpose
Declaration
Remarks

Sets the current drawing color using the palette.


procedure SetColor (Color: Word);

SetColor(S) makes the fifth color in the palette the current drawing color.
Drawing colors might range from 0 to IS, depending on the current
graphics driver and current graphics mode.
GetMaxColor returns the highest valid color for the current driver and
mode.

Restrictions

Must be in graphics mode.

See also

DrawPoly, GetBkColor, GetColor, GetMaxColor, GetPalette, GraphResult,


SetAllPalette, SetBkColor, SetPalette, SetRGBPalette

Example

uses Crt, Graph;


var
GraphDriver, GraphMode: Integer;
begin
GraphDriver := Detect;
InitGraph(GraphDriver, GraphMode, ");
if GraphResult <> grOk then
Halt (1);

Randomize;
repeat
SetColor(Random(GetMaxColor) + 1);
LineTo(Random(GetMaxX), Random(GetMaxY));
until KeyPressed;
end.

WinDos

SetCurDir procedure
Purpose
Declaration

156

Changes the current directory to the path specified by Dir.


procedure SetCurDir (Dir: PChar);

Programmer's Reference

SetCurDir procedure

Remarks

If Dir specifies a drive letter, the current drive is also changed. Errors are
reported in DosError.

See also

GetCurDir, CreateDir, RemoveDir. ChDir performs the same function as


SetCurDir, but it takes a Pascal-style string as the argument rather than a
null-terminated string.

SetDote procedure
Purpose
Declaration

Dos, WinDos

Sets the current date in the operating system.


procedure SetDate (Year, Month, Day: Word);

Remarks

Valid parameter ranges are Year 1980 .. 2099,Month 1..12, and Day 1..31. If
the date is invalid, the request is ignored.

See also

GetDate, GetTime, SetTime

SetFAttr procedure
Purpose
Declaration
Remarks

Dos, WinDos

Sets the attributes of a file.


procedure SetFAttr (var F; Attr: Word);

F must be a file variable (typed, untyped, or text file) that has been

assigned but not opened. The attribute value is formed by adding the
appropriate file attribute masks defined as constants in the Dos and
WinDos units. See page 43 for a list of file attribute constants.
Errors are reported in DosError; possible error codes are 3 (Invalid path)
and 5 (File access denied).
Restrictions

F cannot be open.

See also

File attribute, GetFAttr, GetFTime, SetFTime

Example

uses Dos;
var F: file;
begin
Assign(F, 'C:\AUTOEXEC.BAT');
SetFAttr(F, Hidden);
Readln;
SetFAttr(F, Archive);
end.

Chapter 7, Library reference

{ or WinDos }

{ or faHidden }
{ or faArchive }

157

SetFiliPattern procedure'

SetFiliPattern procedure
Purpose
Declaration
Remarks

Graph

Selects a user-defined fill pattern.


procedure SetFillPattern(Pattern: FillPatternType; Color: Word);

Sets the pattern and color for all filling done by FillPoly, FloodFill, Bar,
Bar3D, and PieS lice to the bit pattern specified in Pattern and the color
specified by Color. If invalid input is passed to SetFillPattern, GraphResult
returns a value of grError, and the current fill settings will be unchanged.
The fill pattern is based on the underlying Byte values contained in the
Pattern array. The pattern array is 8 bytes long with each byte corresponding to 8 pixels in the pattern. Whenever a bi~ in a pattern byte is
valued at I, a pixel will be plotted. For example, the following pattern
represents a checkerboard (50% gray scale):
Binary

Hex

10101010
01010101
10101010
01010101
10101010
01010101
10101010
01010101

$AA
$55
$AA
$55
$AA
$55
$AA
$55

(1st byte)
(2nd byte)
(3rd byte)
(4th byte)
(5th byte)
(6th byte)
(7th byte)
(8th byte)

User-defined fill patterns enable you to create patterns different from the
predefined fill patterns that can be selected with the SetFillStyle
procedure. Whenever you select a new fill pattern with SetFillPattern or
SetFillStyle, all fill operations will use that fill pattern. Calling SetFillStyle
(UserField, SomeColor) will always select the user-defined pattern. This lets
you define and use a new pattern using SetFillPattern, then switch
between your pattern and the built-ins by making calls to SetTextStyle.
Restrictions

158

Must be in graphics mode.

See also

Bar, Bar3D, FillPoly, GetFillPattern, GetFillSettings, GraphResult, grXXXX


constants, PieS lice

Example

uses Graph;
const
Gray50: FillPatternType
var Gd, Gm: Integer;

= ($AA, $55, $AA, $55, $AA, $55, $AA, $55);

Programmer's Reference

SetFiIIPaHern procedure

begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;
SetFillPattern(Gray50, White);
Bar (0, 0, 100, 100);
Readln;
CloseGraph;
end.

{ Draw a bar in a 50% gray scale }

SetFiliStyle procedure
Purpose
Declaration
Remarks

Restrictions

Graph

Sets the fill pattern and color.


procedure SetFillStyle(Pattern: Word; Color: Word);

Sets the pattern and color for all filling done by FillPoly, Bar, Bar3D, and
PieS lice. A variety of fill patterns are available. The default pattern is solid,
and the default color is the maximum color in the palette. If invalid input
is passed to SetFillStyle, GraphResult returns a value 'of grError, and the
current fill settings will be unchanged. If Pattern equals UserFill, the userdefined pattern (set by a call to SetFillPattern) becomes the active pattern.
See page 48 for the declaration of Fill pattern constants.
Must be in graphics mode.

See also

Bar, Bar3D, FillPattern, FillPoly, GetFillSettings, PieS lice, GetMaxColor,


GraphResult

Example

uses Graph;
var Gm, Gd: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
SetFillStyle(SolidFill, 0);
Bar (0, 0, 50, 50);
SetFillStyle(XHatchFill, 1);
Bar (60, 0, 11 0, 50);
Readln;
CloseGraph;
end.

Chapter 7, Library reference

159

SetFTime procedure

Dos, WinDos

SetFTime procedure
Purpose
Declaration
Remarks

Restrictions
See also

Sets the date and time a file was last written.


procedure SetFTime (var F; Time: Longint);

F must be a file variable (typed, untyped, or text file) that has been
assigned and opened. TheTime parameter can be created by calling
PackTime. Errors are reported in Dos Error; the only possible error code is 6
(Invalid file handle).
F must be open.

DosError, GetFTime, PackTime, SetFAttr, UnpackTime

Graph

SetGraphBufSize procedure
Purpose
Declaration
Remarks

Lets you change the size of the buffer used for scan and flood fills.
procedure SetGraphBufSize (BufSize: Word);

Sets the internal buffer size to BufSize, and allocates a buffer on the heap
when a call is made to InitGraph.
The default buffer size is 4K, which is large enough to fill a polygon with
about 650 vertices. Under rare circumstances, you might need to enlarge
the buffer in order to avoid a buffer overflow.

Restrictions
See also

Note that after InitGraph is called, calls to SetGraphBufSize are ignored.

FloodFill, FillPoly, InitGraph

Graph

SetGraphMode procedure
Purpose
Declaration
Remarks

Sets the system to graphics mode and clears the screen.


procedure SetGraphMode (Mode: Integer);

Mode must be a valid mode for the current device driver. SetGraphMode is
used to select a graphics mode different than the default one set by
InitGraph.
SetGraphMode can also be used in conjunction with RestoreCrtMode to
switch back and forth between text and graphics modes.
SetGraphMode resets all graphics settings to their defaults (current pointer,
palette, color, viewport, and so forth).

160

Programmer's Reference

GetModeRange returns the lowest and highest valid modes for the current
driver.
If an attempt is made to select an invalid mode for the current device

driver, GraphResult returns a value of grlnvalidMode.


See page 33, Drive and Mode constants, for a list of graphics drivers and
modes.
Restrictions

A successful call to InitGraph must have been made before calling this
routine.

See also

ClearDevice, CloseGraph, DetectGraph, Driver and Mode, GetGraphMode,


GetModeRange, GraphResult, InitGraph, RestoreCrtMode

Example

uses Graph;
var
GraphDriver: Integer;
GraphMode: Integer;
LowMode: Integer;
HighMode: Integer;
begin
GraphDriver := Detect;
InitGraph(GraphDriver , GraphMode , ");
if GraphResult <> grOk then
Halt (1) ;
GetModeRange(GraphDriver , LowMode , HighMode);
SetGraphMode(LowMode);
Line(O, 0, GetMaxX, GetMaxY);
Readln;
CloseGraph;
end.

{ Select low-resolution mode }

SetlntVec procedure
Purpose
Declaration
Remarks

Dos, WinDos

Sets a specified interrupt vector to a specified address.


procedure SetIntVec(IntNo: Byte; Vector: Pointer);

IntNo specifies the interrupt vector number (0 ..255), and Vector specifies
the address. Vector is often constructed with the @ operator to produce the
address of an interrupt procedure. Assuming Int1BSave is a variable of
type Pointer, and IntlBHandler is an interrupt procedure identifier, the
following statement sequence installs a new interrupt $1B handler and
later restores the original handler:

Chapter 7, Library reference

161

SetlntVec procedure

GetIntVec($lB, Int1BSave);
SetIntVec($lB, @Int1BHandler);
SetIntVec($lB, Int1BSave);

See also

GetIntVec

SetLineStyle procedure
Purpose
Declaration
Remarks

Restrictions

Graph

Sets the current line width and style.


procedure SetLineStyle (LineStyle: Word; Pattern: Word; Thickness: Word);

Affects all lines drawn by Line, LineTo, Rectangle, DrawPoly, Are, and so on.
Lines can be drawn solid, dotted, centerline, or dashed. If invalid input is
passed to SetLineStyle, GraphResult returns a value of grError, and the
current line settings will be unchanged. See Line style constants for a list of
constants used to determine line styles. LineStyle is a value from SolidLn to
UserBitLn(O ..4), Pattern is ignored unless LineStyle equals UserBitLn, and
Thickness is NormWidth or ThickWidth. When LineStyle equals UserBitLn,
the line is output using the 16-bit pattern defined by the Pattern
parameter. For example, if Pattern = $AAAA, then the 16-bit pattern looks
like this:
1010101010101010

{ NormWidth }

1010101010101019
1010101010101010
1010101010101010

{ ThickWidth }

Must be in graphics mode.

See also

DrawPoly, GetLineSettings, GraphResult, Line, LineRel, LineTo, Line style,


Set WriteMode

Example

uses Graph;
var

Gd, Gm: Integer;


Xl, Y1, X2, Y2: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;
Xl := 10;
Y1 := 10;

162

Programmer's Reference

SetLineStyle procedure

X2 := 200;
Y2 := 150;
SetLineStyle(DottedLn, 0, NormWidth);
Rectangle (Xl, Y1, X2, Y2);
SetLineStyle(UserBitLn, $C3, ThickWidth);
Rectangle (Pred(X1) , Pred(Y1), Succ(X2), Succ(Y2));
Readln;
CloseGraph;
end.

SetPalette procedure
Purpose
Declaration
Remarks

Graph

Changes one palette color as specified by ColorNum and Color.


procedure SetPalette (ColorNum: Word; Color: Shortint);

Changes the ColorNum entry in the palette to Color. SetPalette(O, LightCyan)


makes the first color in the palette light cyan. ColorNum might range from
oto 15, depending on the current graphics driver and current graphics
mode. If invalid input is passed to SetPalette, GraphResult returns a value
of grError, and the palette remains unchanged.
Changes made to the palette are seen immediately onscreen. In the
example here, several lines are drawn onscreen, then the palette is
changed randomly. Each time a palette color is changed, all occurrences of
that color onscreen will be changed to the new color value. See Color
constants for a list of defined color constants.

Restrictions

Must be in graphics mode, and can be used only with EGA, EGA 64, or
VGA (not the IBM 8514).

See also

GetBkColor, GetColor, GetPalette, GraphResult, SetAllPalette, SetBkColor,


SetColor, SetRGBPalette

Example

uses Crt, Graph;


var
GraphDriver, GraphMode: Integer;
Color: Word;
Palette: PaletteType;
begin
GraphDriver := Detect;
InitGraph(GraphDriver, GraphMode, ");
if GraphResult <> grOk then

Halt (1) ;

GetPalette(Palette) ;
if Palette. Size <> 1 then

Chapter 7, Library reference

163

SetPaleHe procedure

begin
for Color := 0 to Pred(Palette.Size) do
begin
SetColor(Color) ;
Line(O, Color * 5, 100, Color * 5);
end;
Randomize;
repeat
SetPalette(Random(Palette.Size),Random(Palette.Size));
until KeyPressed;
end
else
Line(O, 0, 100, 0);
Readln;
CloseGraph;
end.
i

Graph

SetRGBPalette procedure
Purpose
Declaration
Remarks

Modifies palette entries for the IBM 8514 and VGA drivers.
procedure SetRGBPalette(ColorNum, RedValue, GreenValue, BlueValue: Integer);

ColorNum defines the palette entry to be loaded, while RedValue,


GreenValue, and BlueValue define the component colors of the palette
entry.
For the IBM 8514 display, ColorNum is in the range 0.. 255. For the VGA in
256K color mode, ColorNum is the range 0..15. Only the lower byte of
RedValue, GreenValue or BlueValue is used, and out of this byte, only the 6
most-significant bits are loaded in the palette.
For compatibility with other IBM graphics adapters, the BGI driver
defines the first 16 palette entries of the IBM 8514 to the default colors of
the EGA/VGA. These values can be used as is, or they can be changed by
using SetRGBPalette.

Restrictions

164

SetRGBPalette can be used only with the IBM 8514 driver and the VGA.

See also

GetBkColor, GetColor, GetPalette, GraphResult, SetAllPalette, SetBkColor,


SetColor, SetPalette

Example

The first example illustrates how to use SetRGBPalette on a system using


an EGA graphics driver; the second example shows how to use
SetRGBPalette on a system using a VGA graphics driver.

Programmer's Reference

SetRGBPalette procedure

Example 1:
uses Graph;
type
RGBRec = record
RedVal, GreenVal, BlueVal: Integer;
end;
const
EGAColors: array[O .. MaxColors] of RGBRec =
(
{NAME
(RedVal:$OO;GreenVal:$OO;BlueVal:$OO) ,{Black
(RedVal:$OO;GreenVal:$OO;BlueVal:$FC) ,{Blue
(RedVal:$24;GreenVal:$FC;BlueVal:$24) ,{Green
(RedVal:$OO;GreenVal:$FC;BlueVal:$FC) ,{Cyan
(RedVal:$FC;GreenVal:$14;BlueVal:$14) ,{Red
(RedVal:$BO;GreenVal:$OO;BlueVal:$FC) ,{Magenta
(RedVal:$70;GreenVal:$48;BlueVal:$00) ,{Brown
(RedVal:$C4;GreenVal:$C4;BlueVal:$C4) ,{White
(RedVal:$34;GreenVal:$34;BlueVal:$34) ,{Gray
(RedVal:$00;GreenVal:$00;BlueVal:$70},{Lt Blue
(RedVal:$00;GreenVal:$70;BlueVal:$00},{Lt Green
(RedVal:$00;GreenVal:$70;BlueVal:$70},{Lt Cyan
(RedVal:$70;GreenVal:$00;BlueVal:$00},{Lt Red
(RedVal:$70;GreenVal:$00;BlueVal:$70},{Lt Magenta
(RedVal:$FC;GreenVal:$FC;BlueVal:$24) , {Yellow
(RedVal;$FC;GreenVal:$FC;BlueVal:$FC) {Br. White

COLOR}
EGA O}
EGA 1}
EGA 2}
EGA 3}
EGA 4}
EGA 5}
EGA 20}
EGA 7}
EGA 56}
EGA 57}
EGA 58}
EGA 59}
EGA 60}
EGA 61}
EGA 62}
EGA 63}

};

var
Driver, Mode, I: Integer;
begin
Driver := IBM8514;
Mode := IBM8514Hi;
InitGraph(Driver, Mode, "};
if GraphResult < 0 then
Halt(l} ;
{ Zero palette, make all graphics output invisible
for I := 0 to MaxColors do
with EGAColors[I] do
SetRGBPalette(I, 0, 0, O};
{ Display something }
{ Change first 16 8514 palette entries
for I := 1 to MaxColors do
begin
SetColor(I} ;
OutTextXY(lO, I * 10, ' .. Press any key .. '};
end;

Chapter 7, Library reference

{ Override detection
Put in graphics mode

165

SetRGBPaleHe procedure

{ Restore default EGA colors to 8514 palette }


for I := 0 to MaxColors do
with EGAColors[I] do
SetRGBPalette (I, RedVal, GreenVal, BlueVall i
Readlni
CloseGraphi.
end.

Example 2:
{ Example for SetRGBPalette with VGA 16 color modes }
uses Graph, CRTi
type
RGBRec = record
RedVal, GreenVal, BlueVal : Integeri
{ Intensity values (values from 0 to 63) }
Name: Stringi
ColorNum: Integeri
{ The VGA color palette number as mapped into 16 color palette }
endi
const
{ Table of suggested colors forVGA 16 color modes }
Colors : array[O . . MaxColors] of RGBRec = (
( RedVal:OiGreenVal:OiBlueVal:OiName:'Black'iColorNum: 0),
( RedVal:OiGreenVal:OiBlueVal:40iName:'Blue'iColorNum: 1),
( RedVal:OiGreenVal:40iBlueVal:OiName:'Green' iColorNum: 2),
( RedVal:OiGreenVal:40iBlueVal:40iName:'Cyan' iColorNum: 3),
( RedVal:40iGreenVal:7iBlueVal:7iName: 'Red' iColorNum: 4),
( RedVal:40iGreenVal:OiBlueVal:40iName:'Magenta'iColorNum: 5),
( RedVal:40iGreenVal:30i BlueVal:OiName: 'Brown' iColorNum: 20),
( RedVal:49iGreenVal:49iBlueVal:49iName: 'Light Gray'iColorNum: 7),
( RedVal:26iGreenVal:26iBlueVal:26iName: 'Dark Gray'iColorNum: 56),
( RedVal:OiGreenVal:OiBlueVal:63iName:'Light Blue'iColorNum: 57),
( RedVal:9iGreenVal:63iBlueVal:9iName:'Light Green'iColorNum: 58),
( RedVal:OiGreenVal:63iBlueVal:63iName:'Light Cyan'iColorNum: 59),
( RedVal:63iGreenVal:10iBlueVal:10iName:'Light Red'iColorNum: 60),
( RedVal:44iGreenVal:OiBlueVal:63iName:'Light Magenta'i
ColorNum:61) ,
( RedVal:63iGreenVal:63iBlueVal:18iName:'Yellow'iColorNum: 62),
( RedVal:63i GreenVal:63i BlueVal:63i Name: 'White'i ColorNum: 63)
)i

var
Driver, Mode, I, Error: Integeri
begin
{ Initialize Graphics Mode
Driver := VGAi
Mode := VGAHii

166

Programmer's Reference

SetRGBPaleHe procedure

1nitGraph(Driver, Mode, 'C:\TP\BG1');


Error := GraphResult;
if Error <> GrOk then
begin
writeln(GraphErrorMsg(Error));
halt (1) ;
end;
SetFillStyle(SolidFill, Green);
{Clear}
Bar(O, 0, GetMaxX, GetMaxY);
if GraphResult < 0 then
Halt(l);
{ Zero palette, make graphics invisible}
SetRGBPalette(Colors[O] .ColorNum, 63, 63, 63)i
for i := 1 to 15 do
with Colors[i] do
SetRGBPalette(ColorNum, 0, 0, 0);
{ Display the color name using its color with an appropriate
background }
{ Notice how with the current palette settings, only the text
key ... ", "Black", "Light Gray", and "White" are visible. This
the palette entry for color 0 (Black) has been set to display
the text "Light Gray" and "White," color 0 (Black) is used at
SetColor(O);
OutTextXY(O, 10, 'Press Any Key ... ');
for I := 0 to 15 do
begin
with Colors[1] do
begin
SetColor(1);
SetFillStyle(SolidFill, (I xor 15) and 7) i
. { "(I xor 15)" gives an appropriate background}
{ " and 7" reduces the intensity of the background}

for "Press any


occurs because
as white. For
the background.}

Bar(10, (I + 2) * 10 - 1, 10 + TextWidth(Name) ,
(I + 2) * 10 + TextHeight(Name) - 1);
OutTextXY(10, (I + 2) * 10, Name);
end;

end;
ReadKey;
{ Restore original colors to the palette. The default colors might vary
depending upon the initial values used by your video system.}
for i := 0 to 15 do
with Colors[i] do
SetRGBPalette(ColorNum, RedVal, GreenVal, BlueVal);
{ Wait for a keypress and then quit graphics and end. }
ReadKey;
Closegraphi
end.

Chapter 7, Library reference

167

SetTextBuf procedure

SetTextBuf procedure
Purpose
Declaration
Remarks

System

Assigns an I/O buffer to a text file.


procedure SetTextBuf (var F: Text; var Buf [ ; Size: Word ] );

F is a text file variable, Buf is any variable, and Size is an optional


expression of type Word.
Each text file variable has an internal 128-byte buffer that, by default, is
used to buffer Read and Write operations. This buffer is adequate for most
applications. However, heavily I/O-bound programs, such as applications
that copy or convert text files, benefit from a larger buffer because it
reduces disk head movement and file system overhead.

SctTextBuf changes the text file F to use the buffer specified by Buf instead
of F's internal buffer. Size specifies the size of the buffer in bytes. If Size is .
omitted, SizeOf(Buj) is assumed; that is, by default, the entire memory
region occupied by Buf is used as a buffer. The new buffer remains in
effect until F is next passed to Assign.
Restrictions

SetTextBuf should never be applied to an open file, although it can be


called immediately after Reset, Rewrite, and Append. Calling SetTextBuf on
an open file once I/O operations has taken place can cause loss of data
because of the change of buffer.
Turbo Pascal doesn't ensure that the buffer exists for the entire duration of
I/O operations on the file. In particular, a common error is to install a
local variable as a buffer, then use the file outside the procedure that
declared the buffer.

Example

var

F: Text;
Ch: Char;
Buf: array [ 0.. 4095] of Char;

{ 4K buffer }

begin

{ Get file to read from command line }


Assign(F, ParamStr(l));
{ Bigger buffer for faster reads }
'SetTextBuf(F, Buf);
Reset (F) ;
{ Dump text file onto screen }
while not Eof(f) do
begin

Read (F, Ch);


Write (Ch) ;
end;
end.

168

Programmer's Reference

SetTextJustify procedure

SetTextJustify procedure
Purpose
Declaration
Remarks

Graph

Sets text justification values used by OutText and OutTextXY.


procedure SetTextJustify(Horiz, Vert: Word);

Text output after a setTextJustify will be justified around the current


pointer in the manner specified. Given the following:
SetTextJustify(CenterText, CenterText);
OutTextXY(100, 100, 'ABC');

The point (100, 100) will appear in the middle of the letter B. The default
justification settings can be restored by setTextfustify(LeftText, TopText). If
invalid input is passed to setTextfustify, GraphResult returns a value of
grError, and the current text justification settings will be unchanged. See
page 99 for a list of Justification constants.
Restrictions

Must be in graphics mode.

See also

GetTextsettings, GraphResult, Justification, OutText, OutTextXY, setLinestyle,


setUserCharsize, TextHeight, TextWidth

Example

uses Graph;
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;
{ Center text onscreen }
SetTextJustify(CenterText, CenterText);
OutTextXY(Succ(GetMaxX) div 2, Succ(GetMaxY) div 2, 'Easily Centered');
Readln;
CloseGraph;
end.

SetTextStyle procedure
Purpose
Declaration
Remar.ks

Graph

Sets the current text font, style, and character magnification factor.
procedure SetTextStyle(Font: Word; Direction: Word; CharSize: Word);

Affects all text output by OutText and OutTextXY. One 8x8 bit-mapped
font and several stroked fonts are available. Font directions supported
are normal (left to right) and vertical (90 degrees to normal text, starts at
the bottom and goes up). The size of each character can be magnified
using the Char Size factor. A Charsize value of one will display the 8x8 bit-

Chapter 7, Library reference

169

SetTextStyle procedure

mapped font in an 8x8 pixel rectangle onscreen, a CharSize value equal to


2 will display the 8x8 bit-mapped font in a 16x16 pixel rectangle arid so on
(up to a limit of 10 times the normal size). Always use TextHeight and
TextWidth to determine the actual dimensions of the text.
The normal size values for text are 1 for the default font and 4 for a
stroked font. These are the values that should be passed as the CharSize
parameter to SetTextStyle. SetUserCharSize can be used to customize the dimensions of stroked font text.
Normally, stroked fonts are loaded from disk onto the heap when a call is
made to SetTextStyle. However, you can load the fonts yourself or link
them directly to your .EXE file. In either case, use RegisterBGlfont to
register the font with the Graph unit.
When stroked fonts are loaded from disk, errors can occur when trying to
load them. If an error occurs, GraphResult returns one of the following
values: grFontNotFound, grNoFontMem, grError, grIOError, grlnvalidFont, or -

grlnvalidFontNum.
Restrictions

170

Must be in graphics mode.

See also

Font control, GetTextS~ttings, GraphResult, OutText, OutTextXY,


RegisterBGlfont, SetTextJustify, SetUserCharSize, TextHeight, TextWidth

Example

uses Graph;
var
Gd,Gm: Integer;
Y, Size: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, II);
if GraphResult <> grOk then
Halt (1) ;
Y := 0;
for Size := 1 to 4 do
begin
SetTextStyle(DefaultFont, HorizDir, Size);
OutTextXY(O, Y, 'Size = ' + Chr(Size + 48));
Inc(Y, TextHeight('H') + 1);
end;
Readln;
CloseGraphi
end.

Programmer's Reference

SetTime procedure

SetTime" procedure
Purpose
Declaration

Dos, WinDos

Sets the current time in the operating system.


procedure SetTime (Hour, Minute, Second, Sec100: Word);

Remarks

Valid ranges are Hour 0.. 23, Minute 0..59, Second 0..59, and Sec100
(hundredths of seconds) 0.. 99. If the time isn't valid, the request is ignored.

See also

GetDate, GetTime, PackTime, SetDate, UnpackTime

SetUserCharSize procedure
Purpose
Declaration
Remarks

Restrictions

Graph

Allows the user to vary the character width and height for stroked fonts.
procedure SetuserCharSize(MultX, Divx, MultY, DivY: Word;)

MultX:DivX is the ratio multiplied by the normal width for the active font;
MultY:DivY is the ratio multiplied by the normal height for the active font.
In order to make text twice as wide, for example, use a MultX value of 2,
and set DivX equal to 1 (2 div 1 = 2). Calling SetUserCharSize sets the
current character size to the specified values.
Must be in graphics mode.

See also

SetTextStyle, OutText, OutTextXY, TextHeight, TextWidth

Example

The following program shows how to change the height and width of text:
uses Graph;
var Driver, Mode: Integer;
begin
Driver := Detect;
InitGraph(Driver, Mode, ");
if GraphResult <> grOk then
Halt (1) ;
{ Showoff }
SetTextStyle(TriplexFont, HorizDir, 4);
OutText ('Norm') ;
SetUserCharSize(l, 3, 1, 1);
OutText('Short ');
SetUserCharSize(3, 1, 1, 1);
OutText ('Wide');
Readln;
CloseGraph;
end.

Chapter 7, Library reference

171

SetVerify procedure

Dos, WinDos

SetVerify procedure
Purpose
Declaration

Sets the state of the verify flag in DOS.


procedure SetVerify(Verify: Boolean);

Remarks

Set Verify sets the state of the verify flag in DOS. When off (False), disk
writes are not verified. When on (True), DOS verifies all disk writes to
ensure proper writing.

See also

Get Verify

.SetViewPort procedure
Purpose
Declaration
Remarks

Graph

Sets the current ,?utput viewport or window for graphics output.


procedure SetViewPort(X1, Y1, X2, Y2: Integer; Clip: Boolean); .

(Xl, Yl) define the upper left corner of the viewport, and (X2, Y2) define
the lower right corner (0 <= Xl < X2and 0 <= Yl < Y2). The upper left
corner of a viewport is (0,0).
The Boolean parameter Clip determines whether drawings are clipped at
the current viewport boundaries. setViewPort(O, 0, GetMaxX, GetMaxY,
True) always sets the viewport to the entire graphics screen. If invalid
input is passed to Set ViewPort, GraphResult returns grError, and the
current view settings will be unchanged.
All graphics commands (for example, GetX, OutText, Rectangle, MoveTo,
and so on) are viewport-relative. In the following example, the
coordinates of the dot in the middle are relative to the boundaries of the
viewport.
(0,0)

(GetMaxX,O)
(X1,Y1)

(X2,Y1)

(X1,Y2)
(O,GetMaxY)

(X2,Y2)
(GetMaxX,GetMaxY)

If the Boolean parameter Clip is set to True when a call to setViewPort is


made, all drawings will be clipped to the current viewport. Note that the

172

Programmer's Reference

SetViewPort procedure

"current pointer" is never clipped. The following will not draw the
complete line requested because the line will be clipped to the current
viewport:
SetViewPort(10, 10, 20, 20, ClipOn);
Line(O, 5, 15, 5);

The line would start at absolute coordinates (10,15) and terminate at


absolute coordinates (25, 15) if no clipping was performed. But since
clipping was performed, the actual line that would be drawn would start
at absolute coordinates (10, 15) and terminate at coordinates (20, 15).

InitGraph, GraphDefaults, and SetGraphMode all reset the viewport to the


entire graphics screen. The current viewport settings are available by
calling the procedure GetViewsettings, which accepts a parameter of
ViewPort Type.
Set ViewPort moves the current pointer to (0,0).
Restrictions

Must be in graphics mode.

See also

ClearViewPort, GetViewsettings, GraphResult

Example

uses Graph;
var Gd, Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;
if (Gd = HercMono) or (Gd = EGA) or (Gd
begin
SetVisualPage(O);
SetActivePa~e(l) ;
Rectangle(10, 20, 30, 40) i
SetvisualPage(l);
end
else
OutText('No paging supported.');
Readlni
CloseGraph;
end.

SetVisualPage procedure
Purpose
Declaration

= EGA64)

or (Gd

= VGA)

then

I
Graph

Sets the visual graphics page number.


procedure SetVisualPage (Page: Word);

Chapter 7, Library reference

173

SefVisualPage procedure

Remarks

Makes Page the visual graphics page.


Multiple pages are only supported by the EGA (256K), VGA, and
Hercules graphics cards. With multiple graphics pages, a program can
direct graphics output to an off-screen page, then quickly display the offscreen image by changing the visual page with the Set VisualPage
procedure. This technique is especially useful for animation.

Restrictions

Must be in graphics mode.

See also

SetActivePage

Example

uses Graph;
var Gd,Gm: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, If);
if GraphResult <> grOk then
Halt(l) ;
if (Gd = HercMono) or (Gd = EGA) or (Gd
begin
SetVisualPage(O);
SetActivePage(l);
Rectangle (10, 20, 30, 40);
SetVisualPage(l);
end
else
OutText('No paging supported.');
Readln;
CloseGraph;
end.

= EGA64) or (Gd = VGA) then

SetWriteMode procedure
Purpose

Sets the writing mode for line drawing.

Declaration

procedure SetWriteMode (WriteMode: Integer);

Remarks

174

Graph

See page 12 for a list of BitBlt operators used by SetWriteMode. Each


constant corresponds to a binary operation between each byte in the line
and the corresponding bytes on the screen. CopyPut uses the assembly
language MOV instruction, overwriting with the line whatever is on the
screen. XORPut uses the XOR command to combine the line with the
screen. Two successive XOR commands will erase the line and restore the
screen to its original appearance.

Programmer's Reference

SetWriteMode procedure

SetWriteMode affects calls only to the following routines: DrawPoly, Line,


LineRel, Line To, and Rectangle.
See also

BitBlt operators, Line, LineTo, PutImage, SetLineStyle

Example

uses Crt, Graph;


var
Driver, Mode, I: Integer;
Xl, Y1, Dx, Dy: Integer;
FillInfo: FillSettingsType;
begin
DirectVideo := False;
Randomize;
Driver := Detect;
InitGraph(Driver, Mode, ");
if GraphResult < 0 then

{ Turn off screen write


{ Put in graphics mode

Halt (1) ;

{ Fill screen with background'pattern


GetFillSettings(FillInfo);
{ Get current settings }
SetFillStyle(WideDotFill, FillInfo.Color)i
Bar(O, 0, GetMaxX, GetMaxY);
Dx := GetMaxX div 4;
{ Determine rectangle's dimensions}
Dy := GetMaxY div 4;
SetLineStyle(SolidLn, 0, ThickWidth);
{ XOR mode for rectangle }
SetWriteMode(XORPut);
repeat
Draw until a key is pressed }
Xl := Random(GetMaxX - Dx);
Y1 := Random(GetMaxY - Dy);
Rectangle (Xl, Y1, Xl + Dx, Y1 + Dy);
{ Draw it }
Pause briefly }
Delay(10) ;
Rectangle (Xl, Y1, Xl + Dx, Y1 + Dy);
{ Erase it }
until KeyPressed;
Readln;
CloseGraph;
end.

Sin function
Purpose
Declaration

,System
Returns the sine of the argument.
function Sin (X: Real): Real;

Remarks

X is a real-type expression. Returns the sine of the angle X in radians.

See also

ArcTan, Cos

Chapter 7, Library reference

175

Example

var R: Real i
begin
R := Sin(pi)
end.

System

SizeOf function
Purpose
Declaration
RSmarks

Returns the number of bytes occupied by the argument.


function SizeOf (X): Wordi

X is either a variable reference or a type identifier. SizeO! returns the


number of bytes of memory occupied by X.

SizeO! should always be used when passing values to FillChar, Move,


GetMem, and so on:
FillChar(S, SizeOf(S), O)i
GetMem(P, SizeOf(RecordType))i

Example

type
CustRec = record
Name: string[30]i
phone: string[14] i
endi
var P: ACustReci
begin
GetMem(P, SizeOf(CustRec))i
end.

Crt

Sound procedure
Purpose
Declaration

176

Starts the internal speaker.


procedure Sound (Hz: Word)

Remarks

Hz specifies the frequency of the emitted sound in hertz. The speaker


continues until explicitly turned off by a call to NoSound.

See also

NoSound

Example

uses Crt i
begin
Sound (220) i
Delay(200) i
NoSoundi
end.

Programmer's Reference

SPtr function

SPtr function
Purpose
Declaration

System
Returns the current value of the SP register.
function SPtr: Word;

Remarks

Returns the offset of the stack pointer within the stack segment.

See also

SSeg

Sqr function
Purpose
Declaration
Result type
Remarks

System
Returns the square of the argument.
function Sqr (Xl;

Same type as parameter.


X is an integer-type or real-type expression. The result, of the same type
as X, is the square of X, or X*X.

Sqrt function
Purpose
Declaration
Remarks

System
Returns the square root of the argument.
function Sqrt (X: Real l: Real;

X is areal-type expression. The result is the square root of X.

SSeg function
Purpose
Declaration

System

function SSeg: Word;

Remarks

The result, of type Word, is the segment address of the stack segment.

See also

SPtr, CSeg, DSeg

StackLimit variable
Purpose
Declaration

Returns the current value of the SS register.

System

Contains the offset of the bottom of the stack in the stack segment.
var StackLimit: Word;

Chapter 7, Library reference

177

StackLimit variable

Remarks

StackLimit returns the lowest value the SP register can contain before it is
considered a stack overflow.

See also

SPtr

Str procedure
Purpose
Declaration

System
Converts a numeric value to its string representation.
procedure Str (X [: Width [: Decimals ] ]; var S);

Remarks

X is an integer-type or real-type expression. Width and Decimals are


integer-type expressions. S is a string-type variable or a zero-based
character array variable if extended syntax is enabled. Str converts X to its
string representation, according to the Width and Decimals formatting
parameters. The effect is exactly the same as a call to the Write standard
procedure with the same parameters, except that the resulting string is
stored in S instead of being written to a text file.

See also

Val, Write

Example

function IntToStr (I: Longint): String;


{ Convert any integer type to a string }
var s: string [11] ;
begin
Str(I, S);
IntToStr := S;
end;
begin
Writeln(IntToStr(-5322));
end.

Streat function
Purpose
Declaration

178

Strings

Appends a copy of one string to the end of another and returns the
concatenated string.
function StrCat (Dest, Source: PChar): PChar;

Remarks

StrCat appends a copy of Source to Dest and returns Dest. StrCat does not
perform any length checking. You must ensure that the buffer given by
Dest has room for at least StrLen(Dest) + StrLen(Source) + 1 characters. If
you want length checking, use the StrLCat function.

See also

StrLCat

Programmer's Reference

Streat function

Example

uses Strings;
const
Turbo: PChar = 'Turbo';
Pascal: PChar = 'Pascal';
var
S: array[O .. 15] of Char;
begin
StrCopy(S, Turbo);
StrCat(S, ' ');
StrCat(S, Pascal);
Writeln(S) ;
end.

StrComp function
Purpose
Declaration
Remarks

Compares two strings.


function StrComp (Str1, Str2: PChar): Integer;

,StrComp compares Strl to Str2. The return value is less than a if


Strl < Str2, a if Strl = Str2, or greater than a if Strl > Str2.

See also

StrIComp, StrLComp, StrLIComp

Example

uses Strings;
var
C: Integer;
Result: PChar;
Sl, S2: array[O .. 79] of Char;
begin
Readln(Sl) ;
Readln(S2) ;
C := StrComp(Sl, S2);
if C < 0 then Result := ' is less than ' else
if C > 0 then Result := ' is greater than' else
Result := 'is equal to ';
Writeln(Sl, Result, S2);
end.

StrCopy function
Purpose
Declaration

Strings

I
Strings

Copies one string to another.


function StrCopy(Dest, Source: PChar): PChar;

t'

Chapter 7~' Library reference

179

5trCopy function

Remarks

StrCopy copies Source to Dest and returns Dest. StrCopy does not perform
any length checking. You must ensure that the buffer given by Dest has
room for at least StrLen(Source) + 1 characters. If you want length
checking, use the StrLCopy fUhction.

See also

StrECopy, StrLCopy

Example

uses Strings;
var
S: array [0 .. 15) of. Char;
begin
StrCopy(S, 'Turbo Pascal');
Writeln (S) ;
end.

StrDispose function
Purpose
Declaration

Strings

Disposes of a string on the heap.


function StrDispose (Str: PChar);

Remarks

StrDispose disposes of a string that was previously allocated with StrNew.


If Str is nil, StrDispose does nothing.

See also

StrNew

StrECopy function
Purpose
Declaration

180

Strings

Copies one string to another, returning a pointer to the end of the


resulting string.
function StrECopy(Dest, Source: PChar): PChar;

Remarks

StrECopy copies Source to Dest and returns StrEnd(Dest). You must ensure
that the buffer given by Dest has room for at least StrLen(Source) + 1
characters. Nested calls to StrECopy can be used to concatenate a sequence
of strings-this is illustrated by the example that follows.

See also

StrCopy, StrEnd

Example

uses Strings;
const
Turbo: PChar = 'Turbo';
Pascal: PChar = 'Pascal';
var
S: array[O .. 15) of Char;

Programmer's Reference

5trECopy function

begin
StrECopy(StrECopy(StrECopy(S, Turbo), ' '), Pascal);
Writeln(S) ;
end.

StrEnd function
Purpose
Declaration

Strings

Returns a pointer to the end of a string.


function StrEnd(Str: PChar): PChar;

Remarks

StrEnd returns a pointer to the null character that terminates Str.

See also

Str Len

Example

uses Strings;
var
S: array[O .. 79] of Char;
begin
Readln(S);
Writeln('String length is'
end.

StrEnd(S) - S);

StrlComp function
Purpose
Declaration

Strings

Compares two strings without case sensitivity.


function StrIComp (Strl, Str2: PChar): Integer;

Remarks

StrIComp compares Strl to Str2 without case sensitivity. The return value
is the same as StrComp.

See also

StrComp, StrLComp, StrLIComp

StrLCat function
Purpose
Declaration

Strings

Appends characters from a string to the end of another, and returns the
concatenated string.
function StrLCat (Dest, Source: PChar; MaxLen: Word): PChar;

Chapter 7, Library reference

181

StrLCat function

Remarks

StrLCat appends at most MaxLen - StrLen(Dest) characters from Source to


the end of Dest, and returns Dest. The SizeD! standard function can be
used to determine the MaxLen parameter.

See also

StrCat

Example

uses Strings;
var
S: array[O .. 9] of Char;
begin
StrLCopy(S, 'Turbo', SizeOf(S) - 1)
StrLCat(S, ' " SizeOf(S) - 1);
StrLCat(S, 'Pascal', SizeOf(S) - 1);
Writeln(S) ;
end.

StrLComp function
Purpose
Declaration

Strings

Compares two strings, up to a maximum length.


function StrLComp (Str1, Str2: PChar; MaxLen: Word): Integer;

Remarks

StrLComp compares Strl to Str2, up to a maximum length of MaxLen


characters. Theretum value is the same as StrComp.

'See also

StrComp, StrLIComp, StrIComp

Example

uses Strings;
var
Result: PChar;
Sl, S2: array[O .. 79] of Char;
begin
Readln(Sl);
Readln (S2 ) ;
if StrLComp(Sl, S2, 5) = 0 then
Result .- 'equal'
else
Result .- 'different';
Writeln('The first five characters are'
end.

Result);

StrLCopy function
Purpose
Declaration

182

Strings

Copies characters fr6m one string to another.


function StrLCopy(Dest, Source: PChar; MaxLen: Word): PChar;

Programmer's Reference

StrLCopy function

Remarks

StrLCopy copies at most MaxLen characters from Source to Dest and returns
Dest. The SizeO! standard function can be used to determine the MaxLen
parameter-this is demonstrated by the example that follows.

See also

StrCopy

Example

uses Strings;

var
S: array[O .. 9] of Char;
begin
StrLCopy(S, 'Turbo Pascal', SizeOf(S) - 1);
Writeln(S) ;
end.

StrLen function
Purpose
Declaration

Strings

Returns the number of characters in Str.


function StrLen(Str: PChar): Word;

Remarks

StrLen returns the number of characters in Str, not counting the null
terminator.

See also

StrEnd

Example

uses Strings;

var
S: array[O .. 79] of Char;
begin
Readln(S) ;
Writeln('St:dng length is'
end.

StrLen(S));

_St_rL_I_C_o_m~p__fu_n_c_t_io_n____________________________~____St_r_in_g_s
Purpose
Declaration

Compares two strings, up to a maximum length, without case sensitivity.


function StrLIComp (Strl, Str2: PChar; MaxLen: Word): Integer;

Remarks

StrLIComp compares Strl to Str2, up to a maximum length -of MaxLen


characters, without case sensitivity. The return value is the same as
StrComp.

See also

StrComp, StrIComp, StrLComp

Chapter 7, Library reference

183

III

5trLower function

Strings

StrLower function
Purpose
Declaration

Converts a string to lowercase.


function StrLower(Str: PChar): PChar;

Remarks

StrLower converts Str to lowercase and returns Str.

See also

StrUpper

Example

uses Strings;
var
S: array[0 .. 79] of Char;
begin
Readln(S);
Writeln(StrLower(S));
Writeln(StrUpper(S));
end.

StrMove function
Purpose
Declaration

184

Strings

Copies characters from one string to another.


function StrMove(Dest, Source: PChar; Count: Word): PChar;

Remarks

StrMove copies exactly Count characters from Source to Dest and returns
Dest. Source and Dest can overlap.

Example

function StrNew(S: PChar): PChari


{ Allocate string on heap }
var.,
L: Word;
P: PChar;
begin
if (S = nil) or (SA = #0) then StrNew :~ nil else
begin
L := StrLen(S) + 1;
GetMem(P, L);
StrNew := StrMove(P, S, L);
end;
end;
procedure StrDispose(S: PChar);
{ Dispose of string on heap }
begin
if S <> nil then FreeMem(S, StrLen(S) + 1);
end;

Programmer's Reference

StrNew function

StrNew function
Purpose
Declaration

Strings

Allocates a string on the heap.


function StrNew(Str: PChar): PChar;

Remarks

StrNew allocates a copy of Str on the heap. If Str is nil or points to an


empty string, StrNew returns nil and doesn't allocate any heap space.
Otherwise, StrNew makes a duplicate of Str, obtaining space with a call to
the GetMem standard procedure, and returns a pointer to the duplicated
string. The allocated space is StrLen(Str) + 1 bytes long.

See also

StrDispose

Example

uses Strings;
var
P: PChar;
S: array[O .. 79] of Char;
begin
Readln(S) ;
P : = StrNew(S);
Writeln (P) ;
StrDispose(P);
end.

StrPas function
Purpose
Declaration

Strings

Converts a null-terminated string to a Pascal-style string.


function StrPas (Str: PChar): String;

Remarks

StrPas converts Str to a Pascal-style string.

See also

StrPCopy

Example

uses Strings;
var
A: array[O .. 79] of Char;
S: string [79] ;
begin
Readln (A) ;
S : = StrPas (A); _
Writeln(S);
end.

Chapter 7, Library reference

185

StrPCopy function

StrPCopy function
Purpose
Declaration

Strings

Copies a Pascal-style stri1::,-g into a null-terminated string.


function StrPCopy(Dest:

PChari

Source: String):

PChari

Remarks . StrPCopy copies the Pascal-style string Source into Dest and returns Dest.

You must ensure that the buffer given by Dest has room for at least
. Length(Source) + 1 characters.
See also

StrCopy

Example

uses Strings i
var
A: array[O .. 79] of
S: string[79] i
begin
Readln(S) i
StrPCopy(A, S) i
Writeln (A) i
end.

Chari

StrPos function
Purpose
Declaration

186

Strings

Returns a pointer to the first occurrence of a string in another string.


function StrPos (Strl, Str2: PChar):

PChari

Remarks

StrPos rehlrns a pointer to the first occurrence of Str2 in Strl. If Str2 does
not occur in Strl, StrPos returns nil.

Example

uses Strings i
var
P: PChari
S, SubStr: array[O .. 79] of Chari
begin
Readln(S)i
Readln(SubStr)i
P := StrPos(S, SubStr)i
if P = nil then
Writeln('Substring not found')i
else
Writeln('Substring found at index', P - S)i
end.

Programmer's Reference

StrRScan function

StrRScan function
Purpose
Declaration

Strings

Returns a pointer to the last occurrence of a character in a string.


function StrRScan(Str: PChar; Chr: Char}: PChar;

Remarks

StrRScan returns a pointer to the last occurrence of Chr in Str. If Chr does
not occur in Str, StrRScan returns nil. The null terminator is considered to
be part of the string.

See also

StrScan

Example

{Return pointer to name part of a full path name


function NamePart(FileName: PChar}: PChar;
var
P: PChar;
begin
P := StrRScan(FileName, '\'};
if P = nil then
begin
P := StrRScan(FileName, , :'};
if P = nil then P := FileName;
end;
NamePart : = P;
end;

StrScan function
Purpose
Declaration

Strings

Returns a pointer to the first occurrence of a character in a string.


function StrScan(Str: PChar; Chr: Char}: PChar;

Remarks

StrScan returns a pointer to the first occurrence of Chr in Str.1f Chr does
not occur in Str, StrScan returns nil. The null terminator is considered to
be part of the string.

See also

StrRScan

Example

{Return True if file name has wildcards in it


function HasWildcards(FileName: PChar}: Boolean;
begin
HasWildcards := (StrScan(FileName, '*') <>nil} or
(StrScan(FileName, '?') <> nil};
end;

Chapter 7, Library reference

187

5trUpper function

Strings

StrUpper function
Purpose

Converts a string to uppercase.

Declaration

function StrUpper(Str: PChar): PChari

StrUpper convertsStr to uppercase and returns Str.

Remarks

See also' StrLower


Example

uses Strings i
var
S: array[O .. 79] of Chari
begin
Readln(S) i
Writeln(StrUpper(S)) i
Writeln(StrLower(S))i
end.

Succ function
Purpose
Declaration
Result type

System
Returns the successor of the argument.
function

Succ (X) :

Same type as parameter.

Remarks

X is an ordinal-type expression. The result, of the same type as X, is the


successor of X.

See also

Dec, Inc, Pred

Swap function
Purpose
Declaration
Result type

188

System
Swaps the high- and low-order bytes of the argument.
function Swap (X) i

Same type as parameter.

Remarks

X is an expression of type Integer or Word.

See also

Hi, La

Programmer's Reference

Swap function

Example

var x: Word;
begin
X := Swap($1234);
end.

{$3412}

SwapVectors procedure
Purpose
Declaration

Dos

Swaps interrupt vectors.


procedure SwapVectors;

Remarks

Swaps the contents of the SaveIntXX pointers in the System unit with the
current contents of the interrupt vectors. Swap Vectors is typically called
just before and just after a call to Exec. This ensures that the Execed
process does not use any interrupt handlers installed by the current
process and vice versa.

See also

Exec, SavelntXX

Example

{$M 8192,O,O}
uses Dos;
var Command: string[79];
begin
Write('Enter DOS command: ~);
Readln(Command) ;
if Command <> " then
Command:= 'IC ' + Command;
SwapVectors;
Exec (GetEnv('COMSPEC'), Command);
SwapVectors;
if DosError <> 0 then
Writeln( 'Could not execute COMMAND. COM' );
end.

TDateTime type
Purpose

Declaration

WinDos

Variables of type TDateTime are used in connection with UnpackTime and


PackTime procedures to examine and construct 4-byte, packed date-andtime values for the GetFTime, SetFTime, FindFirst, and FinNext procedures.
type
TDateTime'= record
Year,Month,Day,Hour,Min, Sec: Word;
end;

Chapter 7, Library reference

189

TOateTime type

Remarks

Valid ranges are Year 1980 ..2099, Month 1..12, Day 1..31, Hour 0.. 23, Min
0 ..59, and Sec 0..59.

See also

PackTime

System

Test8086 variable
Purpose
Declaration
Remarks

Identifies the type of 80x86 processor the system contains.


var Test8086: Byte;

The run-time library's start-up code contains detection logic that automatically determines what kind of 80x86 processor the system contains.
The result of the CPU detection is stored in TestSOS6 as one of the
following values:
Value

o
1
2

Definition

Processor is an 8086
Processor is an 80286
Processor is an 80386 or later

When the run-time library detects that the processor is an 80386 or later
CPU, it uses 80386 instructions to speed up certain operations. In
particular, Longint multiplication, division, and shifts are performed using
32-bit instructions when an 80386 is detected.
See also

TestSOS7

System

Test808? variable
Purpose
Declaration
Remarks

Stores the results of the 80x87 autodetection logic and coprocessor


classification.
var Test8087: Byte;

The TestSOS7 variable indicates whether floating-point instructions are


being emulated or actually executed. The following values stored in
TestSOS7 are defined.
Value

o
1
2
3

190

Definition

No coprocessor detected
8087 detected
80287 detected
80387 or later detected

Programmer's Refer?nce

Test8087 variable

If an application contains no 80x87 instructions, the80x87 detection logic


is not linked into the executable, and Test8087 will therefore always
contain zero.

For additional information on writing programs using the 80x87, see


Chapter 14, "Using the 80x87," in the Language Guide~
Example

The following program tests for the existence of a coprocessor.


program Test87;
{$N+}
{$E+}
var
x: Single;
begin

{ Enable 80x87 instructions }


{ Include 80x87 emulator library }

{ Force generation of 80x87 instructions


Test8087 of
Writeln ('No numeric coprocessor detected.');
writeln ('8087 detected. ');
Writeln ('80287 detected.');
Writeln ('80387 or later detected.');

X := 0;

case
0:
1:
2:
3:
end;
end.

TextAttr variable
Purpose
Declaration
Remarks

Crt

Stores the currently selected text attribute.


var TextAt tr: Byte;

Although text attributes are normally set through calls to TextColor and
TextBackground, you can also set them by directly storing a value in
TextAttr. The color information is encoded in TextAttr as follows:

bit -

7 6 5 4 3 2 1 0

Islblblblflflflfl

where ffff is the 4-bit foreground color, bbbb is the 3-bit background color,
and B is the blink-enable bit. If you use the color constants for creating
TextAttr values, the background color can only be selected from the first 8
colors, and it must be multiplied by 16 to get it into the correct bit
positions. For example, the following assignment selects blinking yellow
characters on a blue background:
TextAttr := Yellow + Blue * 16 + Blink;
See also

LowVideo, NormVideo, TextBackground, TextColor

Chapter 7, Library reference

191

Text color constants

Text color constants

Crt

Purpose

Represents the text colors.

Remarks

The following constants are used in connection with the T ext Color and
TextBackground procedures.
Constant

Black
Blue
Green
Cyan
Red
. Magenta
Brown
LightGray
DarkGray
LightBlue
LightGreen'
LightCyan
LightRed
LightMagenta
Yellow
White
Blink

Value

0
1
2
3
4
5
6
7
8
9

10
11

12
13
14
15
128

Text colors are represented by the numbers between 0 and 15; to easily
identify each color, you can use these constants instead of numbers. In the
color text modes, the foreground of each character is selectable from 16
colors, and the background from 8 colors. The foreground of each
character can also be made to blink.
See also

TextAttr, TextBackground, TextColor

TextBackground procedure
Purpose
Declaration
Remarks

192

Crt

Selects the background color.


procedure TextBackground(Color: Byte);

Color is an integer expression in the range 0.. 7, corresponding to one of the


first eight text color constants. There is a byte variable in Crt-TextAttrthat is used to hold the current video attribute. TextBackground sets bits
4-6 of TextAttr to Color.

Programmer's Reference

TextBackground procedure

The background of all characters subsequently written will be in the


specified color.
See also

HighVideo, LowVideo, NormVideo, TextColor, Text color

TextColor procedure
Purpose
Declaration
Remarks

Crt

Selects the foreground character color.


procedure TextColor (Color: Byte);

Color is an integer expression in the range 0..15, corresponding to one of


the text color constants defined in Crt.
There is a byte-type variable in Crt-TextAttr-that is used to hold the
current video attribute. TextColor sets bits 0-3 to Color. If Color is greater
than 15, the blink bit (bit 7) is also set; otherwise, it is cleared.
You can make characters blink by adding 128 to the color value. The Blink
constant is defined for that purpose; in fact, for compatibility with Turbo
Pascal 3.0, any Color value above 15 causes the characters to blink. The
foreground of all characters subsequently written will be in the specified
color.

See also

HighVideo, LowVideo, NormVideo, TextBackground, Text color

Example

TextColor (Green);
TextColor(LightRed + Blink);
TextColor(14) ;

TextHeight function
Purpose
Declaration
Remarks

{ Green characters
{ Blinking light-red characters }
{ Yellow characters }

Graph

Returns the height of a string in pixels.


function TextHeight (TextString: String): Word;

Takes the current font size and multiplication factor, and determines the
height of TextString in pixels. This is useful for adjusting the spacing
between lines, computing viewport heights, sizing a title to make it fit on
a graph or in a box, and more.
For example, with the 8x8 bit-mapped font and a multiplication factor of 1
(set by SetTextStyle), the string Turbo is 8 pixels high.
It is important to use TextHeight to compute the height of strings, instead

of doing the computation manually. In that way, no source code modifications have to be made when different fonts are selected.

Chapter 7, Library reference

193

II

TextHeight function

Restrictions

Must be in graphics mode.

See also

OutText, OutTextXY, SetTextStyle, SetUserCharSize, TextWidth

Example

uses Graph;
var
Gd, Gm: Integer;
Y, Size: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1);
Y := 0;
for Size := 1 to 5 do
begin
SetTextStyle(DefaultFont, HorizDir, Size);
OutTextXY(O, Y, 'Turbo Graphics');
Inc(Y, TextHeight('Turbo Graphics'));
end;
Readln;
CloseGraph;
end.

TextMode procedure
Purpose
Declaration
Remarks

Crt

Selects a specific text mode.


procedure TextMode (Mode: Word);

See page 25 for a list of defined Crt mode constants. When TextMode is
called, the current window is. reset to the entire screen, DirectVideo is set to
True, CheckS now is set to True if a color mode was selected, the current text
attribute is reset to normal corresponding to a call to NormVideo, and the
current video is stored in LastMode. In addition, LastMode is initialized at
program startup to the then-active video mode.
Specifying TextMode(LastMode) causes the last active text mode to be
reselected. This is useful when you want to return to text mode after using
a graphics package, such as Graph or Graph3.
The following call to TextMode:
TextMode(C80 + Font8x8)

will reset the display into f-l3lines and 80 columns on an EGA, or 50 lines
and 80 columns on a VGA' with a color monitor. TextMode(Lo(LastMode))

194

Programmer's Reference

TextMode procedure

always turns off 43- or 50-line mode and resets the display (although it
leaves the video mode unchanged); while
TextMode (Lo (LastMode) + Font8x8)

will keep the video mode the same, but reset the display into 43 or 50
lines.
If your system is in 43- or 50-line mode when you load a Turbo Pascal
program, the mode will be preserved by the Crt startup code, and the
window variable that keeps track of the maximum number of lines
onscreen (WindMax) will be initialized correctly.

Here's how to write a "well-behaved" program that will restore the video
mode to its original state:
program Video;
uses Crt;
var OrigMode: Integer;
begin
OrigMode := LastMode;

{ Remember original mode }

TextMode(OrigMode) ;
end.

Note that TextMode does not support graphics modes, and therefore
TextMode(OrigMode) will only restore those modes supported by
TextMode.
See also

Crt mode constants, RestoreCrtMode

TextRec.type
Purpose
Declaration

Dos
Record definition used internally by Turbo Pascal and also declared in the
Dos unit.
type
TextBuf = array[O .. 127J of Char;
TextRec = record
Handle: Word;
Mode: Word;
BufSize: Word;
Private: Word;
BufPos: Word;
BufEnd: Word;
BufPtr: ATextBuf;
OpenFunc: Pointer;
InOutFunc: Pointer;

Chapter 7, Library reference

195

TextRec type

FlushFunc: Pointer;
CloseFunc: Pointer;
UserData: array[l .. 16] of Byte;
Name: array[O .. 79] of Char;
Buffer: TextBuf;
end;

Remarks

TextRec is the internal format of a variable of type Text. See Chapter 18,
"Using overlays," in the Language Guide for additional information.

See also

FileRec

TextSettingsType type
Purpose
Declaration

Graph

The record that defines the text attributes used by GetTextSettings.


type

TextSettingsType = record
Font: Word;
Direction: Word;
CharSize: Word;
Horiz: Word;
Vert: Word;
end; .

Remarks

See page 55 for a list of the Font control control constants used to identify
font attributes.

TextWidth function
Purpose
Declaration
Remarks

Graph

Returns the width of a st~ing in pixels.


function TextWidth(TextString: String): Word;

Takes the string length, current font size, and multiplication factor, and
determines the width of TextString in pixels. This is useful for computing
viewport widths, sizing a title to make it fit on a graph or in a box, and so
on.
For example, with the 8x8 bit-mapped font and a multiplication factor of 1
(set by SetTextStyle), the string Turbo is 40 pixels wide.
It is important to use TextWidth to compute the width of strings, instead of
doing the computation manually. In that way, no source code
modifications have to be made when different fonts are selected.

Restrictions

196

Must be in graphics mode.

Programmer's Reference

TextWidth function

See also

OutText, OutTexfXY, SetTextStyle~ SetUserCharSize, TextHeight

Example

uses Graph;
var
Gd, Gm: Integer;
Row: Integer;
Title: String;
Size: Integer;
begin
Gd := Detect;
InitGraph(Gd, Gm, ");
if GraphResult <> grOk then
Halt (1) ;
Row := 0;
Title := 'Turbo Graphics';
Size := 1;
while TextWidth(Title) < GetMaxX do
begin
OutTextXY(O, Row, Title);
Inc (Row, TextHeight('M'));
Inc(Size);
SetTextStyle(DefaultFont, HorizDir, Size);
end;
Readln;
CloseGraph;
'end.

TFileRec type
Purpose
Declaration

Remarks

WinDos
A record definition used f~r both typed and untyped files.
type
TFileRec = record
Handle: Word;
Mode: Word;
RecSize: Word;
Private: array[1 .. 26] of Byte;
UserData: array[1 .. 16] of Byte;
Name: array[O .. 79] of Char;
end;

TFileRec is a record definition used internally by Turbo Pascal as well


as being declared in the WinDos unit. See "Internal data formats" in
Chapter 19 in the Language Guide.

Chapter 7, Library reference

197

TRegisters type

WinDos

TRegisters type
Purpose

Declaration

Variables of type TRegisters are used by Intr and MsDos procedures to


specify the specify input register contents and examine output register
contents of a software interrupt.
type
TRegisters = record
case Integer of
0: (AX, BX, CX i DX, BP, SI, DI, DS, ES, Flags: Word);
1: (AL, AR, BL, BH, eLi CH, DL, DH: Byte);
end;

Notice the use of a variant record to map the 8-bit registers on top of their
16-bit equivalents.

Trunc function
Purpose
Declaration
Remarks
Restrictions
See also

System
Truncates a real-type value to an integer-type value.
function Trunc (X: Real): Longint;

X is a real-type expression. Trunc returns a Longint value that is the value


of X rounded toward zero.
A run-time error occurs if the truncated value of X is not within the
Longint range.

Round, Int

System

Truncate procedure
Purpose
Declaration
Remarks

Truncates the file size at the current file position.


procedure Truncate (var F);

F is a file variable of any type. All records past F are deleted, and the
current file position also becomes end-of-file (Eof(F) is True).
If I/O-checking is off, the IOResult function returns a nonzero value if an

error occurs.
Restrictions
See also

198

F must be open. Truncate does not work on text files.

Reset, Rewrite, Seek

Programmer's Reference

TSearchRec type

TSearchRec type
Purpose
Declaration

WinDos

Variables of type TSearchRec are used by the FindFirst and FindNext


procedures to scan directories.
type

TSearchRec = record
Fill: array[1 .. 21] of Byte;
Attr: Byte;
Time: Longint;
Size: Longint;
Name: array[O .. 12] of Char;
end;

Remarks

The information for each file found by one of these procedures is reported
back in a TSearchRec. The Attr field contains the file's attributes
(constructed from file attribute constants), Time contains its packed date
and time (use UnpackTime to unpack), Size contains its size in bytes, and
Name contains its name. The Fill field is reserved by DOS; don't modify it.

See also

FindFirst, FindNext

TIextRec type
Purpose
Declaration

WinDos
A record definition that is the internal format of a variable of type Text.
type

PTextBuf = ATTextBuf;
TTextBuf = array[O .. 127] of Char;
TTextRec = record
Handle: Word;
Mode: Word;
BufSize: Word;
Private: Word;
BufPos: Word;
BufEnd: Word;
BufPtr: PTextBuf;
OpenFunc: Pointer;
InOutFunc: Pointer;
FlushFunc: Pointer;
CloseFunc: Pointer;
UserData: array[1 .. 16] of Byte;
Name: array[O .. 79] of Char;
Buffer: TTextBuf;
end;

Chapter 7, Library reference

I
199

TTextRec type

Remarks

TTextRec is a record definition used internally by Turbo Pascal as well


as being declared in the WinDos unit. See "Internal data formats" in
Chapter 19 in the Language Guide.

TypeOf function
Purpose
Declaration
Remarks

Returns a pointer to an object type's virtual method table (VMT).


function TypeOf (X): Pointer i

X is either an object type identifier or an instance of an object type. In


either case, TypeO! returns the address of the object type's virtual method
table. TypeO! can be applied only to object types that have a VMT; all
other types result in an error. See Chapter 19, "Memory issues," in the
Language Guide.

UnpackTime procedure
Purpose
Declaration

Dos, WinDos

Converts a 4-byte, packed date-and-time Longint returned by GetFTime,


FindFirst, or FindNext into an unpacked DateTime record.
procedure UnpackTime(Time: Longintivar DT: DateTime) i

Remarks

DateTime is a record declared in the Dos unit. If you are writing Windows
programs, use TDateTime. The fields of the Time record are not rangechecked. See page 26 for the DateTime record declaration and page 189 for
the TDateTime r~cord declaration.

See also

DateTime, GetFTime, GetTime, PackTime, SetFTime, SetTime, TDateTime

UpCase function
Purpose
Declaration
Remarks

200

System

System

Converts a character to uppercase.


function UpCase (Ch: Char): Char i

Ch is an expression of type Char. The result of type Char is Ch converted to


uppercase. Character values not in the range a.. z are unaffected.

Programmer's Reference

Val procedure

System

Val procedure
Purpose
Declaration
Remarks

Converts the string value to its numeric representation.


procedure Val (8i var Vi var Code: Integer)

S is a string-type expression or an expression of type PChar if the


extended syntax is enabled. V is an integer-type or real-type variable. Code
is a variable of type Integer. S must be a sequence of characters that form a
signed whole number according to the syntax shown in the section
"Numbers" in Chapter 2 in the Language Guide. Val converts S to its
numeric representation and stores the result in V. If the string is somehow
invalid, the index of the offending character is stored in Code; otherwise,
Code is set to zero. For a null-terminated string, the error position returned
in Code is one larger than the actual zero-based index of the character in
error.

Val performs range checking differently depending on the state of {$R}


and the type of the parameter V.
With range checking on, {$R+}, an out-of-range value always generates a
run-time error. With range checking off, {$R-}, the values for an out-ofrange value vary depending upon the data type of V. If V is a Real or
Longint type, the value of V is undefined and Code returns a nonzero
value. For any other numeric type, Code returns a value of zero, and V will
contain the results of an overflow calculation (assuming the string valueis
within the long integer range).
Therefore, you should pass Val a Longint variable and perform range
checking before making an ,assignment of the returned value:
{$R-}
Val('65536', LongIntVar, Code)
if (Code <> 0) or (LongIntVar < 0) or (LongIntVar > 65535) then
{ Error}
else
WordVar

:=

LongIntVari

In this example, LongIntVar would be set to 65,536, and Code would equal
O. Because 65,536 is out of range for a Word variable, an error would be
reported.
Restrictions
See also

Trailing spaces must be deleted.

Str

Chapter 7, Library reference

201

Val procedure

Example

var I, Code: Integer;


begin
Val(ParamStr(l), I, Code);
if code <> 0 then
Writeln('Error at position: '
else
Writeln('Value = " I);
end.

{ Get text from command line }


{ Error during conversion to integer? }
Code)

ViewPortType type
Purpose
Declaration

Graph

A record that reports the status of the current viewport; used by


Get View Settings .
type
ViewPortType = record
Xl, Y1, X2, Y2: Integer;
Clip: Boolean;
end;

Remarks

The points (Xl, Yl) and (X2, Y2) are the dimensions of the active viewport
and are given in absolute screen coordinates. Clip is a Boolean variable
that controls whether clipping is active.

See also

GetViewSettings

WhereX function
Purpose
Declaration
See also

Crt

Returns the X-coordinate of the current cursor position, relative to the


current window.
function WhereX: Byte;

GotoXY, WhereY, Window

WhereY function
Purpose
Declaration
See also

202

Crt

Returns the Y-coordinate of the current cursor position, relative to the


current window.
function WhereY: Byte;

GotoXY, WhereX, Window

Programmer's Reference

WindMax and WindMin variables

WindMax and WindMin variables


Purpose
Declaration

Crt

Store the screen coordinates of the current window.


var WindMax,' WindMin: Word;

Remarks

These variables are set by calls to the Window procedure. WindMin defines
the upper left corner, and WindMax defines the lower right corner. The
x-coordinate is stored in the low byte, and the y-coordinate is stored in the
high byte. For example, Lo(WindMin) produces the x-coordinate of the left
edge, and Hi(WindMax) produces the y-coordinate of the bottom edge.
The upper left corner of the screen corresponds to (x,y) = (0,0). However,
for coordinates passed to Window and GotoXY, the upper left corner is at
(1,1).

See also

GotoXY, High, Lo, LoWindow

Window procedure
Purpose
Declaration
Remarks

Crt

Defines a text window onscreen.


procedure Window (Xl, Y1, X2,' Y2: Byte);

Xl and Yl are the coordinates of the upper left corner of the window, and
X2 and Y2 are the coordinates of the lower right corner. The upper left
corner of the screen corresponds to (1, 1). The minimum size of a text
window is one column by one line. If the coordinates are in any way
invalid, the call to Window is ignored.
.

The default window is (1, 1,80,25) in 25-line mode, and (1, 1,80,43) in
43-linemode, corresponding to the entire screen.
All screen coordinates (except the window coordinates themselves) are
relative to the current window. For instance, GotoXY(1, 1) will always
position the cursor in the upper left corner of the current window.
Many Crt procedures and functions are window-relative, including ClrEol,
ClrSer, DelLine, GotoXY, InsLine, WhereX, WhereY, Read, Readln, Write,
Writeln.
WindMin and WindMax store the current window definition. A call to the
Window procedure always moves the cursor to (1, 1).
See also

ClrEol, ClrSer, DelLine, GotoXY, WhereX, WhereY

Chapter 7, Library reference

203

Window procedure

Example

uses Crt;
var
X, Y: Byte;
begin
TextBackground(Black);
ClrScr;
repeat
X := Succ(Random(80));
Y := Succ(Random(25));
Window (X, Y, X + Random(lO)
TextBackground(Random(16));
ClrScr;
until KeYPressed;
end.

{ Clear screen }

{ Draw random windows }


I

Y + Random(8));
{ In random colors }

Write procedure (text-files)


Purpose
Declaration
Remarks

System

Writes one or more values to a text file.


procedure Write( [ var F: Text; 1 PI [,

P2/ "P N

1 );

F, if specified, is a text file variable. If F is omitted, the standard file

variable Output is assumed. Each P is a write parameter. Each write


parameter includes an output expression whose value is to be written to
the file. A write parameter can also contain the specifications of a field
width and a number of decimal places. Each output expression must be of
.a type Char, Integer, Real, string, packed string, or Boolean.
A write parameter has the form
OutExpr [: MinWidth [: DecPlaces 1 1

where OutExpr is an output expression. Min Width and DecPlaces are type
integer expressions.

Min Width specifies the minimum field width, which must be greater than
O. Exactly Min Width characters are written (using leading blanks if necessary) except when OutExpr has a value that must be represented in more
than Min Width characters. In that case, enough characters are written to
represent the value of OutExpr. Likewise, if MinWidth is omitted, then the
necessary number of characters are written to represent the value of
OutExpr.
DecPlaces specifies the number of decimal places in a fixed-point representation of a type Real value. It can be specified only if OutExpr is of type

204

Programmer's Reference

Real, and if Min Width is also specified. When Min Width is specified, it
must be greater than or equal to O.
Write with a character-type value: If MinWidth is omitted, the character
value of OutExpr is written to the file. Otherwise, Min Width - 1 blanks
followed by the character value of OutExpr is written.
Write with a type integer value: If Min Width is omitted, the decimal
representation of OutExpr is written to the file with no preceding blanks.
If Min Width is specified and its value is larger than the length of the
decimal string, enough blanks are written before the decimal string to
make the field width Min Width.
Write with a type real value: If OutExpr has a type real value, its decimal

representation is written to the file. The format of the representation


depends on the presence or absence of DecPlaces.
If DecPlaces is omitted (or if it is present but has a negative value), a
floating-point decimal string is written. If Min Width is also omitted, a

default MinWidth of 17 is assumed; otherwise, if Min Width is less than 8, it


is assumed to be 8. The format of the floating-point string is
I - 1 <digit> . <decimals> E [ + I - 1 <exponent>

The components of the output string are shown in Table 1.3:


Table 1.3
The components of
the output string

[ I -]

" " or "-", according to the sign of OutExpr

<digit>

Single digit, "0" only if OutExpr is 0

<decimals>

Digit string of MinWidth-7 (but at most 10) digits

Uppercase [E] character

[+ I- ]

According to sign of exponent

<exponent>

Two-digit decimal exponent

If DecPlaces is present, a fixed-point decimal string is written. If DecPlaces


is larger than 11, it is assumed to be 11. The format of the fixed-point

string follows:
[ <blanks> 1 [ - 1 <digits> [ . <decimals> 1

The components of the fixed-point string are shown in Table 1.4:


Table 1.4
The components of
the fixed-point
string

[ <blanks> ]

Blanks to satisfy Min Width

[- ]

If OutExpr is negative

<digits>

At least one digit, but no leading zeros

[ . <decimals> ]

Decimals if DecPlaces > 0

Chapter 7, Library reference

I
205

Write with a string-type value: If Min Width is omitted, the string value of

OutExpr is written to the file with no leading blanks. If Min Width is


specified, and its value is larger than the length of OutExpr, enough
blanks are written before the decimal string to make the field width
Min Width.
Write with a packed string-type value: If OutExpr is of packed string type,
the effect is the same as writing a string whose length is the number of
elements in the packed string type.
Write with a Boolean value: If OutExpr is of type Boolean, the effect is the
same as writing the strings True or False, depending on the value of
OutExpr.

With {$I-}, IOResult returns a if the operation was successful; otherwise, it


returns a nonzero error code.
Restrictions
See also

File must be open for output.

Read, Readln, Writeln

Write procedure (typed files)


Purpose
Declaration
Remarks

System

Writes a variable into a file component.


procedure Write (F / Vi [/ V2 /

/ VN

1 )i

F is a file variable, and each V is a variable of the same type as the


component type of F. For each variable written, the current file position is
advanced to the next component. If the current file position is at the end
of the file (that is, if Eof(F) is True) the file is expanded.
With {$I-}, IOResult returns a if the operation was successful; otherwise, it
returns a nonzero error code.

See also

Writeln

System

Writeln procedure
Purpose
Declaration
Remarks

206

Executes the Write procedure, then outputs an end-of-line marker to the


file.
procedure Wri teln ( [ var F: Text i 1 Pi [/ P2 /

/ PN

1 )i

vyriteln procedure is an extension to the Write procedure, as it is defined


for text files. After executing Write, Writeln writes an end-of-line marker
(carriage-return/linefeed) to the file. ,Writeln(F) with no parameters writes

Programmer's Reference

WrlTeln proceaure

an end-of-line marker to the file. (Writeln with no parameter list altogether


corresponds to Writeln(Output).)
Restrictions
See also

File must be open for output.


Write

I
Chapter 7, Library reference

207

208

Programmer's Reference

2
Compiler directives
See Appendix B for a table
summarizing the compiler
directives.

This chapter describes the compiler directives you can use to


control the features of the Turbo Pascal compiler. Listed
alphabetically, each compiler directive is classified as either a
switch, parameter, or conditional compilation directive. Following
the list of compiler directives is a brief discussion of how to use
the conditional compilation directives. This section describes how
to use conditional constructs and symbols to produce different
code from the same source text.
.
A compiler directive is a comment with a special syntax. Turbo
Pascal allows compiler directives wherever comments are
allowed. A compiler directive starts with a $ as the first character
after the opening comment delimiter, immediately followed by a
name (one or more letters) that designates the particular directive.
You can include comments after the directive and any necessary
parameters.
There are three types of directives described in this chapter:
Switch directives turn particular compiler features on or off by

specifying + or - immediately after the directive name. Switch


directives are either global or local.

Global directives affect the entire compilation and must appear


before the declaration part of the program or the unit being
compiled.
.

Local directives affect only the part of the compilation that


extends from the directive until the next occurrence of the
same directive. They can appear anywhere.

Chapter 2, Compiler directives

209

You can group switch directives in a single compiler directive


comment by separating them with commas with no intervening
spaces. For example,
{$B+,R-,S-}

Parameter directives. These directives specify parameters that


See page 223 for more
information about using
conditional compilation
directives.

affect the compilation, such as file names and memory sizes.


Conditional directives. These directives control conditional
compilation of parts of the source text, based on user-definable
conditional symbols.
All directives, except switch directives, must have at least one
blank between the directive name and the parameters. Here are
some examples of compiler directives:
{$B+}
{$R- Turn off range checking}
{$I TYPES. INC}
{SO EdFormat}
{$M 65520,8192,655360}
{$DEFINE Debug}
{$IFDEF Debug}
{$ENDIF}

You can put compiler directives directly into your source code.
You can also change the default directives for both the
command-line compiler (TPC.EXE) and the IDE (TURBO.EXE or
TPX.EXE). The Options I Compiler menu contains many of the
compiler directives; any changes you make to the settings there
will affect all subsequent compilations.
When using the command-line compiler, you can specify compiler
directives on the command line (for example, TPC I$R+ MYPROG), or
you can place directives in a configuration file (see Chapter 3).
Compiier directives in the source code always override the
default values in both the command-line compiler and the IDE.
If you are working in the IDE, using the editor's Alternate
command set, and want a quick way to see what compiler
directives are in effect, press Ctr/+O O. Turbo Pascal will insert the
current settings at the top of your edit window.

210

.Programmer's Reference

Align data

Align data

Switch

Syntax

{$A+}

Default

{$A+}

Type
Remarks

or

{$A-}

Global
The $A directive switches between byte and word alignment of variables
and typed constants. Word alignment has no effect on the 8088 CPU.
However, on a1l80x86 CPUs, word alignment means faster execution
because word-sized items on even addresses are accessed in one memory
cycle rather than two memory cycles for words on odd addresses.
In the {$A+} state, all variables and typed constants larger than one byte
are aligned on a machine-word boundary (an even-numbered address). If
required, unused bytes are inserted between variables to achieve word
alignment. The {$A+} directive does not affect byte-sized variables, nor
does it affect fields of record structures and elements of arrays. A field in a
rec01;:d will align on a word boundary only if the total size of all fields
before it is even. For every element of an array to align on a word
boundary, the size of the elements must be even.
In the {$A-} state, no alignment measures are taken. Variables and typed
constants are simply placed at the next,available address, regardless of
their size.
Regardless of the state of the $A directive, each global var and const
declaration section always starts at a word boundary. Likewise, the
compiler always keeps the stack pointer (SP) word aligned by allocating
an extra unus~d byte in a procedure'S stack frame if required.

Boolean evaluation
Syntax

{$B+}

Default

{$B- }

Type
Remarks

or

Switch
{$B-}

Local
The $B directive switches between the two different models of code
generation for the and and or Boolean operators.
In the {$B+} state, the compiler generates code for complete Boolean
expression evaluation. This means that every operand of a Boolean
expression built from the and and or operators is guaranteed to be
evaluated, even when the result of the entire expression is already known.

Chapter 2, Compiler directives

211

Boolean evaluation

In the {$B-} state, the compiler generates code for short-circuit Boolean
expression evaluation, which means that evaluation stops as soon as the
result of the entire expression becomes evident.
For further details, see the section "Boolean operators" in Chapter 6,
"Expressions," in the Language Guide.

Debug information
Syntax

{ $D+} or {$D-}

Default

{$D+ }

Type

Remarks

Switch

Global
The $0 directive enables or disables the generation of debug information.
This information consists of a line-number table for each procedt:Lre,
which maps object code addresses into source text line numbers.
For units, the debug information is recorded in the .TPU file along with
the unit's object code. Debug information increases the size of .TPU files
and takes up additional room when compiling programs that use the unit,
but it does not affect the size or speed of the executable program.
When a program or unit is compiled in the {$O+} state, Turbo Pascal's
integrated debugger lets you single-step and set breakpoints in that
module.
The Standalone debugging (Options I Debugger) and Map file (Options I
Linker) options produce complete line information for a given module
only if you've compiled that module in the {$O+} state.
The $0 switch is usually used in conjunction with the $L switch, which
enables and disables the generation of local symbol information for '
debugging.
.
If you want to use Turbo Debugger to debug your program, set Compile I
Destination to Disk, choose Options I Debugger, and select the Standalone
option.

DEFINE directive
Syntax

Remarks

212

Conditional compilation

{$DEFINE name}

Defines a conditional symbol with the given name. The symbol is


'recognized for the remainder of the compilation of the current module in

Programmer's Reference

ELSE directive

which the symbol is declared, or until it appears in an {$UNDEF name}


directive. The {$DEFINE name} directive has no effect if name is already
defined.

ELSE directive
Syntax
Remarks

Conditional compilation
{$ELSE}

Switches between compiling and ignoring the source text delimited by the
last {$IFxxx} and the next {$ENDIF}.

Emulation

Switch

Syntax

{$E+}

Default

{$E+}

Type
Remarks

or

{$E-}

Global
The $E directive enables or disables linking with a run-time library that
will emulate the 80x87 numeric coprocessor if one is not present.
When you compile a program in the {$N+,E+} state, Turbo Pascal links
with the fu1l80x87 emulator. The resulting .EXE file can be used on any
machine, regardless of whether an 80x87 is present. If one is found, Turbo
Pascal will use it; otherwise, the run-time library emulates it.
In the {$N+,E-} state, Turbo Pascal produces a program which can only be
used if an 80x87 is present.

The 80x87 emulation switch has no effect if used in a unit; it applies only
to the compilation of a program. Furthermore, if the program is compiled
in the {$N-} state, and if all the units used by the program were compiled
with {$N-}, then an 80x87 run-time library is not required, and the 80x87
emulation switch is ignored.

ENDIF directive
Syntax
Remarks

Conditional compilation

{$ENDIF}

Ends the conditional compilation initiated by the last {$IFxxx} directive.

Chapter 2, Compiler directives

213

Extended syntax

Extended syntax
Syntax

{$X +}

Default

{$X+}

Type
Remarks
The {$X+} directive
does not apply to
built-in functions
(those defined in
the System unit).

Switch
or

{$X - }

Global
The $X directive enables or disables Turbo Pascal's extended syntax:
Function statements. In the {$X+} mode, function calls can be used as
procedure calls; that is, the result of a function call can be discarded.
Generally, the computations performed by a function are represented
through its result, so discarding the result makes little sense. However,
in certain cases a function can carry out multiple' operations based on its
'parameters, and some of those cases may not produce a useful result. In
such cases, the {$X+} extensions allow the function to be treated as a
procedure .
Null-terminated strings. A {$X+} compiler directive enables Turbo
Pascal's support for null-terminated strings by activating the special
rules that apply to the built-in PChar type and zero-based character
arrays. For more details about null-terminated strings, see
Chapter 16, "Using null-terminated strings," in the Language Guide.
r

Force for calls

Switch

Syntax

{$F+}or {$F-}

Default

{$F-}

Type
Remarks

Local'
The $F directive determines which call model to use for subsequently
compiled procedures and functions. Procedures and functions compiled
in the {$F+} state always use the far call modeL In the {$F-} state, Turbo
Pascal automatically selects the appropriate model: far if the procedure or
function is declared in the interface section of a unit; otherwise it selects
near.
The near and far call models are described in full in Chapter 20, "Control
issues," in the Language Guide.

214

Programmerrs Reference

Generate 80286 Code

Generate 80286 Code


Syntax

{ $G+} or {$G-}

Default

{ $G- }

Type

Remarks

Switch

Global

The $G directive enables or disables 80286 code generation. In the {$G-}


state, only generic 8086 instructions are generated, and programs compiled in this state can run on any 80x86 family processor. You can specify
{$G-} any place within your code.
In the {$G+} state, the compiler uses the additional instructions of the
80286 to improve code generation, but programs compiled in this state
cannot run on 8088 and 8086 processors. Additional instructions used in
the {$G+} state include ENTER, LEAVE, PUSH immediate, extended IMUL,
and extended SHL and SHR.

IFDEF directive
Syntax

Remarks

Conditional compilation
{ $IFDEF name}

Compiles the source text that follows it if name is defined.

IFNDEF directive
Syntax

Remarks

Conditional compilation

{ $IFNDEF name}

Compiles the source text that follows it if name is not defined.

IFOPT directive
Syntax

Remarks

Conditional compilation

{$IFOPT switch}

Compiles the source text that follows it if switch is currently in the


specified state. switch consists of the name of a switch option, followed by
a + or a - symbol. For example, the construct
{$IFOPT N+}
type Real ,= Extended;
{$ENDIF}

will compile the type declaration if the $N option is currently active.

Chapter 2, Compiler directives

215

Include file

Include file
Syntax
Type

Remarks

Parameter
{ $I filename}

Local
The $1 parameter directive instructs the compiler to include the named file
in the compilation. In effect, the file is inserted in the compiled text right
after the {$I filename} directive. The default extension for filename is .PAS. If
filename does not specify a directory path, then, in addition to searching
for the file in the current directory, Turbo Pascal searches in the directories
specified in the Options I Directories I Include Directories input box (or in
the directories specified in the II option on the TPC command line).
There is one restriction to the use of include files: An include file can't be
specified in the middle of a statement part. In fact, all statements between
the begin and end of a statement part must exist in the same source file.

Input/output checking
Syntax

{$I+}

Default

{$I+}

Type

Local

Remarks

or

{$I-}

The $1 switch directive enables or disables the automatic code generation


that checks the result of a call to an I/O procedure. I/O procedures are
described in Chapter 13, "Input and output," in the Language Guide. If an
I/O procedure returns a nonzero I/O result when this switch is on, the
program terminates and displays a run-time error message. When this
switch is off, you must check for I/O errors by calling IOResult.

Link object file


Syntax
Type

Remarks

216

Switch

Parameter
{$L filename}

Local

The $L parameter directive instructs the compiler to link the named file
with the program or unit being compiled. The $L directive is used to link
with code written in assembly language for subprograms declared to be
external. The named file must be an Intel relocatable object file (.OBJ file).

Programmer's Reference

Link object file

The default extension for filename is .OBJ. If filename does not specify a
directory path, then, in addition to searching for the file in the current
directory, Turbo Pascal searches in the directories specified in the
Options IDirectories IObject Directories input box (or in the directories
specified in the /0 option on the TPC command line). For further details
about linking with assembly language, see Chapter 23, "Linking
assembler code," in the Language Guide.

Local symbol information


Syntax

{$L+}

Default

{$L+ }

Type
Remarks

Switch

or {$L- }

Global

The $L switch directive enables or disables the generation of local symbol


information. Local symbol information consists of the names and types of
all local variables and constants in a module, that is, the symbols in the
module's implementation part, and the symbols within the module's
procedures and functions.
For units, the local symbol information is recorded in the .TPU file along
with the unit's object code. Local symbol information increases the size of
.TPU files, and takes up additional room when compiling programs that
use the unit, but it does not affect the size or speed of the executable
program.
When a program or unit is compiled in the {$L+} state, Turbo Pascal's
integrated debugger lets you examine and modify the module's local
variables. Furthermore, calls to the module's procedures and functions can
be examined via View ICall Stack.
The Standalone debugging (Options IDebugger) and Map file (Options I
Linker) options produce local symbol information for a given module
only if that module was compiled in the {$L+} state.
The $L switch is usually used in conjunction with the $0 switch, which
enables and disables the generation of line-number- tables for debugging.
The $L directive is ignored if the compiler is in the {$O-} state.

Chapter 2, Compiler directives

217

Memory allocation sizes

Memory allocation sizes


Syntax

{$M stacksize,heapmin,heapmax}

Default

{$M 16384,~,655360}

Type
Remarks

Parameter

Global
The $M directive specifies an application's memory allocation parameters.

stacksize must be an integer number in the range 1,024 to 65,520 which


specifies the size of the stack segment. heapmin and heapmax specify the
minimum and maximum sizes of the heap, respectively. heapmin must be
in the range 0 to 655360, and heapmax must be in the range heapmin to
655360.
The $M directive has no effect when used in a unit.

Numeric coprocessor
Syntax

{$N+}

Default

{ $N - }

Type
Remarks

or

{$N-}

Global
The $N directive switches between the two different models of floating. point code generation supported by Turbo Pascal. In the {$N-} state, code
is generated to perform all real-type calculations in software by calling
run-time library routines. In the {$N+} state, code is generated to perform
all real-type calculations using the 80x87 numeric coprocessor.

Open string parameters


Syntax

{$P+}

Default

{$p- }

Type
Remarks

218

Switch

or

Switch

{$p-}

Local
The $P directive controls the meaning of variable parameters declared
using the string keyword. In the {$P-} state, variable parameters declared
using the string keyword are normal variable parameters, but in the {$P+}
state, they are open string parameters. Regardless of the setting of the $P
directive, the OpenString identifier can always be used to declare open

Programmer's Reference

Overflow checking

string parameters. For more information about open parameters, see


Chapter 9, "Procedures and functions," in the Language Guide.

Overflow checking
Syntax

{$Q+}

Default

{$Q-}

Type

Local

Remarks

Switch

or {$Q-}

The $Q directive controls the generation of overflow checking code. In the


{$Q+} state, certain integer arithmetic operations (+, -, *, Abs, Sqr, Succ,
and Pred) are checked for overflow. The code for each of these integer
arithmetic operations is followed by additional code that verifies that the
result is within the supported range. If an overflow check fails, the
program terminates and displays a run-time error message.
The {$Q+} does not affect the Inc and Dec standard procedures. These
procedures are never checked for overflow.
The $Q switch is usually used in conjunction with the $R switch, which
enables and disables the generation of range-checking code. Enabling
overflow checking slows down your program and mak~s it somewhat
larger, so use {$Q+} only for debugging.

Overlay code generation


Syntax

{$O+}

Default

{$O- }

Type

Remarks

Switch

or {$O-}

Global

The $0 switch directive enables or disables overlay code generation.


Turbo Pascal allows a unit to be overlaid only if it was compiled with
{$O+}. In this state, the code generator takes special precautions when
passing string and set constant parameters from one overlaid procedure
or function to another.
The use of {$O+} in a unit does not force you to overlay that unit. It just
instructs Turbo Pascal to ensure that the unit can be overlaid, if so desired.
If you develop units that you plan to use in overlaid as well as nonoverlaid applications, then compiling them with {$O+} ensures that you
can indeed do both with just one version of the unit.

Chapter 2, Compiler directives

219

Overlay code generation

A {$O+} compiler directive is almost always used in conjunction with a


{$F+} directive to satisfy the overlay manager's far call requirement.
For further details on overlay code generation, see Chapter 18, "Using
overlays,'~ in the Language Guide.

Overlay unit name


Syntax
Type

Remarks

Parameter

{$O uni tname}

Local
The Overlay unit name directive turns a unit into an overlay.
The {SO unitname} directive has no effect if used in a unit; when compiling
a program, it specifies which of the units used by the program should be
place~ in an .OVR file instead of in the .EXE file.

{SO unitname} directives must be placed after the program's uses clause ..
Turbo Pascal reports an error if you attempt to overlay a unit that wasn't
compiled in the {$O+} state.

Range checking
Syntax

{$R+}

Default

{ $R- }

Type

Local

Remarks

Switch
or

{$R-}

The $R directive enables or disables the generation of range-checking .


code. In the {$R+} state, all array and string-indexing expressions are

verified as being within the defined bounds and all assignments to scalar
and subrange variables are checked to be within range. If a range check
fails, the program terminates and displays a run-time error message.

If $R is switched on, all calls to virtual methods are checked for the
initialization status of the object instance making the call. If the instance
making the call has not been initialized by its constructor, a range check
run-time error occurs.
Enabling range checking and virtual method call checking slows down
your program and makes it somewhat larger, so use the {$R+} only for
debugging.

220

Programmer's Reference

Stack -overflow checking

Stack-overflow checking
Syntax

{$S+}

Default

{$S+ }

.Type

Local

Remarks

or

{$S-}

The $S directive enables or disables the generation of stack-overflow


checking code. In the {$S+} state, the compiler generates code at the
beginning of each procedure or function that checks whether there is
sufficient stack space for the local variables and other temporary storage.
When there is not enough stack space, a call to a procedure or function
compiled with {$S+} causes the program to terminate and display a runtime error message. In the {$S-} state, such a call is likely to cause a system
crash.

Symbol reference information


Syntax

{$Y+}

Default

{ $Y +}

Type
Remarks

Switch

or

Switch

{$Y-}

Global
The $Y directive enables or disables generation of symbol reference
information. This information consists of tables that provide the line
numbers of all declarations of and references to symbols in a module.
For units, the symbol reference information is recorded in the .TPU file
along with the unit's object code. Symbol reference information increases
the size of .TPU files, but it does not affect the size or speed of the
executable program.
When a program or unit is compiled in the {$Y+} state, Turbo Pascal's
integrated browser can display symbol definition and reference
information for that module.
The $Y switch is usually used in conjunction with the $0 and $L switches,
which control generation of debug information and local symbol
information. The $Y directive has no effect unless both $0 and $L are
enabled.

Chapter 2, Compiler directives

221

Type-checked p'ointers

Type-checked pOinters
Syntax

{$T+}

Default

{$T-}

Type
Remarks

or

{$T-}

Global
The $T directive controls the types of pointer values generated by the @
operator. In the {$T-} state, the result type of the @ operator is always
Pointer. In other words, the result is an untyped pointer that is compatible
with all other pointer types. When @ is applied to a variable reference in
the {$T+} state, the type of the result is AT, where T is the type of the.
variable reference. In other words, the result is of a type that is compatible
only with other pointers to the type of the variable.

UNDEF directive
Syntax
Remarks

Conditional compilation

{$UNDEF name}

Undefines a previously defined conditional symbol. The symbol is


forgotten for the remainder of the compilation or until it reappears in a
{$DEFINE name} directive. The {$UNDEF name} directive has no effect if
name is already undefined.

Var-string checking
Syntax

{$V+}

Default

{$V+}

Type
Remarks

Switch

or

Switch
{$V-}

Local.
The $V directive controls type checking on strings passed as variable
parameters. In the {$V+} state, strict type checking is performed, requiring
the formal and actual parameters to be of identical string types. In the {$V-}
(relaxed) state, any string type variable is allowed as an actual parameter,
even if the declared maximum length is not the same as that of the formal
parameter.
The {$V-} state essentially provides an ('unsafe" version of open string
parameters. Although {$V-} is still supported, you should use .open string .
parameters. For additional information, see "Open string parameters" in
Chapter 9 in the Language Guide.

222

Programmer's Reference

Using conditional compilation directives


Two basic conditional compilation constructs closely resemble
Pascal's if statement. The first construct,
{$IFxxx}
{$ENDIF}

causes the source text between {$IFxxx} and {$ENDIF} to be


compiled only if the condition specified in {$IFxxx} is True. If the
condition is False, the source text between the two directives is
ignored.
The second conditional compilation construct
{$IFxxx}
{$ELSE}
{$ENDIF}

causes either the source text between {$IFxxx} and {$ELSE} or the
source text between {$ELSE} and {$ENDIF} to be compiled,
depending on the condition specified by the {$I Fxxx}.
Here are some examples of conditional compilation constructs:
{$IFDEF Debug}
writeln(/X =
{$ENDIF}

"

Xl;

{$IFDEF CPU87}
{$N+}
type

Real
{$ELSE}
{$N-}

= Double;

type

Single = Real;
Double = Real;
Extended = Real;
Comp = Real;
{$ENDIF}

You can nest conditional compilation constructs up to 16 levels


deep. For every {$IFxxx}, the corresponding {$ENDIF} must be
found within the same source file-which means there must be an
equal number of {$IFxxx}'s and {$ENDIF}'s in every source file.

Chapter 2, Compiler directives

223

Conditional
symbols

Conditional compilation is based on the evaluation of conditional


symbols. Conditional symbols are defined and undefined using
the directives
{$DEFINE name}
{$UNDEF name}

You can also use the /0 switch in the command-line compiler (or
place it in the Conditional Defines input box from within
Options I Compiler of the IDE).
Conditional symbols are best compared to Boolean variables:
They are either True (defined) or False (undefined). The {$OEFINE}
directive sets a given symbol to True, and the {$UNOEF} directive
sets it to False.
Conditional symbols follow the same rules as Pascal identifiers:
They must start with a letter, followed by any combination of
letters, digits, and underscores. They can be of any length, but
only the first 63 characters are significant.
Conditional symbols and Pascal identifiers have no correlation
whatsoever. Conditional symbols cannot be referenced in the
actual program and the program's identifiers cannot be referenced
in conditional directives. For example, the construct
const
Debug = True;
begin
{$IFDEF Debug}
Writeln('Debugis on');
{$ENDIF}
end;

will not compile the Writeln statement. Likewise, the construct


{$DEFINE Debug}
begin
if Debug then
Writeln('Debug is on');
end;

will result in an unknown identifier error in the if statement.


Turbo Pascal defines the following standard conditional symbols:

224

Programmer's Reference

VER70

Always defined, indicating that this is version 7.0 of


Turbo Pascal. Each version has corresponding
predefined symbols; for example, version B.O would
have VERBO defined, version B.S would have VERBS
defined, and so on.

MSOOS

Always defined, indicating that the operating


system is MS-DOS or PC-DOS.

CPU86

Always defined, indicating that the CPU belongs to


the BOxB6 family of processors. Versions of Turbo
Pascal for other CPUs will instead define a symbolic
name for that particular CPU.

CPU87

Defined if an BOxB7 numeric coprocessor is present


at compile time. If the construct
{$IFDEF CPU87} {$N+} {$ELSE} {$N-} {$ENDIF}

appears at the beginning of a compilation, Turbo


Pascal automatically selects the appropriate model
of floating-point code generation for that particular
computer.
Other conditional symbols can be defined before a compilation by
using the Conditional Defines input box (Options ICompiler), or
the 10 command-line option if you are using the command-line
compiler.

Chapter 2, Compiler directives

225

226

Programmer's Reference

Command-line compiler
Turbo Pascal command-line compiler (TPC.EXE) lets you invoke
all the functions of the IDE compilers (TURBO.EXE and TPX.EXE)
from the DOS command line.
If you need help using the
command-line compiler, you
can get online help by
typing THELP at the
command line.

You run TPC.EXE from the DOS prompt using a command with
the following syntax:
TPC [options] filename [options]

options are zero or more optional parameters that provide


additional information to the compiler. filename is the name of the
source file to compile. If you type TPC alone, it displays a help
screen of command-line options and syntax.
If filename does not have an extension, TPC assumes .PAS. If you

don't want the file you're compiling to have an extension, you


must append a period (.) to the end of filename. If the source text
contained infilename is a program, TPC creates an executable file
named FILENAME.EXE. If filename contains a unit, TPC creates a
Turbo Pascal unit file named FILENAME. TPU.
You can specify a number of options for TPC. An option consists
of a slash (I) immediately followed by an option letter. In some
cases, the option letter is followed by additional information, such
as a number, a symbol, or a directory name. Options can be given
in any order and can come before and/or after the file name.

Chapter 3, Command-line compiler

227

Command-line compiler options


The IDE lets you set various options through the menus; TPC
gives you access to these options using the slash (/) delimiter. You
can also precede options with a hyphen (-) instead of a slash (I),
but those options that start with a hyphen must be separated by
blanks. For example, the following two command lines are
equivalent and legal:
TPC -IC:\TP -DDEBUG SORTNAME -$S- -$F+
TPC /IC:\TP/DDEBUG SORTNAME /$S-/$F+

The first command line uses hyphens with at least one blank
separating the options; the second uses slashes, and no separation
is needed.
The following table lists the command-line options:
Table 3.1
Command-line options

Option

'$A+
I$AIf you type TPC alone at the
command line, a list of
command-line compiler
options appears on your
screen.

1$8+
1$8.1$0+
1$0-

I$E+
I$EI$F+
I$FI$G+
I$G1$1+
1$1I$L+
I$L-

I$Mstack,min,max
I$N+
I$N1$0+
1$0I$P+
I$P1$0+
1$0I$R+
I$R1$5+
1$5I$T+
I$TI$V+
I$VI$X+

228

Description

Align data on word boundaries


Align data on byte boundaries
Complete Boolean evaluation
Short circuit Boolean evaluation
Debugging information on
Debugging information off
Emulation on
Emulation off
Force far calls on
Force far calls off
286 code generation on
286 code generation off
I/O checking on
I/O checking off
Local symbols on
Local symbols off
Memory sizes
Numeric coprocessor on
Numeric coprocessor off
Overlay code generation on
Overlay code generation off
Open parameters on
Open parameters off
Overflow checking on
Overflow checking off
Range checking on
Range checking off
Stack checking on
Stack checking off
Type-checked pointers on
Type-checked pointers off
Strict var-string checking
Relaxed var-string checking
Extended syntax support on

Programmers Reference

Table 3.1: Command-line options (continued)

!$X-

Extended syntax support off

18

Build all units


Define conditional symbol
EXE and TPU directory
Find run-time error
Map file with segment
Map file with publics
Detailed map file
Include directories
Link buffer on disk
Make modified units
Object directories
Quiet compile
TPL & CFG directories
Unit directories
EXE debug information

lOdefines
IEpath
IFsegment:offset
IGS
IGP
IGO

Ilpath
IL
1M

IOpath
10

fTpath
IUpath
N

Compiler
directive options Turbo Pascal supports several compiler directives, all of which are
described in Chapter 2, "Compiler directives."
The 1$ and 10 command-line options let you change the default
states of most compiler directives. Using 1$ and 10 on the
command line is equivalent to inserting the corresponding
compiler directive at the beginning of each source file compiled.
The switch directive
option

The 1$ option lets you change the default state of all the switch
directives. The syntax of a switch directive option is 1$ followed
by the directive letter, followed by a plus (+) or a minus (-). For
example,
TPC MYSTUFF /$R-

compiles MYSTUFF.PAS with range checking turned off, while


TPC MYSTUFF /$R+

compiles it with range checking turned on. Note that if a {$R+} or


{$R-} compiler directive appears in the source text, it overrides the
I$R command-line option.
You can repeat the 1$ option in order to specify multiple compiler
directives:
TPC MYSTUFF /$R-/$I-/$V-/$F+

Alternately, TPC lets you write a list of directives (except for $M),
separated by commas:

Chapter 3, Command-line compiler

229

Note that only one dollar sign


($) is needed.

TPC MYSTUFF /$R-,I-,V-,F+

In addition to changing switch directives, 1$ also lets you specify a


program's memory allocation parameters, using the following
format:
/$Mstacksize,heapmin,heapmax

where stacksize is the stack size, heapmin is the minimum heap


size, and heapmax is the maximum heap size. The values are in
bytes, and each is a decimal number unless it is preceded by a
dollar sign ($), in which case it is assumed to be hexadecimal. So,
for example, the following command lines are equivalent:
TPC MYSTUFF /$M16384,256,4096
TPC MYSTUFF /$M$4000,$100,$1000

Note that, because of its format, you cannot use the $M option in a
list of directives separated by commas.
The conditional defines
option

The 10 option lets you define conditional symbols, corresponding


to the {$OEFINE symbol} compiler directive. The 10 option must be
followed by one or more conditional symbols, separated by
semicolons (;). For example, the following command line
TPC MYSTUFF /DIOCHECKiDEBUGiLIST

. defines three conditional symbols, iocheck, debug, and list, for the
compilation of MYSTUFF.PAS. This is equivalent to inserting
{$DEFINE IOCHECK}
{$DEFINE DEBUG}
{$DEFINE LIST}

at the beginning of MYSTUFF.PAS. If you specify multiple 10


directives, you can concatenate the symbol lists. Therefore,
TPC MYSTUFF /DIOCHECK/DDEBUG/DLIST

is equivalent to the first example.

Compiler mode
options

A few options affect how the compiler itself functions. These are
1M (Make), 18 (Build), IF (Find Error), IL (Link Buffer), and IQ

(Quiet). As with the other options, you can use the hyphen format
(remember to separate th~ options with at least one blank).

230

Programmer's Reference

The make (1M) option

TPC has a built-in MAKE utility to aid in project maintenance.


The 1M option instructs TPC to check all units upon which the file
being compiled depends.
A unit will be recompiled if
The source file for that unit has been modified since the .TPU
file was created.
Any file included with the $1 directive, or any .OBJ file linked in
by the $L directive, is newer than the unit's .TPU file.
The interface section of a unit referenced in a uses statement
has changed.

Units in TURBO.TPL are excluded from this process.

If you were applying this option to the previous example, the


command would be
TPC MYSTUFF 1M

The build all (lB) option


You can't use /M and /8 at
the same time.

Instead of relying on the 1M option to determine what needs to be


updated, you can tell TPC to update all units upon which your
program depends using the 18 option.

If you were using this option in the previous example, the


command would be
TPC MYSTUFF IB

The find error (IF)


option

When a program terminates due to a run-time error, it displays an


error code and the address (segment:offset) at which the error
occurred. By specifying that address in a /Fsegment:offset option,
you can locate the statement in the source text that caused the
error, provided your program and units were compiled with
debug information enabled (via the $0 compiler directive).
Suppose you have a file called TEST.PAS that contains the
following program:
program Test;
var
x : Real;
begin
x := 0;
x := x I x;
end

. Chapter 3, Command-line compiler

{ Force a divide by zero error }

231

First, compile this program using the command-line compiler:


TPC TEST

If you do a DIR TEST.*, DOS lists two files: TEST. PAS, your

source code, and TEST.EXE, the executable file.


Now, type TEST to run. You'll get a run-time error: "Run-time
error 200 at 0000:003D." Notice that you're given an error code
(200) and the address (0000:003D in hex) of the instruction pointer
(CS:IP) where the error occurred. To figure out which line in your
source caused the error, simply invoke the compiler, use IF and
specify the segment and offset as reported in the error message:
C:\>TPC TEST /FO:3D
Turbo Pascal 7.0 Copyright (c) 1983,92 Borland International
10/02/92 14:09:53
TEST.PAS(7)
TEST. PAS (6) : Target address found.
x := x / x;

In order for TPC to find the run-time error with IF, you must

compile the program with all the same command-line parameters


you used the first time you compiled it.
The compiler now gives you the file name and line number, and
points to the offending line number and text in your source code.
As mentioned previously, you must compile your program and
units with debug information enabled for TPC to be able to find
run-time errors. By default, all programs and units are compiled
with debug information enabled, but if you turn it off, using a
{$O-} compiler directive or a 1$0- option, TPC will not be able to
locate run-time errors.
The link buffer (fL)
option

The IL option disables buffering in memory when .TPU files are


linked to create an .EXE file. Turbo Pascal's built-in linker makes
two passes. In the first pass through the .TPU files, the linker
marks every procedure that gets called by other procedures. In
the second pass, it generates an .EXE file by extracting the marked
procedures from the .TPU files.
By default, the .TPU files are kept in memory between the two
passes; however, if the IL option is specified, they are read again
from disk during the second pass. The default method is faster
but requires more memory; for very large programs, you may
have to specify IL to link successfully.

232

Programmer's Reference

The quiet (lQ) option

The quiet mode option suppresses the printing of file names and
line numbers during compilation. When TPC is invoked with the
quiet mode option
TPC MYSTUFF /Q

its output is limited to the sign-on message and the usual statistics
at the end of compilation. If an error occurs, it will be reported.

Directory options
TPC supports several options that let you specify the five
directory lists used by TPC: TPL & CFG, EXE & TPU, Include,
Unit, and Object.
Excluding the EXE and TPU directory option, you may specify
one or multiple directories for each command-line directory
option. If you specify multiple directories, separate them with
semicolons (;). For example, this command line tells TPC to search
for Include files in C: \ TP \ INCLUDE and D: \ INC after searching
the current directory:
TPC MYSTUFF /IC:\TP\INCLUDEiD:\INC

If you specify multiple directives, the directory lists are


concatenated. Therefore,
TPC MYSTUFF /IC:\TP\INCLUDE /ID:\INC

is equivalent to the first example.

The TPL & CFG


directory (IT) option

TPC looks for two files when it is executed: TPC.CFG, the


configuration file, and TURBO.TPL, the resident library file. TPC
automatically searches the current directory and the directory
containing TPC.EXE. The IT option lets you specify other
directories in which to search. For example, you could say
TPC /TC:\TP\BIN MYSTUFF

If you want the IT option to affect the search for TPC.CFG, it must
be the very first command-line argument, as in the previous
example.

Chapter 3, Command-line compiler

233

The EXE & TPU . directory


(fE) option

This option lets you tell TPC where to put the .EXE and .TPU files
it creates. It takes a directory path as its argument:
TPC MYSTUFF /EC:\TP\BIN

You can specify only one EXE


and TPU directory

If no such option is given, TPC creates the .EXE and .TPU files in
the same directories as their corresponding source files.

The include directories


(fE) option

Turbo Pascal supports include files through the {$Ifilename}


compiler directive. The II option lets you specify a list of
directories in which to search for Include files.

The unit directories (fU)


option

When you compile a program that uses units, TPC first attempts
to find the units in TURBO.TPL (which is loaded along with
TPC.EXE). If they cannot be found there, TPC searches for
unitname.TPU in the current directory. The IU option lets you
specify additional directories in which to search for units.

The object files


directories (f0) option

Using {$L filename} compiler directives, Turbo Pascal lets you link
in .OBI files containing external assembly language routines, as
explained in Chapter 23, "Linking assembler code," in the
Language Guide. The 10 option lets you specify a list of directories
in which to search for such .OBI files.

Debug options
TPC has two command-line options that enable you to generate
debugging information: the map file option and the debugging
option.
The map file (fG)
option

Unlike the binary format of


.EXE and. TPU files, a .MAP file
is a legible text file that can
be output on a printer or
loaded into the editor.

The IG option instructs TPC to generate a .MAP file that shows


the layout of the .EXE file. The IG option must be followed by the .
letter S, P, or D to indicate the desired level of information in the
.MAP file. A .MAP file is divided into three sections:
Segment
Publics
Line Numbers
The IGS option outputs only the Segment section, IGP outputs the
Segment and Publics section, and IGO outputs all three sections.

234

Programmer's Reference

For modules (program and units) compiled in the {$O+,L+} state


(the default), the Publics section shows all global variables,
procedures, and functions, and the Line Numbers section shows
line numbers for all procedures and functions in the module. In
the {$D+,L-} state, only symbols defined in a unit's interface part
are listed in the Publics section. For modules compiled in the {$O-}
state, there are no entries in the Line Numbers section.
The debugging (IV)
option

When you specify the N option on the command line, TPC


appends Turbo Debugger-compatible debug information at the
end of the .EXE file. Turbo Debugger includes both source- and
machine-level debugging and powerful breakpoints including
breakpoints with conditionals or expressions attached to them.
Even though the debug information generated by N makes the
resulting .EXE file larger, it does not affect the actual code in the
.EXE file, and if it is executed, the .EXE file does not require
additional memory.
The extent of debug information appended to the .EXE file
depends on the setting of the $0 and $L compiler directives in
each of the modules (program and units) that make up the
application. For modules compiled in the {$O+,L+} state, which is
the default, all constant, variable, type, procedure, and function
symbols become known to the debugger. In the {$O+,L-} state,
only symbols defined in a unit's interface section become known
to the debugger. In the {$O-} state, no line-number records are
generated, so the debugger cannot display source lines when you
debug the application.

The TPC,CFG file


You can set up a list of options in a configuration file called
TPC.CFG, which will then be used in addition to the options
entered on the command line. Each line in TPC.CFG corresponds
to an extra command-line argument inserted before the actual
command-line arguments. Thus, by creating a TPC.CFG file, you
can change the default setting of any command-line option.
TPC lets you enter the same command-line option several times,
ignoring all but the last occurrence. This way, even though you've
changed some settings with a TPC.CFG file, you can still override
them on the command line.

Chapter 3, Command-line compiler

235

When TPC starts, it looks for TPC.CFG in the current directory. If


the file isn't found there, TPC looks in the directory where
TPC.EXE resides. To force TPC to look in a specific list of
directori~s (in addition to the current directory), specify a rr
command-line option as the first option on the command line.
If TPC.CFG contains a line that does not start with a slash (I) or a
hyphen (-), that line defines a default file name to compile. In that
case, starting TPC with an empty command line (or with a
command line consisting of command-line options only and no
file name) will cause it to compile the default file name, instead of
displaying a syntax summary.

Here's an example TPC.CFG file, defining some default directories


for include, object, and unit files, and changing the default states
of the $F and $S compiler directives:
/IC:\TP\INCiC:\TP\SRC
/OC:\TP\ASM
/UC:\TP\UNIT
/$F+
/$s-

Now, if you type


TPC .MYSTUFF

at the system prompt, TPC acts as if you had typed in the


following:
TPC /IC:\TP\INCiC:\TP\SRC /OC:\TP\ASM /UC:\TP\UNIT /$F+ /$S- MYSTUFF

236

Programmer's Reference

Error messages
This chapter describes the possible e~ror messages you can get
from Turbo Pascal during program development. The error
messages are grouped according to the categories listed in
Table 4.1. Run-time errors are subdivided.into DOS, I/O, critical,
and fatal errors. Within each of the groups, the errors are listed in
numerical order.
Table 4.1
Error message types

Type of message

Page

Compiler

See page 238.

DOS

See page 258.

I/O

See page 260.

Critical

See page 261.

Fatal

See page 261.

Compiler error messages


Whenever possible, the compiler will display additional
diagnostic information in the form of an identifier or a file name.
For example,
Error 15: File not found (GRAPH.TPU).

When an error is detected, Turbo Pascal (in the IDE) automatically


loads the source file and places the cursor at the error. The '
command-line compiler displays the error message and number

Chapter 4, Error messages

237

and the source line, and uses a caret (/\) to indicate where the
error occurred. Note, however, that some errors are not detected
until a little later in the source text. For example, a type mismatch
in an assignment statement cannot be detected until the entire
expression after the := has been evaluated. In such cases, look for
the error to the left of or above the cursor.
1. Out of memory.

This error occurs when the compiler runs out of memory. Try
these possible solutions:
If Compile I Destination is set to Memory, set it to Disk in the
integrated environment.
If Options I Linker I Link Buffer is set to Memory, toggle it to
Disk. Use a IL option to place the link buffer on disk when
using the command-line compiler.
If these suggestions don't help, your program or unit might
simply be too large to compile in the amount of memory available, and you might have to break it into two or more smaller
units.
2 Identifier expected.

An identifier was expected at this point. You might be trying to


redeclare a reserved word.
3 Unknown identifier.

This identifier has not been declared, or might not be visible


within the current scope.
4 Duplicate identifier.

The identifier already represents a program or unit's name, a


constant, a variable, a type, aprocedure, or a function declared
within the current block.
5 Syntax error.

An illegal character was found in the source text. You might have
forgotten the quotes around a string constant.

238

Programmer's Reference

6 Error in real constant.

The syntax of type constants is defined in Chapter 2, "Tokens," in


the Language Guide.
7 Error in integer constant.

The syntax of integer-type constants is defined in Chapter 2,


"Tokens," in the Language Guide. Note that whole real numbers
outside the maximum integer range must be followed by a
decimal point and a zero; for example, 12345678912.0.
8 String constant exceeds line.

You have most likely forgotten the ending quote in a string


constant.
10 Unexpected end of file.

You might have gotten this error message for one of the following
reasons:
Your source file ends before the final end of the main statement
part. Most likely, your begin and end statements do not match.
An Include file ends in the middle of a statement part. Every
statement part must be entirely contained in one file.
You didn't close a comment.
11 Line too long.

The maximum line length is 127 characters.


12 Type identifier expected.

The identifier does not denote a type as it should.


13 Too many open files.

If this error occurs, your CONFIG.syS file does not include a


FILES=xx entry or the entry specifies too few files. Increase the
number to some suitable value, such as 20.

Chapter 4, Error messages

, 239

14 Invalid file name.

The file name is invalid or specifies a nonexistent path.


15 File not found.

The compiler could not find the file in the current directory or in
any of the search directories that apply to this type of file.
16 Disk full.

Delete some files or use a different disk.


17 Invalid compiler directive.

The compiler directive letter is unknown, one of the compiler


directive parameters is invalid, or you are using a global compiler
directive when compilation of the body of the program has
begun.
18 Too many files.

There are too many files involved in the compilation of the


program or unit. Try to use fewer files. For example, you could
merge include files. You could also shorten the file names or
move all the files into one directory and make it the current
directory at compile time.
19 Undefined type in pointer definition.

The type was referenced in a pointer-type declaration previously,


but it was never declared.
20 Variable identifier expected.

The identifier does not denote a variable as it should.


21 Error in type.

This symbol cannot start a type definition.


22 Structure too large.

The maximum allowable size of a structured type is 65,535 bytes.

240

Programmer's Reference

23 Set base type out of range.

The base type of a set must be a subrange with bounds in the


range 0.. 255 or an enumerated type with no more than 256
possible values.
24 File components may not be files or objects.
file of file and file of object constructs are not allowed; nor is a file

of any structured type that includes an object type or file type.


25 Invalid string length.

The declared maximum length of a string must be in the range


1..255.
26 Type mismatch.

This is due to one of the following:


Incompatible types of the variable and the expression in an
assignment statement
Incompatible types of the actual and formal parameter in a call
to a procedure or function
An expression type that is incompatible with the index type in
array indexing
Incompatible types of operands in an expression
27 Invalid subrange base type.

All ordinal types are valid base types.


28 Lower bound greater than upper bound.

The declaration of a subrange type specifies a lower bound


greater than the upper bound.
29 Ordinal type expected.

Real types, string types, structured types, and pointer types are
not allowed here.
30 Integer constant expected.

Chapter 4, Error messages

241

31 Constant expected.
32 Integer or real constant expected.
33 Pointer type identifier expected.

The identifier does not denote a pointer type as it should.


34 Invalid function result type.

Valid function result types are all simple types, string types, and
pointer types.
35 . Label identifier expected.

The identifier does not denote a label as it should.


36 BEGIN expected.

A begin is expected here, or there is an error in the block structure


of the unit or program.
37 END expected.

An end is expected here, or there is an error in the block structure


of the unit or program.
38 Integer expression expected.

The preceding expression must be of an integer type.


39 Ordinal expression expected.

The preceding expression must be of an ordinal type.


40 Boolean expression expected.

The preceding expression must be of a boolean type.


41 Operand types do not match operator.

The operator cannot be applieq./ to operands of this type, for


example, 'A' div '2'.

242

Programmer's Reference

42 Error in expression.

This symbol cannot participate in an expression in the way it


does. You might have forgotten to write an operator between two
operands.
43 Illegal assignment.

Files and untyped variables cannot be assigned values .


A function identifier can only be assigned values within the
statement part of the function.
44 Field identifier expected.

The identifier does not denote a field in the corresponding record


or object variable.
45 Object file too large.

Turbo Pascal cannot link in .OB] files larger than 64K.


46 Undefined external.

The external procedure or function did not have a matching


PUBLIC definition in an object file. Make sure you have specified
all object files in {$Lfilename} directives, and check the spelling of
the procedure or function identifier in the .ASM file.
47 Invalid object file record.

The .OB] file contains an invalid object record; make sure. the file
is in fact an .OB] file.
48 Code segment too large.

The maximum size of the code of a program or unit is 65,520


bytes. If you are compiling a program, move some procedures or
functions into a unit. If you are compiling a unit, break it into two
or more units.

Chapter 4, Error messages

243

, 49 Data segment too large.

The maximum size of a program's data segment is 65,520 bytes,


including data declared by the used units. If you need more
global data than this, declare the larger structures as pointers, and
allocate them dynamically using the New procedure.
50 DO expected.

The reserved word do does not appear w~ere it should;


51 Invalid PUBLIC definition.

Two or more PUBLIC directives in assembly language define


the same identifier.
The .OBJ file defines PUBLIC symbols that do not reside inthe
CODE segment.
52 Invalid EXTRN definition.

The identifier was referred to through an EXTRN directive in


assembly language, but it is not declared in the Pascal program
or unit, nor in the interface part of any of the used units.
The identifier denotes an absolute variable.
The identifier denotes an inline procedure or function.
53 Too many EXTRN definitions.

Turbo Pascal cannot handle .OBJ files with more than 256 EXTRN
definitions.
54 OF expected.

The reserved word of does not appear where it should.


55 INTERFACE expected.

The reserved word interface does not appear where it should.


56 Invalid relocatable reference.

The .OBJ file contains data and relocatable references in


segments other than CODE. For example, you are attempting to
declare initialized variables in the DATA segment.

244

Programmer's Reference

The .OBI file contains byte-sized references to relocatable


symbols. This error occurs if you use the HIGH and LOW
operators w.ith relocatable symbols or if you refer to relocatable
symbols in DB directives.
An operand refers to a relocatable symbol that was not defined
in the CODE segment or in the DATA segment.
An operand refers to an EXTRN procedure or function with an
offset, for example, CALL SortProc+S.
57 THEN expected.

The reserved word then does not appear where it should.


58 TO or DOWNTO expected.

The reserved word to or downto does not appear where it should.


59 Undefined forward.

The procedure or function was declared in the interface part of


a unit, but its definition never occurred in the implementation
part.
The procedure or function was declared with forward, but its
definition was never found.
61 Invalid typecast.

The sizes of the variable reference and the destination type


differ in a variable typecast.
You are attempting to typecast an expression where only a
variable reference is allowed.
62 Division by zero.

The preceding operand attempts to divide by zero.


63 Invalid file type.

The file type is not supported by the file-handling procedure; for


example, Readln with a typed file or Seek with a text file.

Chapter 4, Error messages

245

64 Cannot Read or Write variables of this type .

Read and Readln can input variables of character, integer, real,


and string types .
Write and Writeln can output variables of character, integer, real,
string, and boolean types.
65 Pointer variable expected.

The preceding variable must be of a pointer type.


66 String variable expected.

The preceding variable must be of a string type.


67 String expression expected.

The pr,eceding expression must be of a string type.


68 Circular unit reference.

Two units are not allowed to use each other in the interface part.
It is legal for two units to use each other in the implementation
part. Rearrange your uses clauses so that circular references occur
only in the implementation parts. For more details, see "Circular
unit references" in Chapter 10 in the Language Guide.
69 Unit name mismatch.

The name of the unit found in the .TPU file does not match the
name specified in the uses clause.
70 Unit version mismatch.

One or more of the units used by this unit have been changed
since the unit was compiled. Use Compile I Make or Compile I
Build in the IDE and 1M or IB options in the command-line
compiler to automatically compile units that need recompilation.
71 Internal stack overflow.

The compiler's. internal stack is exhausted due to too many levels


of nested statements. Rearrange your code so it is not nested so
deeply. For example, move the inner levels of nested statements
into a separate procedure.

246

Programmer's Reference

72 Unit file format error.

The ~ TPU file is somehow invalid; make sure it is in fact a .TPU


file. The. TPU file might have been created with an older version
of Turbo Pascal. In this case, a new .TPU must be created by
recompiling the source file.
73 IMPLEMENTATION expected.

The reserved word implementation does not appear where it


should. You are probably including the implementation of a
procedure, function, or method in the interface part of the unit.
74 Constant and case types do not match.

The type of the case constant is incompatible with the case


statement's selector expression.
75 Record or object variable expected.

The preceding variable must be of a record or object type.


76 Constant out of range.

You are trying to


Index an array with an out-of-range constant
Assign an out-of-range constant to a variable
Pass an out-of-range constant as a parameter to a procedure or
function
77 File variable expected.

The preceding variable must be of a file type.


78 Pointer expression expected.

The preceding expression must be of a pointer type.


79 Integer or real expression expected.

The preceding expression must be of an integer or a real type.

Chapter 4, Error messages

247

80 Label not within current block.

A goto statement cannot reference a label outside the current


block.
81 Label already defined.

The label already marks a statement. .


82 Undefined label in preceding statement part.

The label was declared and referenced in the preceding statement


part, but it :was never defined.
83 Invalid

argument.

Valid arguments are variable references and procedure or


function identifiers.
84 UNIT expected.

The reserved word unit does not appear where it should.


85 ";" expected.

A semicolon does not appear where it should.


86 ":" expected.

A colon does not appear where it should.


87 "," expected.

A comma does not appear where it should.


88 . "(" expected.

An opening parenthesis does not appear where it should.


89 ")" expected.

A closing parenthesis does not appear where it should.

248

Programmer's Reference

90

"=" expected.

An equal sign does not appear where it should.


91 ":=" expected.

An assignment operator does not appear where it should.


92 "[" or "(." expected.

A left bracket does not appear where it should.


93 "]" or ".)" expected.

A right bracket does not appear where it should.


94 "." expected.

A period does not appear where it should. Check to make sure


that a type is not being used as a variable or that the name of the
program does not override an important identifier from another
unit.
95 " .. " expected.

A subrange does not appear where it should.


96 Too many variables .

The total size of the global variables declared within a program


or unit cannot exceed 64K .
The total size of the local variables declared within a procedure
or function cannot exceed 64K.
97 Invalid FOR control variable.

The for statement control variable must be a simple variable


defined in the declaration part of the current subprogram.
98 Integer variable expected.

The' preceding variable must be of an integer type.

Chapter 4, Error messages

249

99 File types are not allowed here.

A typed constant cannot be of a file type.


100 String length mismatch.

The length of the string constant does not match the number of
components in the character array.
101 Invalid ordering of ,fields.

The fields of a record- or object-type constant must be written in


the order of declaration.
102 String constant expected.

A string constant does not appear where it should.


103 Integer or real variable expected.

The preceding variable must be of an integer or real type.


104 Ordinal variable expected.

The preceding variable must be of an ordinal type.


105 INLINE error.

The < operator is not allowed in conjunction with relocatable


references to variables-such references are always word-sized.
106 Character expression expected.

The preceding expression must be of a character type.


107 Too many relocation items.

The size of the relocation table part of the .EXE file exceeds 64K,
which is Turbo Pascal's upper limit. If you encounter this error,
your program is simply too big for Turbo Pascal's linker to
handle. It is probably also too big for DOS to execute. You will
have to split the program into a "main" part that executes two or
more "subprogram" parts using the Exec procedure in the Dos
unit.

250

Programmer's Reference

108 Overflow in arithmetic operation.

The result of the preceding arithmetic operation is not in the


Longint range (-2147483648 .. 2147483647). Correct the operation or
use real-type values instead of integer-type values.
109 No enclosing FOR, WHILE, or REPEAT statement.

The Break and Continue standard procedures cannot be used


outside a for, while, or repeat statement.
112 CASE constant out of range.

For integer-type case statements, the constants must be within


the range -32768 ..32767.
113 Error in statement.

This symbol cannot start a statement.


114 Cannot call an interrupt procedure.

You cannot directly call an interrupt procedure.


116 Must be in 8087 mode to compile this.

This construct can only be compiled in the {$N+} state. Operations


on the 80x87 real types (Single, Double, Extended, and Comp) are
not allowed in the {$N-} state.
117 Target address not found.

The Search I Find Error command in the IDE or the IF option in


the command-line version could not locate a statement that
corresponds to the specified address.
118 Include files are not allowed here.

Every statement part must be entirely contained in one file.


119 No inherited methods are accessible here.

You are using the inherited keyword outside a method or in a


method of an object type that has no ancestor.

Chapter 4, Error messages

251

121 Invalid qualifier.

You are trying to do one of the following:


Index a variable that is not an array.
Specify fields in a variable that is not a record.
Dereference a variable that is not a pointer.
122 Invalid variable reference.

The preceding construct follows the syntax of a variable reference,


but it does not denote a memory location. Most likely, you are
trying to modify a const parameter, or you are calling a pointer
function but forgetting to dereference the result.
123 Too many symbols.

The program or unit declares more than 64K of symbols. If you


are compiling with {$D+},try turning it off-note, however, that
this will prevent you from finding run-time errors in that module.
Otherwise, you could try moving some declarations into a
separate unit.
124 Statement part too large.

Turbo Pascal limits the size of a statement part to about 24K. If


you encounter this error, move sections of the statement part into
one or more procedures. In any case, with a statement part of that
size, it's worth the effort to clarify the structure of your program.
126 Files must be var parameters.

You are attempting to declare a file-type value parameter. Filetype parameters must be var parameters.
127 Too many conditional symbols.

There is not enough room to define further conditional symbols.


Try to eliminate some symbols, or shorten some of the symbolic
names.

252

Programmer:S Reference

128 Misplaced conditional directive.

The compiler encountered an {$ELSE} or {$ENOIF} directive


without a matching {$IFDEF}, {$IFNOEF}, or {$IFOPT} directive.
129 ENOIF directive missing.

The source file ended within a conditional compilation construct.


There must be an equal number of {$IFxxx}s and {$ENOIF}s in a
source file.
130 Error in initial conditional defines.

The initial conditional symbols specified in Options I Compiler I


Conditional Defines (in the IDE) or in a 10 directive (with the
command-line compiler) are invalid. Turbo Pascal expects zero or
more identifiers separated by blanks, commas, or semicolons.
131 Header does not match previous definition.

The procedure or function header specified in the interface part or


forward declaration does not match this header.
133 Cannot evaluate this expression.

You are attempting to use a non-supported feature in a constant


expression. For example, you're attempting to use the Sin function
in a const declaration. For a description of the allowed syntax of
constant expressions, see Chapter 3, "Constants," in the Language
Guide.
134 Expression incorrectly terminated.
Integrated debugger only

Turbo Pascal expects either an operator or the end of the


expression at this point, but found neither.
135 Invalid format specifier.

Integrated debugger only

Chapter 4, Error messages

You are using an invalid format specifier, or the numeric


argument of a format specifier is out of range. For a list of valid
format specifiers, see Chapter 5, "Debugging in the IDE," in the
User's Guide.

253

136 Invalid indirect reference.

The statement attempts to make an invalid indirect reference. For


example, you are using an absolute variable whose base variable
is not known in the current module, or you are using an inline
routine that references a variable not known in the ~urrent
module.
137 Structured variables are not allowed here.

You are attempting to perform a non-supported operation on a


structured variable. For example, you are trying to multiply two
records.
138 Cannot evaluate without system unit.
Integrated debugger only

Your TURBO. TPL library must contain the System unit for the
debugger to be able to evaluate expressions.
139 Cannot access this symbol.

Integrated debugger only

A program's entire set of symbols is available as soon as you have


compiled the program. However, certain symbols, such as
variables, cannot be accessed until you actually run the program.
140 Invalid floating-point operation.

An operation on two real type values produced an overflow or a


division by zero.
141 Cannot compile overlays to memory.

A program that uses overlays must be compiled to disk.


142 Pointer or procedural variable expected.

The Assigned standard function requires the argument to be a


variable of a pointer or procedural type.
143 ,Invalid procedure or function reference .

You are attempting to call a procedure in an expression.


If you are going to assign a procedure or function to a
procedural variable, it must be compiled in the {$F+} state and
cannot be declared with inline or interrupt.

254

Programmer's Reference

144 Cannot overlay this unit.

You are attempting to overlay a unit that wasn't compiled in the


{O+} state.
146 File access denied.

The file could not be opened or created. Most likely, the compiler
is trying to write to a read-only file.
147 Object type expected.

The identifier does not denote an object type.


148 Local object types are not allowed.

Object types can be defined only in the outermost scope of a


program or unit. Object-type definitions within procedures and
functions are not allowed.
149 VIRTUAL expected.

The reserved word virtual is missing.


150 Method identifier expected.

The identifier does not denote a method.


151 Virtual constructors are not allowed.

A constructor method must be static.


152 Constructor identifier expected.

The identifier does not denote a constructor.


153 Destructor identifier expected.

The identifier does not denote a destructor.


154 Fail only allowed within constructors.

The Fail standard procedure can be used only within constructors.

Chapter 4, Error messages

255

155 Invalid combination of opcode and operands.

The assembler ope ode does not accept this combination of


operands. Possible causes are:
There are too many or too few operands for this assembler
opcode; for example, INC AX,BX or MOV AX .
The number of operands is correct, bl1-t their types or order do
not match the opcode; for example, DEC 1, MOV AX,CL or
MOV 1,AX.
156 Memory reference expected.

The assembler operand is not a memory reference, which is


required here.\Most likely you have forgotten to put square
brackets around an index register operand, for example,
MOV AX,BX+SI instead of MOV AX,[BX+SI].
157 Cannot add or subtract relocatable symbols.

The only arithmetic operation that can be performed on a


relocc:ttable symbol in an assembler operand is addition or
subtraction of a constant. Variables, procedures, functions, and
labels are relocatable symbols. Assuming that Var is a variable
and Const is a constant, then the instructions MOV P:I.., Const+Const
and MOV P:I.., Var+Const are valid, but MOV P:I.., VartVar is not.
158 Invalid register combination.

Valid index register combinations are [BX], [BP], [SI], [DI],


[BX+SI], [BX+DI], [BP+SI], and [BP+DI]. Other index register
combinations (such as [AX], [BP+BX], and [SI+DX]) are not
allowed.
Local variables (variables declared in procedures and functions)
are always allocated on the stack and accessed via the BP register.
The assembler automatically adds rBP] in references to such variables, so even though a construct like Local[BX] (where Local is a
local variable) appears valid, it is not since the final operand
would become Local[BP+BX].

256

Programmer's Reference

159 286/287 instructions are not enabled.

Use a {$G+} compiler directive to enable 286/287 opcodes, but be


aware that the resulting code cannot be run on 8086- and 8088based machines.
160 Invalid symbol reference.

This symbol cannot be accessed in an assembler operand. Possible


causes. follow:
You are attempting to access a standard procedure, a standard
function, or the Mem, MemW, MemL, Port, or PortW special
arrays in an assembler operand.
You are attempting to access a string, floating-point, or set
constant in an assembler operand.
You are attempting to access an inline procedure or function in
an assembler operand.
You are attempting to access the @Result special symbol outside
a function.
You are attempting to generate a short JMP instruction that
jumps to something other than a label.
161 Code generation error.

The preceding statement part contains a LOOPNE, LOOPE, lOOP,


or JCXZ instruction that cannot reach its target label.
162 ASM expected.

You are attempting to compile a built-in assembler function or


procedure that contains a begin ... end statement instead of
asm ... end.

Run-time errors
Certain errors at run time cause the program to display an error
message and terminate:
Run-time error nnn at xxxx:yyyy

where nnn is the run-time error number, and xxxx:yyyy is the


run-time error address (segment and offset).

Chapter 4, Error messages

257

The run-time errors are divided into four categories: DOS errors, 1
through 99; I/O errors, 100 through 149, critical errors, 150
through 199; and fatal errors, 200 through 255.

DOS errors
1 Invalid function number.

You made a call to a nonexistent DOS function.


2 File not found.

Reported by Reset, Append, Rename, Rewrite if the file name is


invalid, or Erase if the name assigned to the file variable does not
specify an existing file.
3 Path not found.

Reported by Reset, Rewrite, Append, Rename, or Erase if the name


assigned to the file variable is invalid or specifies a nonexistent
subdirectory.
Reported by ChDir, MkDir, or RmDir if the path is invalid or
specifies a nonexistent subdirectory.
4 Too many open files.

Reported by Reset, Rewrite, or Append if the program has too many


open files. DOS never allows more than 15 open files per process.
If you get this error with less than 15 open files, it might indicate
that the CONFIG5YS file does not include a FILES=xx entry or
that the entry specifies too few files. Increase the number to some
suitable value, such as 20.
5 File access denied.

Reported by Reset or Append if FileMode allows writing and the


name assigned to the file variable specifies a directory or a
read-only file.
Reported by Rewrite if the directory is full or if the name
assigned to the file variable specifies a directory or an existing
read-only file.
Reported by Rename if the name assigned to the file variable
specifies a directory or if the new name specifies an existing file.

258

Programmer's Reference

Reported by Erase if the name assigned to the file variable


specifies a directory or a read-only file.
Reported by MkDir if a file with the same name exists in the
parent directory, if there is no room in the parent directory, or if
the path specifies a device.
Reported by RmDir if the directory isn't empty, if the path
doesn't specify a directory, or if the path specifies the root
directory.
Reported by Read or BlockRead on a typed or untyped file if the
file is not open for reading.
Reported by Write or BlockWrite on a typed or untyped file if the
file is not open for writing.
6 Invalid file handle.

This error is reported if an invalid file handle is passed to a DOS


system call. It should never occur; if it does, it is an indication that
the file variable is somehow trashed.
12 Invalid file access code.

Reported by Reset or Append on a typed or untyped file if the


value of FileMode is invalid.
15 Invalid drive number.

Reported by GetDir or ChDir if the drive number is invalid.


16 Cannot remove current directory.

Reported by RmDir if the path specifies the current directory.


17 Cannot rename across drives.

Reported by Rename if both names are not on the same drive.


18 No more files.

Reported by the DosError variable in the Dos and WinDos units


when a call to Fi'ndFirst or FindNext finds no files matching the
specified file name and set of attributes.

Chapter 4, Error messages

259

I/O errors
These errors cause termination if the particular statement was
compiled in the {$I+} state. In the {$I-} state, the program
continues to execute, and the error is reported by the IOResult
function.
100 Disk read error.

Reported by Read on a typed file if you attempt to read past the


end of the file.
101 Disk write error.

Reported by Close, Write, Writeln, or Flush if the disk becomes full.


102 File not assigned.

Reported by Reset, Rewrite, Append, Rename, and Erase if the file


variable has not been assigned a name through a call to Assign.
103 File not open.

Reported by Close, Read, Write, Seek, Eof, FilePos, FileSize, Flush,


BlockRead, or BlockWrite if the file is not open.
104 File not open for input.

Reported by Read, Readln, Eof, Eoln, SeekEof, or SeekEoln on a text


file if the file is not open for input.
105 File not open for output.

Reported by Write and Writeln on a text file if the file is not open
for output.
106 Invalid numeric format.

Reported by Read or Readln if a numeric value read from a text file


does not conform to the proper numeric format.

260

Programmer's Reference

Critical Errors
For more information about these errors, see your DOS
programmer's reference manual.
150 Disk is write protected.
151 Unknown unit.
152 Drive not ready.
153 Unknown command.
154 CRC error in data.
155 Bad

driv~

request structure length.

156 Disk seek error.


157 Unknown media type.
158 Sector not found.
159 Printer out of paper.
160 Device write fault.
161 Device read fault.
162 Hardware failure.

Dos reports this error as a result of sharing violations and various


network errors.

Fatal errors
These errors always immediately terminate the program.
200 Division by zero.

The program attempted to divide a number by zero during a I,


mod, or div operation.
201 Range check error.

This error is reported by statements compiled in the {$R+} state


when one of the following situations arises:
The index expression of an array qualifier was out of range .
You attempted to assign an out-of-range value to a variable.

Chapter 4, Error messages

261

You attempted to assign an out-of-range value as a parameter


to a procedure or function.
202 Stack overflow error.

This error is reported on entry to a procedure or function compiled in the {$S+} state when there is not enough stack space to
allocate.the subprogram's local variables. Increase the size of the
stack by using the $M compiler directive.
This error might also be caused by infinite recursion, or by an
assembly language procedure that d()es not maintain the stack
properly.
203 Heap overflow error.

This error is reported by New or GetMem when there is not


enough free space in the heap to allocate a block of the requested
size.
For a complete discussion of the heap manager, see Chapter 19,
"Memory issues," in the Language Guide.
204 Invalid pointer operation.

This error is reported by Dispose or FreeMem if the pointer is nil or


points to a location outside the heap .
.205 Floating point overflow.

A floating-point operation produced a number too large for Turbo


Pascal or the numeric coprocessor (if any) to handle.
206 Floating point underflow.

A floating-point operation produced an underflow. This error is


only reported if you are using the 8087 numeric coprocessor with
a control word that unmasks underflow exceptions. By default, an
underflow causes a result of zero to be returned.
207 Invalid floating point operation .

The real value passed to Trunc or Round could not be converted


to an integer within the Longint range (-2,147,483,648 to
2,147,483,647).

262

Programmer's Reference

The argument passed to the Sqrt function was negative.


The argument passed to the Ln function was zero or negative.
An 8087 stack overflow occurred. For further details on
correctly programming the 8087, see Chapter 14, "Using the
80x87," in the Language Guide.
208 Overlay manager not installed.

Your program is calling an overlaid procedure or function, but the


overlay manager is not installed. Most likely, you are not calling
Ovrlnit, or the call to Ovrlnit failed. Note that, it you have
initialization code in any of your overlaid units, you must create
an additional non-overlaid unit which callsOvrlnit, and use that
unit before any of the overlaid units.
209 Overlay file read error.

A read error occurred when the overlay manager tried to read an


overlay from the overlay file.
210 Object not initialized.

With range-checking on, you made a call to an object's virtual


method, before the object had been initialized via a constructor
call.
211 Call to abstract method.

This error is generated by the Abstract procedure in the Objects


unit; it indicates that your program tried to execute an abstract
virtual method. When an object type contains one or more
abstract methods it is called an abstract object type. It is an error to
instantiate objects of an abstract type-abstract object types exist
only so that you can inherit from them and override the abstract
methods.
For example, the Compare method of the TSortedCollection type in
the Objects unit is abstract, indicating that to implement a sorted
collection you must create an object type that inherits from
TSortedCollection and overrides the Compare method.

Chapter 4, Error messages

263

212 Stream registration error.

This error is generated by the RegisterType procedure in the


Objects unit indicating that one of the following errors has
occurred:
The stream registration record does not reside in the data
segment.
The ObjType field of the stream registration record is zero.
The type has already been registered.
Another type with the same ObjType value already exists.
213 Collection index out of range.

The index passed to a method of a TCollection is out of range.


214 . Collection overflow error.

The error is reported by a TCollection if an attempt is made to add


an element when the collection cannot be expanded.
215 Arithmetic overflow error.

This error is reported by statements compiled in the {$Q+} state


when an integer arithmetic operation caused an overflow such as
when the result of the operation was outside the supported ~ange.
I

264

Programmer's Reference

A
Editor reference
The tables in this appendix list all the available editing commands
you can use in the Turbo Pascal IDE. If two sets of key
combina tions can be used for a single command, the second set is
listed as an alternate key combination. Footnoted references in
Table A.l mark those commands that are described in depth in
Tables A.2, A.3, and A.4.

Appendix A, Editor reference

265

Table Al
Editing commands

Command

Keys

Alternate Keys

Ctrl+S
Ctrl+D
Ctrl+A
Ctrl+F
Ctrl+E
Ctrl+X

Cursor movement commands

Character left
, Character right
Word left
Word right
Lineup
Line down
Scroll up one line
Scroll down one line
Page up
Page down
Beginning of line

A word is defined as a
sequence of characters
separated by one of the
fol/owing: space < > , ;
.()()/\'*+-/$

#=I-?'''%&':
@ \,

and aI/ control and


graphic characters.

End of line
Top of window
Bottom of window
Top of file,
Bottom of file
Move to previous position

Ctrl+~
Ctrl+~

,t
Ctrl+W
Ctrl+Z
PgUp
PgDn
Home
Ctrl+Q S
End
Ctrl+Q D
Ctrl+Q E
Ctrl+QX
Ctrl+Q R
Ctrl+Q C
Ctrl+Q P

Ctrl+R
Ctrl+C

Ctrl+Home
Ctrl+End
Ctrl+PgUp
Ctrl+PgDn

-Insert and delete commands

Delete character
Delete character to left
Delete line
Delete to end of line
Delete to end of word
Insert newline
Insert mode on/off

Del
Backspace
Shift+Tab
Ctrl+Y
Ctrl+Q Y
Ctrl+T
Ctrl+N
Ins

Ctrl+G
Ctrl+H

Ctrl+V

Block commands

Move to beginning of block


Move to end of block
Set beginning of block
Set end of block
Exit to menu bar
Hide/Show block
Mark line
Print selected block
Mark word
Delete block

*
t

:j:

266

Ctrl+Q B
Ctrl+Q K
Ctrl+K B
Ctrl+K K
Ctrl+K D
Ctrl+KH
Ctrl+K L
Ctrl+KP
Ctrl+KT
Ctrl+KY

n represents a number from 0 to 9.


Enter control characters by first pressing Ctrl+P, then pressing the desired
control character.
See Table A.2.
See Table A.3.
See Table A.4.

Programmer's Reference

Table A.l: Editing commands (continued)


Command

Keys

Copy block
Move block
Copy to Clipboard :j:
Cut to Clipboard :j:
Delete block :j:
Indent block
Paste from Clipboard :j:
Read block from disk :j:
Unindent block
Write block to disk:j:

Ctr/tK C
Ctr/tK V
Ctr/t/ns
ShifttDe/
Ctr/tDe/
Ctr/tK /
Shiftt/ns
Ctr/tK R
Ctr/tK U
Ctr/tKW

Alternate Keys

Extending selected blocks

Left one character


Right one character
End of line
Beginning of line
Same column on next line
Same column on previous line
One page down
One page up
Left on~ word
Right one word
End of file
Beginning of file

Shiftt fShiftt ~
ShifttEnd
ShifttHome
Shiftt .t
Shiftt l'
ShifttPgDn
ShifttPgUp
ShifttCtr/t fShifttCtr/t ~
ShifttCtr/tEnd
ShifttCtr/tHome

ShifttCtr/tPgDn
ShifttCtr/tPgUp

Other editing commands

Autoindent mode on/off #


Cursor through tabs on/off #
Exit the IDE
Find place marker #
Help
Help index
Insert control character
Maximize window
Open file #
Optimal fill mode on/off #
Pair matching
Save file #
Search
Search again
Search and replace

Appendix A, Editor reference

Ctr/tO /
Ctr/tO R
A/ttX
Ctr/tOn *
F1
ShifttF1
Ctr/tpt
F5
F3
Ctr/tO F
Ctr/tO [,
Ctr/tO J
Ctr/tK S
Ctr/tO F

F2

Ctr/+L
Ctr/tOA

n represents a number from 0 to 9.


Enter control characters by first pressing Ctr/+P, then pressing the desired
control character.
See Table A.2.
See Table A.3.
See Table A.4.

267

Table A.l: Editing commands (continued)

*
t

Command

Keys

Alternate Keys

Set marker #
Tabs mode on/off #
Topic search help
Undo
Unindent mode on/off #
Display compiler directives

Ctrl+K n *
Ctrl+O T
Ctrl+F1
Alt+Backspace
Ctrl+O U
Ctrl+O 0

n represents a number from 0 to 9.


Enter control characters by first pressing Ctr/+P, then pressing the desired
control character.
See Table A.2.
See Table A.3.
See Table A.4.

Table A.2: Block commands in depth


Command

Keys

Function

Copy to Clipboard and


Paste from Clipboard

Ctrl+lns,
Shift+lns

Copies a previously selected block to the Clipboard


and, after you move your cursor to where you want the
text to appear, pastes it to the new cursor position. The
original block is unchanged. If no block is selected,
nothing happens.

Copy to Clipboard

Ctrl+lns

Copies selected text to the Clipboard.

Cut to Clipboard

Shift+Del

Cuts selected text to the Clipboard.

Delete block

Ctrl+Del

Deletes a selected block. You can "undelete" a


block with Undo.

Cut to Clipboard and


Paste from Clipboard

Shift+Del,
Shift+lns

Moves a previously selected block from its original


position to the Clipboard and, after you move your
cursor to where you want the text to appear, pastes it to
the new cursor position. The block disappears from its
original position. If no block is selected, nothing happens.

Paste from
Clipboard

Shift+lns

Pastes the contents of the Clipboard.

Read block
from disk

Ctrl+K R

Reads a disk file into the current text at the cursor


position exactly as if it were a block. The text read is then
selected as a block. When this command is issued, you
are prompted for the name of the file to read. You can
use wildcards to select a file toread; a directory is
displayed. The file specified can be any legal file name.

Write block
to disk

Ctrl+KW

Writes a selected block to a file. When you give this


command, you are prompted for the name of the file to
write to. The file can be given any legal name (the default
extension is PAS). If you prefer to use a file name without
an extension, append a period to the end of its name.

268

Programmer's Reference

If you have used Borland editors in the past, you might prefer to
use the block commands listed in the following table.
Table A.3
Borland-style block
commands
Selected text is highlighted
only if both the beginning
and end have been set and
the beginning comes before
the end.

Editor commands
in depth

Command

Keys

Function

Set beginning of block Ctr/+K B Begin selection of text.


Set end of block

Ctr/+KK End selection of text.

Hide/show block

Ctr/+K H Alternately displays and hides selected


text.

Copy block

Ctr/+K C Copies the selected text to the position


of the cursor. Useful only with the
Persistent Block option.

Move block

Ctr/+K V Moves the selected text to the position


of the cursor. Useful only with the
Persistent Block option.

The next table describes certain editing commands in more detail.


The table is arranged alphabetically by command name.

Table A.4: Other editor commands in depth


Command

Keys

Function

Autoindent mode on/off

Ctr/+O /

Toggles the automatic indenting of successive lines. You can


also use Options I Editor A1!toindent in the IDE to turn
automatic indenting on and off.

Cursor through
tabs on/off

Ctr/+O R

The arrow keys will move the cursor to the middle of


tabs when this option is on; otherwise the cursor jumps several
columns when moving the cursor over multiple tabs. Ctr/+O R is
a toggle.

Find place
marker

Ctr/+Qn'

Finds up to ten place markers (n can be any number in


the range 0 to 9) in text. Move the cursor to any previously set
marker by pressing Ctr/+O and the marker number.

Open file

F3

Lets you load an existing file into an edit window.

Optimal fill mode on/off

Ctr/+O F

Toggles optimal fill. Optimal fill begins every line with the
minimum number of characters possible, using tabs and spaces
as necessary. This produces lines with fewer characters.

Save file

F2

Saves the file and returns to the editor.

n represents a number from 0 to 9.

Appendix A, Editor reference

269

Table A.4: Other editor commands in depth (continued)


Command

Keys

Function

Set marker

Ctr/+K n *

You can mark up to ten places in text. After marking your


location, you can work elsewhere in the file and then easily
return to your marked location by using the Find Place Marker
command (being sure to use the same marker number). You
can have ten places marked in each window.

Tabs mode on/off

Ctr/+O T

Toggles Tab mode. You can specify the use of true tab
characters in the IDE with the Options I Editor Use Tab
Character option.

Unindent mode on/off

Ctr/+O U

Toggles Unindent. You can turn Unindent on and off from the
IDE with the Options I Editor Backspace Unindents option.

n represents a number from a to 9.

Searching with regular expressions


You can choose to search for text using wildcards in the search
string. This table lists the wildcards you can use:
Table A.S
Regular expression wildcards

Expression

Function

------------------------~-------------------------------

$
*

[]

[-]

270

A circumflex at the start of the string matches the start of a


line.
A dollar sign at the end of the expression matches the end
of a line.
A period matches any character.
A character followed by an asterisk matches any number
of occurrences (including zero) of that charact~r. For
example, bo* matches bot, b, boo, and also be.
A character followed by a plus sign matches any number
of occurrences (but not zero) of that character. For
example, bo+ matches bot and boo, but not be or b.
Characters in brackets match anyone character that
appears in the brackets but no others. For example [bot]
matches b, 0, or t.
A circumflex at the start of the string in brackets means
not. Hence, ["botJ matches any character except b, 0, or t.
A hyphen within the brackets signifies a range of
characters. For example, [b-oJ matches any character from
b througho.
A backslash before a wildcard character tells Turbo Pascal
to treat that character literally, not as a wildcard. For
example, \" matches" and does not look for the start of a
line.

Programmer's Reference

B
Compiler directives quick reference
This appendix lists all of the Turbo Pascal compiler directives. It shows
the syntax as you would enter it in your source code, displays the
. command-line equivalent, and briefly describes each directive.
Asterisks (*) indicate the default setting. For example, the default setting
for debug information {$D+} is on.
Table B.l: Compiler directives

Directive

Source Code
Syntax

Default

Command-line

Description

/$A+

Aligns variables and typed


constants on word boundaries.

{$A-}

/$A-

Aligns variables and typed


constants on byte boundaries.

Boolean evaluation complete

{$B+}

/$B+

Complete Boolean expression


evaluation.

Boolean evaluation short circuit

{$B-}

/$8-

Short circuit Boolean expression


evaluation.

Debug information
on

{$D+}

/$0+

Generates debug information.

Debug information
off

{$D-}

/$0-

Turns off debug information.

Align data word

{$A+}

Align data byte

Appendix B, Compiler directives quick reference

271

Table B.l : Compiler directives (continued)


Directive

Source Code
Syntax

DEFINE

{DEFINE

ELSE

{ELSE}

Emulation on

{$E+}

Emulation off

{$E-}

ENDIF

{$ENDIF}

Default

name}

Command-line

/Dname

I$E+

I$E-

Description

Defines a conditional symbol of


name.
Switches between compiling and
ignoring source delimited by
{$IFxxx} and {$ENDIF}.
Enables linking with a run-time
library that emulates the 80x87
numeric coprocessor..
Disables linking with a run-time
library that emulates the 80x87
numeric coprocessor.
Ends conditional compilation
started by last {$IFxxx}.

Extended syntax1
/$F+

Procedures and functions


compiled always use far call
model.

/$F-

Compiler selects appropriate


model: far or near.

/$G+

Generates 80286 instructions


to improve code generation.

/$G-

Generates only generic 8086


instructions.

/$1+

Enables the automatic code


generation that checks the
result of a call to an II 0
procedure.

/$1-

Disables the automatic code


generation that checks the
result of a call to an I/O
procedure,

Force far calls on

{$F+}

Force far calls off

{$F-}

80286 code
generation on

{$G+}

80286 code
generation off

{$G-}

Input! output
checking on

{$I+}

Input! output
checking off

{$I-}

Include file

{$I filename}

Includes the named file in the


compilation.

IFDEF

{IFDEF name}

Compiles source text that follows


if name is defined.

IFNDEF

{IFNDEF name}

Compiles the source text that


follows if name is not defined.

See $X on page 274.

272

Programmer's Reference

Table B.l: Compiler directives (continued)


Source Code
Syntax

Directive

Default

Command-line

Description

IFOPT

{lFOPT switch}

Compiles the source text that


follows if switch is currently in the
specified state.

Link object file

{$L filename}

Links the named object file with


the program or unit being
compiled.

Local symbol
information on

{$L+}

Local symbol
information off
Memory allocation
sizes

/$L+

Generates local symbol


information.

{$L-}

/$L-

Disables generation of local


symbol information.

{$M}stacksize,
heapmin,heapmax

Specifies an application or
/ $Mstacksize,
heapmin,heapmax library'S memory allocation

parameters.
Numeric coprocessor
on

{$N+}

Numeric coprocessor
off

{$N-}

Open parameters on

{$P+}

Open parameters off

{$P-}

/$N+

Generates code that performs


all real-type calculations
using 80x87.

/$N-

Generates code that performs


all real-type calculations by
calling run-time library routines.

/$P+

Enables open string and array


parameters in procedure and
function declarations.

/$P-

Disables open string and array


parameters.

/$Q+

Enables the generation of


overflow-checking code.

/$Q-

Disables the generation of


overflow-checking code.

/$0+

Enables overlay code


generation

/$0-

Disables overlay code


generation.

/$R+

Generates range-checking code.

Overflow checking on {$Q+}


Overflow checking off {$Q-}

Overlay code
generation

{$O+}

Overlay code
generation

{$O-}

Range checking on

{$R+}

Range checking off

{$R-}

/$R-

Disables generation of rangechecking code.

Stack-overflow
checking on

{$S+}

/$S+

Generates stack-overflow
checking code.

Appendix 8, Compiler directives quick reference

273

Table B.1: Compiler directives (continued)


Directive

Source Code
Syntax

Default

Command-line

Description

{$S-}

/$S-

Disables generation of stackoverflow code.

Type-checked pointers {$T+}


on

/$T+

Enables the generation of


type-checked pointers when the
@ operator is used.

/$T-

Disables the generation of


type-checked pointers when the
@ operator is used.

Stack-overflow
checking off

Type-checked pointers {$T-}


off
UNDEF

,{UNDEF name}

Var-string. checking
on

{$V+}

Var-string checking
off

{$V-}

Extended syntax on

{$X+}

Extended syntax off

{$X-}

274

Undefines a previously defined


conditional symbol.

/$V+

Strict type checking js enabled.

/$V-

Type checking is relaxed.

/$X+

Enables extended syntax to permit


discarding result of a function call
and to support null-terminated
strings.

/$X-

Disables extended syntax.

Programmer,s Reference

c
Reserved words and standard
directives
This appendix lists the Turbo Pascal reserved words and standard
directives.
Reserved words and standard directives appear in lowercase
boldface throughout the manuals. Turbo Pascal isn't case
sensitive, however, so you can use either uppercase or lowercase
letters in your programs.
Reserved words have a special meaning to Turbo Pascal; you
can't redefine them.
Table C.l
Turbo Pascal reserved words

and
array
asm
begin
case
const
constructor
destructor
div
do
downto
else

end
file
for
function
goto
if
implementation
in
inherited
inline
interface
label

mod
nil
not
object
of
or
packed
procedure
program
record
repeat
set

shl
shr
string
then
to
type
unit
until
uses
var
while
with
xor

The following are Turbo Pascal's standard directives. Unlike


reserved words, you may redefine them. It's advised that you
avoid creating user-defined identifiers with the same names as

Appendix C, Reserved words and standard directives

275

directives because doing so can produce unexpected results and


make it difficult to debug your ,program.
TableC.2
Turbo Pascal standard
directives

absolute
assembler
external

far
forward
interrupt

near
private
public

resident
virtual

private and public act as reserved words within object type


declarations, but are otherwise treated as directives.

276

Programmer's Reference

D
ASCII characters
This appendix contains a table that lists the American Standard
Code for Information Interchange (ASCII) characters. ASCII is a
code that translates alphabetic and numeric characters and
symbols and control instructions into 7-bit binary code. Table D.l
shows both printable characters and control characters.

Appendix 0, ASCII characters

277

Table D.l
ASCII table

Dec Hex Char

o
The caret in A@ means to
press the elrl key and type @.

1
2
4

5
6

A@ NUL

1
2
3
4
5
6

7
8

BEL
BS
TAB

10
11
12

LF

o-VT

FF

13

jl

CR

14
15
16
17
18
19
20
21

SO

S1

10
11
12

22
23
24
25
26

27
28
29
30
31

278

SOH
STX
ETX
EOT
.to ENQ
.. ACK

13

14
15
16
17
18
19
1A
1B
1C
1D
1E
1F

DLE
... DC1
DC2
!! DC3
~ DC4
NAK

SYN
ETB
CAN

EM

SUB
ESC
FS

GS

.. RS
~ US

Dec Hex Char


32
33
34
35
36
37
38
39
40
41
42
43
. 44

20
21
22
23
24
25
26
27
28
29
2A
2B
2C

45
46
47
48
49
50
51
52
53
54
55
56
57
.58
59
60
61
62
63

2D
2E
2F
30
31
32
33
34
35
36
37
38
39
3A
3B
3C
3D
3E
3F

$
J\(

&

(
)

*
+

Dec Hex Char


64
65
66
67
68
69
70
71
72
73
74
75
76

77

o
1

2
3
4
5
6
7

8
9

78
79
80
81
82
83
84
85
86
87
88
89
90
91

<
>

92
93
94
95

40
41
42
43
44
45
46
47
48
49
4A
4B
4C
4D
4E
4F
50
51
52
53
54
55
56
57
58
59
5A
5B
5C
5D
5E
5F

B
C
D

E
F
G
H
I
J
K
L
M

o
p
Q

R
S
T
U
V
W
X
Y
Z

\
]
A

Dec Hex Char


96 60
97 - 61
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

62
63
64
65
66
67
68
69
6A
6B
6C
6D
6E
6F
70
71
72
73
74
75
76
77
78
79
7A
7B
7C
7D
7E
7F

a
b

c
d

e
f

9
h
j

k
m

n
o
p
q

s
t
u

v
w
x
y
Z

Programmer's Reference

Table D.l: ASCII table (continued)

Dec Hex Char

Appendix 0, ASCII characters

128
129
130
131
132
133
134
135
136
137
138
139

80
81
82
83
84
85
86
87
88
89
8A
8B

C(

140
141
142
143
144
145
146
147
148
149'
150
151
152
153
154
155
156
157
158
159

8C
8D
8E
8F
90
91
92
93
94
95
96
97
98
99
9A
9B
9C
9D
9E
9F

'I

jj

e
a
a

a
a
c;

e
e
e
;'

A
E
a!

If.

a
o
o
Q

o
o

PI

Dec Hex Char

Dec Hex Char

160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223

AO
A1
A2
A3
A4
A5
A6
A7
A8
A9

6
U
fi

N
a
o

AA

AB
AC
AD

AE

AF
BO
B1
B2
B3
B4
B5
B6
B7
B8
B9
BA
BB
BC
BD
BE
BF

m
II

I
i
=l

~I
11

{I
II
il
:!J
lJ

d
1

co

C1
C2
C3
C4
C5
C6
C7
C8
C9
CA
CB
CC
CD
CE
CF
DO
Dl
D2
D3
D4
D5
D6
D7
D8
D9
DA
DB
DC
DD
DE
DF

.L

Ii'
:!!:

JL

lr
:!:
II

If
lL

If

=f

I
I

Dec Hex Char


224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

EO
E1
E2
E3
E4
E5
E6
E7
E8
E9
EA
EB
EC
ED
EE
EF
FO
F1
F2
F3
F4
F5
F6
F7
F8
F9
FA
FB
FC
FD
FE
FF

ex
B

r
IT

a
J1
T
cJ>

()

o
o
00

ifJ
E

n
2

279

280

Programmer's Reference

80286 code generation compiler switch 215


286 Code option 215
80x87 code option 218

AssignCrt procedure 10
Assigned function 10
autoindent mode 267, 269

$A compiler directive 211


Abs function 6
absolute value of an argument 6
access code passed to DOS 45
Addr function 6
address
converting to pointer 129
of object 6
Align Data command 211
aligning data 211
AndPut constant 13
AnyFile constant 43
Append procedure 6
Arc procedure 8
ArcCoordsType type 7
Archive constant 43
ArcTan function 8
arctangent of an argument 8
argument
arctangent of 8
predecessor of 129
size 176
successor of 188
arguments
command-line compiler 227
number passed 59
ASCII characters 277
aspect ratio 59
correction factor, changing 154
assembly language 216
assign buffer to text file 168
assign file name to file variable 9
Assign procedure 9

/B command-line option (TPC) 231


$B compiler directive 211
bar constants 11
Bar3D procedure 12
Bar procedure 11
BGI, Zenith Z-449 and 91
binary format 234
BINOBJ 137, 139
bit images 70
BitBlt operators 12, 130
BIX, Borland information 2 .
BkSlashFill constant 48
Black constant 22
Black text color constant 192
Blink text color constant 192
block
copy 267, 268
Borland-style 269
cut 268
delete 267, 268
extend 267
. hide and show 266
Borland-style 269
indent 267
move 267, 268
Borland-style 269
to beginning of 266
to end of 266
print 266
read from disk 267, 268
set beginning of 266
Borland-style 269
set end of 266

Index

281

Borland-style 269
unindent 267
write to disk 267, 268
BlockRead procedure 13
BlockWrite procedure 14
Blue constant 22
Blue text color constant 192
Boolean evaluation
compiler switch 211
complete 211
short circuit 211
Borland, contacting 2-4
BottomText constant 99
Break procedure 15
Brown constant 22
Brown text color constant 192
buffer, assigning to text file 168
buffers, flushing 54
Build command 231
build command-line option 231
BW40 mode constant 26
BW80 mode constant 26
bytes, copying 108

c
C040 mode constant 26
C080 mode constant 26
C40 mode constant 26
C80 mode constant 26
CenterLn constant 101
CenterText constant 99
CGA25
changing directories 15
characters
, convert to uppercase 200
delete 266
filling string with 49
ordinal number of 17
ChDir procedure 15
CheckBreak variable 16
CheckEof variable 16
CheckSnow variable 16
Chr function 17
Circle procedure 17
Clear command 268
ClearDevice procedure 18
clearing the overlay buffer 116

282

ClearViewPort procedure 19
Clipboard
copy to 267
cut to 267
paste from 267, 268
ClipOff constant 19
ClipOn constant 19
clipping constants 19
clipping parameters 79
Close procedure 20
CloseDotFill constant 49
CloseGraph procedure 20
ClrEol procedure 21
ClrScr procedure 21
colors 67
background 60
changing text 192
constants 22
constants for SetRGBPalette 22
drawing 62
command-line
compiler reference 227-236
options 229-235
/B231
/D230
debug 234
/E234
/F 231
/G234
/GD234
/GP 234
/GS234
/1234
/L232
/M231
mode 230
, /0234
/Q232
switching directive defaults (/$) 229
/T 233
/U234
/V 235
command-line compiler
arguments 227
compiling and linking with 227
extended syntax 228
options 227

Programmer's Reference

286 code generation 228

align data 228


append debug information to EXE 235
Boolean evaluation 228
build all 230, 231
build all units 229
debug 234
debug information 228, 235
inEXE229
define conditional symbol 229
emulation 228
EXE & TPU directory 229, 234
find error 231
find run-time error 229
force far calls 228
I/O checking 228
include directories 229, 234
link buffer 230, 232
link buffer on disk 229
list of 228
local symbols 228, 235
make 231
make modified units 229
map file 229, 234
memory sizes 228
numeric coprocessor 228
object directories 229, 234
open parameters 228
overflow checking 228
overlay code generation 228
quiet compile 229, 230, 232
range checking 228
stack checking 228
TPL & CFG directories 229, 233
type-checked pointers 228
unit directories 229, 234
var-string checking 228
command-line parameter 59, 127
commands, editor
block operations 266
cursor movement 266
insert and delete 266
compilation, conditional 223
compiler
directives 268
$A211
$B 211

Index

change state of 229


conditional 210
$D 212, 231
$DEFINE 212, 224, 230
$E213
$ELSE 213
$ENDIF 213
$F 214
$G215

$198,216
$IFDEF 215
$IFNDEF 215
$IFOPT 215
$L 216, 217
$M 99, 106, 124,218,230
$N218
$0219,220

$P218
parameter 210
$R220

$S221
switch 209
$UNDEF 222, 224
$V222
$X214
$Y 221
error messages 237
compiling to .EXE file 231
Complete Boolean Eval option 211
CompuServe, Borland information 2
ComStr type 44
Concat function 23
concatenating strings 23
conditional
defines (command-line option) 230
symbols 224
CONFIG.SYS 121
configuration file
TPC.CFG235
Continue procedure 23
control characters 277
insert 267
copy block 267
Borland-style 269
Copy Junction 24
copy to Clipboard 267

283

copying
bytes 108
substrings 24
CopyPut constant 13
Cos function 25
cosine of an argument 25
CPU symbols 225
CreateDir procedure 25
critical errors 261
Crt unit
AssignCrt procedure 10
ClrEol procedure 21
ClrScr procedure 21
Delay procedure 27
DelLine procedure 28
GotoXY procedure 81
HighVideo procedure 88
InsLine procedure 93
KeyPressed function 99
LowVideo procedure 105
NormVideo procedure 111
NoSound procedure 112
ReadKey function 135
Sound procedure 176
TextBackground procedure 192
TextColor procedure 193
TextMode procedure 194
WhereX function 202
WhereY function 202
Window procedure 203
CS register value 26
CSeg function 26
cursor position
reading 202
setting 81
cursor through tabs 267, 269
customer assistance 2-4
cut to Clipboard 267
Cyan constant 22
Cyan text color constant 192

D
/D command-line option 230
$D compiler directive 212, 231
DarkGray constant 22
DarkGray text color constant 192
DashedLn constant 101

284

data alignment 211


date and time procedures
GetDate 63
GetFTime 68
GetTime 78
SetDate 157
SetFTime 160
SetTime 171
DateTime type 26
Debug Information
command 212
option 212
debugging
command-line option 235
information switch 212
options, command-line 234
range-checking switch 220
run-time error messages 257
stack overflow switch 221
Dec procedure 27
DefaultFont constant 55
$DEFINE compiler directive 212, 224, 230
Delay procedure 27
delete
block 267
characters 266
lines 266
words 266
Delete procedure 27
deleting files 38
deleting substrings 27
DelLine procedure 28
DetectGraph procedure 28
devices 18
installing drivers 94
directives 275
directories 64
changing 15, 156
command-line options 233
creating 25, 108
procedures 145
searching 46,51,57
directory
current 62, 64
remove a 141, 145
Directory constant 43
DirectVideo variable 29

Programmer's Reference

DirStr type 44
DiskFree function 30
disks, space 30
DiskSize function 30
Dispose procedure 30
DOS
Pascal functions for 110
verify flag 79
setting 172
Dos unit
DiskFree function 30 .
DiskSize function 30
DosExitCode function 32
DosVersion function 32
EnvCount function 36
EnvStr function 36
Exec procedure 39
FExpand function 42
FindFirst procedure 51
FindNext procedure 52
FSearch function 57
FSplit procedure 57
GetCBreak procedure 61
GetDate procedure 63
GetEnv function 65
GetFAttr procedure 66
GetFTime procedure 68
GetIntVec procedure 71
GetTime procedure 78
GetVerify procedure 79
Intr procedure 97
Keep procedure 99
MsDos procedure 110
PackTime procedure 125
SetCBreak procedure 155
SetFTime procedure 160
SetIntVec procedure 161
SetTime procedure 171
SetVerify 172
SwapVectors procedure 189
UnpackTime procedure 200
DosError variable 31, 39, 160
DosExitCode function 32
DosVersion function 32
DottedLn constant 101
DrawPoly procedure 32
driver constants 33

Index

drivers
active 64
maximum mode number 72
DS register value 35
DSeg function 35
dynamic variables, creating 74

E
IE command-line option 234
$E compiler directive 213
edit windows, moving cursor in 266
editing
block operations 266
deleting 268
reading and writing 268
commands
cursor movement 266
insert and delete 266
EGABlack constant 23
EGABlue constant 23
EGABrown constant 23
EGACyan constant 23
EGADarkGray constant 23
EGAGreen constant 23
EGALightBlue constant 23
EGALightCyan constant 23
EGALightGray constant 23
EGALightGreen constant 23
EGALightMagenta constant 23
EGALightRed constant 23
EGAMagenta constant 23
EGARed constant.23
EGAWhite constant 23
EGAYellow constant 23
ellipse, drawing 49
Ellipse procedure 35
elliptical sector, drawing and filling 148
$ELSE compiler directive 213
EmptyFill constant 48
emulating numeric coprocessor (8087)
compiler switch 213
Emulation
command 213
option 213
end-of-file
error messages 239
status 36, 37, 149

285

end-of-line status 37, 149


$ENDIF compiler directive 213
EnvCount function 36
environment variable 66
EnvStr function 36
Eof function 36, 37
Eoln function 37
Erase procedure 38
error messages 237
fatal 261
searching 231
ErrorAdr variable 39
errors
codes for graphics operations 82, 84
messages 82
range 220
Exclude procedure 39
EXE & TPU directory command-line option 234
.EXE files, creating 231
Exec procedure 39
exit
codes 32
procedures 40
the IDE 267
ExitCode variable 41
ExitProc variable 41
Exp function 42
exponential of an argument 42
extend block 267
extended syntax 214
Extended Syntax option 214
external
declarations 216
procedure errors 243
EXTRN definition errors 244
ExtStr type 44

F
IF command-line option 231
$F compiler directive 214
far calls, forcing use of models in 214
fatal run-time errors 261
FAuxiliary constant 53
FCarry constant 53
fcDirectory constant 42
fcExtension constant 42
fcFileName constant 42

286

fcWildcards constant 42
fcXXXX constants 42
FcXXXX flag constants 48
FExpand function 42
file
expanding file names 44
open 267, 269
position 45
reading file components 135
save 267, 269
size of 47
split into components 47
file attribute constants 43
file-handling procedures
Rename 142
Reset 142
Rewrite 144
Seek 149
SetFAttr 157
Truncate 198
file-handling string types 44
file mode constants 55
file name length constants 43
file record types 46, 195
FileExpand function 44
FileMode variable 45
FilePos function 45
FileRec type 46
files
access-denied error 258
attributes 66
closing 20
creating new 144
erasing 38
.MAP234
.OBJ 234
linking with 216
opening existing 142
record definition for 197
text, record definition 199
truncating 198
untyped, variable 13, 14
FileSearch function 46
FileSize function 47
FileSplit constants 42
FileSplit function 44,47
fill pattern constants 48

Programmer's Reference

fill patterns 67
FillChar procedure 49
FillEllipse procedure 49
filling areas 53
FillPattemType type 50
FillPoly procedure 50
FillSettingsType type 51
Find Error command 231, 232
find error command-line option 231
FindFirst procedure 43, 51
FindNext procedure 52
flag constants in Dos unit 53
flag constants in WinDos unit 53
floating-point errors 262
FloodFill procedure 53
Flush procedure 54
fmClosed constant 55
fmInOut constant 55
fmInput constant 55
fmOutput constant 55
fmXXXX constants 55
font control constants 55
Font8x8 mode constant 26
Font8x8 variable 194, 195
fonts
installing 96
stroked 171
Force Far Calls
command 214
option 214
force far calls compiler switch 214
FOverflow constant 53
FParity constant 53
Frac function 55
fractions, returning 55
FreeList variable 56
FreeMeni. procedure 56
fsDirectory constant 44
FSearch function 57
fsFileName constant 44
FSign constant 53
fsPathName constant 44
FSplit procedure 43, 57
fsWildCards constant 44
FsXXXX constants 48
fsXXXX constants 43

Index

functions
discarding results 214
extended syntax and 214
FXXXX constants 53
fXXXX constants 53
FZero constant 53

G
/G command-line option 234
$G compiler directive 215
/ GD command-line option 234
GEnie, Borland information 2
GetArcCoords procedure 58
GetArgCount function 59
GetArgStr function 59
GetAspectRatio procedure -59
GetBkColor function 60
GetCBreak procedure 61
GetColor function 62
GetCurDir function 62
GetDate procedure 63
GetDefaultPalette function 63
GetDir procedure 64
GetDriverName function 64
GetEnv function 65
GetEnvVar function 66
GetFAttr procedure 43, 66
GetFillPattem procedure 67
GetFillSettings procedure 67
GetFTime procedure 68
GetGraphMode function 69
GetImage procedure 70
GetIntVec procedure 71
GetLineSettings procedure 71
GetMaxColor function 72
GetMaxMode function 72
GetMaxX function 73
GetMaxY function 74
GetMem procedure 74
GetModeName function 75
GetModeRange procedure 75
GetPalette procedure 76
IBM 8514 and 76
GetPaletteSize function 77
GetPixel function 77
GetTextSettings procedure 78
GetTime procedure 78

287

GetVerify procedure 79
GetViewSettings procedure 79
GetX function 80
GetY function 81
GothicFont constant 55
GotoXY procedure 81
/GP command-line option 234
Graph unit
Arc procedure 8
Bar3D procedure 12
Bar procedure 11
Circle procedure 17
ClearDevice procedure 18
ClearViewPort procedure 19
CloseGraph procedure 20
DetectGraph procedure 28
DrawPoly procedure 32
Ellipse procedure 35
FillEllipse procedure 49
FillPoly procedure 50
FloodFill procedure 53
GetArcCoords procedure 58
GetAspectRatio procedure 59
GetBkColor function 60
GetColor function 62
GetDefaultPalettefunction 63
GetDriverName function 64
GetFillPattern procedure 67
GetFillSettings procedure 67
GetGraphMode function 69
GetImage procedure 70
GetLineSettings procedure 71
GetMaxColor function 72
GetMaxMode function 72
GetMaxX function 73
GetMaxY function 74
GetModeName function 75
GetModeRange procedure 75
GetPalette procedure 76
GetPaletteSize function 77
GetPixel function 77
GetTextSettings procedure 78
GetViewSettings procedure 79
GetX function 80
GetY function 81
GraphDefaults procedure 82
GraphErrorMsg function 82

288

GraphResult function 84
ImageSize function 88
InitGraph procedure 90
InstallUserDriver function 94
InstallUserFont function 96
Line procedure 100
LineRel procedure 102
LineTo procedure 103
MoveRel procedure 109
MoveTo procedure 110
OutText procedure 113
OutTextXY procedure 115
PieSlice procedure 127
PutImage procedure 130
PutPixel procedure 132
Rectangle procedure 136
RegisterBGIdriver function 137
RegisterBGIfont function 139
RestoreCrtMode procedure 143
Sector procedure 148
SetActivePage procedure 152
SetAllPalette procedure 152
SetAspectRatio procedure 154
SetBkColor procedure 155
SetColor procedure 156
SetFillPattern procedure 158
SetFillStyle procedure 159
SetGraphBufSize procedure 160
SetGraphMode procedure 160
SetLineStyle procedure 162
SetPalette procedure 163
SetRGBPalette procedure 164
SetTextJustify procedure 169
SetTextStyle procedure 169
SetUserCharSize procedure 171
SetViewPort procedure 172
SetVisualPage procedure 173
SetWriteMode 174
TextHeight function 193
TextWidth function 196
GraphDefaults procedure 82
GraphDriver variable
IBM 8514 and 91
. GraphErrorMsg function 82
GraphFreeMemPtr variable 83
GraphGetMemPtr variable 83

Programmer's Reference

graphics
bit-image operations 130
cards 28,91
drawing operations 100, 102, 103, 127, 136,
162
drivers 90
fill operations 158, 159
mode 69, 90, 101, 102, 103
page operations 152, 173
palette operations 152, 155, 156, 163
plotting operations 132
pointer operations 110
polygons, drawing 32
resolution 59
system operations 160
text operations 113, 115, 169, 193
video mode operations 143
viewport operations 172
GraphMode procedure 90
GraphResult function 84
error codes 84
Green constant 22
Green text color constant 192
grError constant 85
grFileNotFound constant 85
grFontNotFound constant 85
grInvalidDriver constant 85
grInvalidFont constant 85
grInvalidFontNum constant 85
grInvalidMode constant 85
grIOerror constant 85
grNoFloodMem constant 85
grNoFontMem constant 85
grNoInitGraph constant 85
grNoLoadMem constant 85
grNoScanMem constant 85
grNotDetected constant 85
grOk constant 85
grXXXX constants 85
IGS command-line option 234

H
Halt procedure 85
HatchFill constant 49
heap
end function, poiilter to 86
error function, pointer to 86

Index

free memory in 107


management sizes 218, 230
org function, pointer to 86
ptr function, pointer to 87
return memory to 30
HeapEnd variable 86
HeapError variable 86
HeapOrg variable 86
HeapPtr variable 87
Help 267
index 267
topic search 268
Hi function 87
Hidden constant 43
High function 87
high-intensity characters 88
high-order byte 87
high-order bytes
swapping 188
HighVideo procedure 88
HorizDir constant 55

II command-line option 234


$1 compiler directive 98,216

I/O
checking 98, 216
error-checking 216
errors 260
operation, status of last 98
1/0 Checking
command 216
option 216
IBM 8514
GetPalette procedure and 76
GraphDriver variable and 91
InitGraph procedure and 91
palette entries, modifying 164
SetAllPalette procedure and 153
SetPalette procedure and 163
. $IFDEF compiler directive 215
$IFNDEF compiler directive 215
$IFOPT compiler directive 215
ImageSize function 88
Inc procedure 89
Include directories command-line option 216,
'234

289

Include files 216


nesting 216
include files 234
Include procedure 90
indent block 267
InitGraph procedure 90
SetGraphMode and 160
InOutRes variable 92
input file, name of standard 92
Input variable 92
insert
lines 266
mode 266
substring into a string 93
Insert procedure 93
inserting lines 93
InsLine procedure 93
InstallUserDriver function 94
InstallUserFont function 96
Int function 97
integer part of argument 97
InterleaveFill constant 49
interrupt
procedures 161
vectors 71 .
swapping 189
Intr procedure 97
invalid typecasting errors 245
IOResult function 98

J
justification, font 78
justification constants 99

K
Keep procedure 99
keyboard operations 99, 135
KeyPressed function 99

L
IL command-line option 232
$L compiler directive 216, 217
LastMode variable 100
LeftText constant 99
Length function 100
length of file name string 43

290

LightBlue constant 22
LightBlue text color constant 192
LightCyan constant 22
LightCyan text color constant 192
LightGray constant 22
LightGray text color constant 192
LightGreen constant 22
LightGreen text color constant 192
LightMagenta constant 22
LightMagenta text color constant 192
LightRed constant 22
LightRed text color constant 192
line
drawing, setting writing mode for 174 .
mark a 266
settings 71
Line procedure 100
line style constants 101
LineFill constant 48
LineRel procedure 102
lines
delete 266
insert 266
LineSettingsType type 103
LineTo procedure 103
Link Buffer option 232
linking
buffer option 232
object files 216
Ln function 104
Lo function 104
local symbol information switch 217
Local Symbols
command 217
option 217
logarithm, natural 104
Low function 104
low-order bytes 104
swapping 188 .
LowVideo procedure 105
Lst variable 106
LtBkSlashFill constant 48
LtSlashFill constant 48

M
1M command-line option 231
$M compiler directive 99, 106, 124,218,230

Programmer's Reference

Magenta constant 22
Magenta text color constant 192
Make command 231
make command-line option 231
map file command-line option 234
.MAP files 234
marker
find 267, 269
set 268,270
MaxAvail function 106
MaxColors constant 107
MemAvail function 107
memory 74
allocation 230
compiler directive 218
block, size of largest 106
error messages 238
free amount of 107
freeing 30, 56
size 218
MkDir procedure 108
mode constants, video 33
Mono mode constant 26
move block 267
Move procedure 108
MoveRel procedure 109
MoveTo procedure 110
MsDos procedure 110
MSDOS symbols 225

N
$N compiler directive 218
NameStr type 44
nesting files 216
New procedure 111
extended syntax, constructor passed as
parameter 111
NormVideo procedure 111
NormWidth constant 102
NoSound procedure 112
NotPut constant 13
null-terminated strings, compiler directive 214
number, random 132
numeric coprocessor, compiler'switch 218
numeric value, convert to string 178

Index

o
/0 command-line option 234
$0 compiler directive 219, 220
.OBJ files 234
linking with 216
object
directories, compiler directive 216
files, linking with 216
segment of 150
object directories command-line option 234
Odd function 112
odd number 112
offset of an object 112
Ofs function 112
online information services 2
Open a File dialog box 269
Open command 269
open file 267, 269
open string parameters compiler switch 218
Optimal Fill option 267, 269
Ord function 112
ordinal number of a character 17
ordinal value, of expression 112
OrPut constant 13
out-of-memory errors 238
output file, name of standard 113
Output variable 113
OutText procedure 113
OutTextXYprocedure 115
overflow checking 219
overlay buffers
clearing 116
returning size 118
setting size 123
Overlay unit
, OvrClearBuf procedure 116
OvrGetBuf function 118
OvrGetRetry function 118
OvrInit procedure 120
OvrInitEMS procedure 121
OvrSetBuf procedure 123
OvrSetRetry procedure 124
overlay unit name 220
overlays
code generation, compiler switch 219
files
loading into EMS 121

291

opening 120
manager, initializing. 120
Overlays Allowed
command 219, 220
option 219
OvrClearBuf procedure 116
OvrCodeList variable 116
OvrDebugPtr variable 117
OvrdosHandle variable 117
OvrEmsHandle variable 117
OvrFileMode variable 118
OvrGetBuf function 118
OvrGetRetry function 118
OvrHeapEnd variable 119
OvrHeapOrg variable 119
OvrHeapPtr variable 120
OvrHeapSize variable 120
OvrInit procedure 120
OvrInitEMS procedure 121
ovrIOError constant 125
OvrLoadCount variable 122
OvrLoadList variable 122
ovrNoEMSDriver constant 125
ovrNoEMSMemory constant 125
ovrNoMemory constant 125
ovrNotFound constant 125
ovrOk constant 125
OvrReadBuf variable 123
OvrResult variable 123
OvrSetBuf procedure 123
OvrSetRetry procedure 124
OvrTrapCount variable 125
ovrXXXX constants 125

p
$P compiler directive 218
PackTime procedure 125
pair matching 267
palette
color lookup table, returning size 77
definition record 63
PaletteType type 126
ParamCount function 126
parameters
command-line 59, 127
number of 126

292

number passed 59
ParamStr function 127
paste from Clipboard 267, 268
PathStr type 44
Pi function 127
PieSlice procedure 127
pixel values 77
place marker
find 267, 269
set 268, 270
PointType type 128
polygons, drawing 32
Pos function 128
Pred function 129
PrefixSeg variable 129
Printer unit, Lst variable 106
process-handling routines 99
Program Segment Prefix, address of 129
programs
execution, stopping 146
halting 85
rebuilding 231
Ptr function 129
PUBLIC definition errors 244
Putlmage procedure 130
PutPixel procedure 132

Q
/ Q command-line option 232
quiet mode command-line option 232

R
$R compiler directive 220
Random function 132
random generator
initialize 133
seed 133
random number 132
Randomize procedure 133
RandSeed variable 133
Range Checking
command 220
option 220
range checking 229
compiler switch 220
Val and 201

Programmer's Reference

read
a line 136
block 267
file component 135
records into a variable 13
t~xt file 133
Read procedure
text files 133
typed files 135
ReadKey function 135
Readln procedure 136
ReadOnly constant 43
Rectangle procedure 136
Red constant 22
Red text color constant 192
referencing errors 252
RegisterBGIdriver function 137
Register BGIfont function 139
registers, CS 26
Registers type 141
regular expressions
searching 270
wildcards 270
relaxed string parameter checking 222
relocatable reference .errors 244
RemoveDir procedure 141
Rename procedure 142
Reset procedure 142
resolution, graphics 59
RestoreCrtMode procedure 143
results, discarding 214
return flags for FileSplit constants 42
Rewrite procedure 144
RightText constant 99
RmDir procedure 145
Round function 145
run-time errors 257
,address of 39
fatal 261
Find Error command and 231
finding 231
generating 146
RunError procedure 146

5
$S compiler directive 221
SansSerifFont constant 55

Index

save file 267, 269


SaveIntOO variable 146
SaveInt02 variable 146
SaveInt21 variable 146
SaveInt23 variable 146
SaveInt24 variable 146
SaveInt34 variable 146
SaveInt35 variable 146
SaveInt36 variable 146
SaveInt37 variable 146
SaveInt38 variable 146
SaveInt39 variable 146
SaveInt75 variable 147
SaveInt3A variable 146
SaveIntlB variable 146
SaveInt3B variable 147
SaveInt3C variable 147
SaveInt3D variable 147
SaveInt3E variable 147
SaveInt3F variable 147
SaveIntXX variables 146
search for text 267
searching
directories 51
run-time error messages 231
SearchRec type 147
Sector procedure 148
Seek procedure 149
SeekEof function 149
SeekEoln function 149
Seg0040 variable 150
Seg function 150
SegAOOO variable 150
SegBOOO variable 151
SegB800 variable 151
segment of object 150
SelectorInc variable 151
SetActivePage procedure 152
SetAllPalette procedure 152
IBM 8514 and 153
SetAspectRatio procedure 154
SetBkColor procedure 155
SetCBreak procedure 155
SetColor procedure 156
SetCurDir procedure 156
SetDate procedure 157
SetFAttr procedure 43, 157

293

SetFillPattern procedure 158


SetFillStyle procedure 159
SetFTime procedure 160
SetGraphBufSize procedure 160
SetGraphMode procedure 160
SetIntVec procedure 161
SetLineStyle procedure 162
SetPalette procedure 163
IBM 8514 and 163
SetRGBPalette procedure 164
SetTextBuf procedure 168
SetTextJustify procedure 169
SetTextStyle procedure 169
OutText and 113
OutTextXYand 115
SetTime procedure 171
SetUserCharSize procedure 171,
SetVerify procedure 172
SetViewPort procedure 172
SetVisualPage procedure 173
SetWriteMode procedure 174
short-circuit Boolean evaluation 211
Sin function 175
sine of argument 175
size
free memory in heap 107
largest free block in heap 106
of argument 176
SizeOf function 49, 176
SlashFill constant 48
SmallFont constant 55
software interrupts 97
SolidFill constant 48
SolidLn constant 101
sound operations
NoSound 112
Sound 176
Sound procedure 176
source debugging compiler switch 212
SP register, value of, 177
SPtr function 177
Sqr function 177
Sqrt function 177
square of argument 177
square root of argument 177
SS register, value of 177
SSeg function 177

294

stack
checking switch directive 221
overflow, switch directive 221
size 218
Stack Checking
command 221
option 221
Str procedure 178
StrCat function 178
StrComp function 179
StrCopy function 179
StrDispose function 180
StrECopy function 180
StrEnd function 181
StrIComp function 181
strict string parameter checking 222
string
convert to 178
convert to number 201
first occurrence of 186
first occurrence of character in 187
last occurrence of character in 187
length of 1~O, 183
point to end of 181
String Var Checking
command 222
option 222
strings
allocating on heap 185
appending 178, 181
comparing 179
up to maximum length 182
without case sensitivity 181, 183
comparing up to maximum length 183
concatenation of 23
converting null-terminated 185
converting to lowercase 184
converting to uppercase 188
copying 179, 180, 186
copying characters 182, 184
deleting 27
disposing of 180
initializing 49
length byte 49
null-terminated 214
relaxed parameter checking of 222
strict parameter checking of 222

Programmer's Reference

StrLCat function 181


StrLComp function 182
StrLCopy function 182
StrLen function 183
StrLIComp function 183
StrLower function 184
StrMove function 184
StrNew function 185
stroked fonts 171
StrPas function 185
StrPCopy function 186
StrPos function 186
StrRScan function 187
StrScan function 187
StrUpper function 188
subdirectory, create a 108
substrings
copying 24
deleting 27
inserting 93
position of 128
Succ function 188
support, technical 2-4
Swap function 188
swapping bytes 188
SwapVectors procedure 189
switch compiler directives 209
symbol reference, compiler switch 221
symbols
conditional 224
CPU 225
local information 217
syntax, extended 214
SysFile constant 43

T
IT command-line option 233
Tab mode 270
Tabs mode 268
TDateTime type in WinDos unit 189
technical support 2-4
terminating a program 40
cause of 41
with exit procedure 41
terminating program 85
Test8086 type in System unit 190
Test8087 variable 190

Index

text attribute variable 191


text attributes 78
text color constants 192
text file, reading from 133
text file record definition 199
text files 36
TextAttr variable
ClrEol and 21
ClrScr and 21
HighVideo and 88
LowVideo and 105
NormVideo and 111
TextBackground and 192
TextColor and 193
TextBackground procedure 192
TextColor procedure 193
TextHeight function 193
TextMode procedure 194
TextRec type 46, 195
TextSettingsType type 196
TextWidth function 196
TFileRec file record type in WinDos unit 197
ThickWidth constant 102
time procedures
GetFTime 68
GetTime 78
SetFTime 160
SetTime 171
Topic search in Help 268
TopOff constant 11
TopOn constant 11
TopText constant 99
TPC.CFG file 233, 235
sample 236
TPL & CFG directory command-line option 233
trapping I/O errors 216
TRegisters type 198
TriplexFont constant 55
Trunc function 198
truncate a value 198
Truncate procedure 198
TSearchRec type 199
TTextRec file record type 199
TURBO.TPL 233, 234
type checking, strings and 222
typecasting, invalid 245
TypeOf function 200

295

types
file record 46, 195
mismatches, error messages 241

U
IU command-line option 234
$UNDEF compiler directive 222, 224
undo 268
unindent
block 267
mode 268, 270
Unit Directories option 234
units, version mismatch errors 246
UnpackTime procedure 200
untyped files, variable 13, 14
UpCase function 200
UserBitLn constant 102
UserCharSize constant 55
UserFill constant 49

V
IV command-line option 235
$V compiler directive 222
Val procedure 201
var, string checking, compiler switch 222
variable
decrementing a 27
environment 66
variables
disposing of 30, 56
DosError 39, 52, 66, 68, 160
dynamic, creating 74, 111
incrementing 89
untyped file 13, 14
VER70 symbol 225
VertDir constant 55
VGA
driver, modifying palette entries for 164
modes, emulated 91
VGAHi 69
VGALo 69
VGAMed 69
video mode constants 33
video operations
AssignCrt 10
CirEol21

296

ClrScr 21
DelLine procedure 28
GotoXY 81
HighVideo 88
InsLine 93
LowVideo 105
NormVideo 111
RestoreCrtMode 143
TextBackground 192
TextColor 193
WhereX202
WhereY 202
Window 203
Write (text) 204
Write (typed) 206
Writeln206
viewports 19
parameter 79
ViewPortType type 202
VMT, pointer to a 200
VolumeID constant 43

W
WhereX function 202
WhereY function 202
White constant 22
White text color constant 192
WideDotFill constant 49
WindMax and WindMin variables 203
WinDos unit
DiskFree function 30
DiskSize function 30
GetCBreak procedure 61
GetDate procedure 63
GetFAttr procedure 66
GetFTime procedure 68
GetIntVec procedure 71
GetTime procedure 78
GetVerify procedure 79
Intr procedure 97
MsDos procedure 110
PackTime procedure 125
SetCBreak procedure 155
SetFTime procedure 160
SetIntVec procedure 161
SetTime procedure 171
SetVerify 172

Programmer's Reference

UnpackTime procedure 200


Window procedure 203
word
delete 266
mark 266
write block 267
Write procedure
text files 204
typed files 206
write records from a variable 14
Writeln procedure 206

x
$X compiler directive 214
XHatchFill constant 49
XORPut constant 13

y
$Y compiler directive 221
Yellow constant 22
Yellow text color constant 192

Z
Zenith Z-449, BGI and 91

Index

297

7.0

R L A N D

Corporate Headquarters: 1800 Green Hills Road , P.O. Box 660001 , Scotts Valley, CA 95067-0001 , (408) 438-8400. Offices in: Australia,
Belgium, Canada, Denmark, France, Germany, Hong Kong, Italy, Japan, Korea, Malaysia, Netherlands, New Zealand , Singapore, Spain,
Sweden, Taiwan, and United Kingdom Part #11 MN-TPL03-70 BOR 4681

You might also like