Borland_C++_Version_3.1_Library_Reference_1992 Borland C Version 3.1 Library Reference 1992

Borland_C++_Version_3.1_Library_Reference_1992 Borland_C++_Version_3.1_Library_Reference_1992

User Manual: Borland_C++_Version_3.1_Library_Reference_1992

Open the PDF directly: View PDF PDF.
Page Count: 671

DownloadBorland_C++_Version_3.1_Library_Reference_1992 Borland C  Version 3.1 Library Reference 1992
Open PDF In BrowserView PDF
3.1

LIBRARY REFERENCE
• RUNTIME LIBRARY
• GLOBAL VARIABLES
• CROSS-REFERENCE

BORLAND

BorlancP c++
Version 3.1

Library Reference

BORLAND INTERNATIONAL, INC. 1800 GREEN HILLS ROAD
P.O. BOX 660001, scons VALLEY, CA 95067-0001

Copyright © 1991, 1992 by Borland International. All rights reserved.
All Borland products are trademarks or registered trademarks of
Borland International, Inc. Other brand and product names are
trademarks or registered trademarks of their respective holders.
Windows, as used in this manual, refers to Microsoft's
implementation of a windows system.

Rl

PRINTED IN THE USA.
10987654

c

o

N

T

Introduction
1
Class and member function
documentation ..................... 1
Chapter 1 The main function
Arguments to main ...................
An example program . . . . . . . . . . . . . . ..
Wildcard arguments ................
An example program . . . . . . . . . . . . ..
Using -p (Pascal calling conventions) ....
The value main returns ................

3
3
4
5
6
7
7

Chapter 2 The run-time library
9
How to use function entries ............ 9
abort ............................... 11
abs ................................. 11
absread ............................. 12
abswrite ............................ 14
access .............................. 14
acos, acosl .......................... 15
alloca . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 16
allocmem, _dos_allocmem ............ 18
arc ................................. 19
arg ................................. 21
asctime .............................. 22
asin, asinl . . . . . . . . . . . . . . . . . . . . . . . . . .. 23
assert ............................... 24
atan,atanl .......................... 25
atan2,atan21 ........................ 26
atexit ............................... 26
atof, _atold .......................... 27
atoi ................................ 29
atol ................................ 30
bar ................................. 30
bar3d ............................... 32
bcd ................................ 33
bdos ............................... 34

E

N

T

bdosptr .............................
bios com ............................
_bios_disk ..........................
bios disk ............................
biosequip ...........................
_bios_equiplist ......................
bioskey .............................
_bios_keybrd . . . . . . . . . . . . . . . . . . . . . . ..
biosmemory . . . . . . . . . . . . . . . . . . . . . . . ..
_bios_memsize ......................
biosprint . . . . . . . . . . . . . . . . . . . . . . . . . . ..
_bios_printer . . . . . . . . . . . . . . . . . . . . . . ..
_bios_serialcom ......................
biostime ............................
_bios_timeofday .....................
brk .................................
bsearch .............................
cabs, cabsl ..........................
calloc ...............................
ceil, ceill ............................
_c_exit. . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
_cexit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
cgets ...............................
_chain_intr . . . . . . . . . . . . . . . . . . . . . . . . ..
chdir ...............................
chdrive ............................
_chmod .............................
chmod ..............................
chsize ..............................
circle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
_clear87 ............................
cleardevice . . . . . . . . . . . . . . . . . . . . . . . . ..
clearerr ..... . . . . . . . . . . . . . . . . . . . . . . ..
clearviewport .......................
clock ...............................
_close, close .........................

s

35
36
38
41
44
45
47
49
51
51
52
53
55
57
58
59
60
62
63
65
65
66
67
69
70
71
72
74
75
76
77
78
79
80
82
82

closedir . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 83
closegraph .......................... 84
clreol ............................... 85
clrscr ............................... 86
complex ......... , .................. 86
conj ................................ 87
_control87 .......................... 88
coreleft ............................. 89
cos, cosl ............................ 90
cosh,coshl .......................... 91
country ............................. 92
cprintf .............................. 93
cputs ............................... 94
_creat, _dos_creat ........... . . . . . . . .. 95
creat ............................... 96
creatnew ............................ 98
crea ttem p . . . . . . . . . . . . . . . . . . . . . . . . . .. 99
cscanf ............................. 100
ctime .............................. 101
ctrlbrk . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 102
delay .............................. 103
delline . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 104
detectgraph ........................ 104
difftime . . . . . . . . . . . . . . . . . . . . . . . . . . .. 107
disable, _disable, enable, _enable ...... 108
div ................................ 110
_dos_close ......................... 111
_dos_creatnew ..................... 112
dosexterr .......................... 113
_dos_findfirst ...................... 114
_dos_findnext ...................... 116
_dos_getdiskfree .................... 117
_dos_getdrive, _dos_setdrive . . . . . . . .. 118
_dos_getfileattr, _dos_setfileattr ....... 119
_dos_getftime, _dos_setftime ......... 120
_dos_gettime, _dos_settime .......... 121
_dos _getvect ....................... 123
_dos_setvect ....................... 124
_dos_write. . . . . . . . . . . . . . . . . . . . . . . .. 125
dostounix .......................... 126
drawpoly .......................... 127
dup ............................... 129
dup2 .............................. 130
ecvt ............................... 132

ellipse . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 133
__emit__ .......................... 134
eof ................................ 136
exec!, execle, execlp, execlpe, execv, execve,
execvp,execvpe .................... 137
_exit .............................. 142
exit ............................... 143
exp, expl . . . . . . . . . . . . . . . . . . . . . . . . . .. 144
fabs, fabsl . . . . . . . . . . . . . . . . . . . . . . . . .. 145
farcalloc ........................... 146
farcoreleft . . . . . . . . . . . . . . . . . . . . . . . . .. 147
farfree . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 148
farheapcheck ....................... 149
farheapcheckfree .................... 149
farheapchecknode .................. 151
farheapfillfree ...................... 152
farheapwalk ........................ 154
farmalloc .......................... 155
farrealloc .......................... 156
fclose .............................. 157
fcloseall ........................... 157
fcvt ............................... 158
fdopen ............................ 159
feof ............................... 161
ferror .............................. 162
fflush. . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 162
fgetc .............................. 164
fgetchar ........................... 165
fgetpos ............................ 165
fgets .............................. 166
filelength .......................... 167
fileno .............................. 168
fillellipse . . . . . . . . . . . . . . . . . . . . . . . . . .. 169
fillpoly ............................ 170
findfirst . . . . . . . . . . . . . . . . . . . . . . . . . . .. 171
find next ........................... 174
floodfill . . . . . . . . . . . . . . . . . . . . . . . . . . .. 175
floor, floorl . . . . . . . . . . . . . . . . . . . . . . . .. 176
flushall ............................ 177
_fmemccpy ........................ 178
_fmemchr . . . . . . . . . . . . . . . . . . . . . . . . .. 178
_fmemcmp ................ '. . . . . . . .. 178
_fmemcpy ......................... 178
_fmemicmp ........................ 178

_fmemset ..........................
fmod, fmodl . . . . . . . . . . . . . . . . . . . . . . ..
fnmerge ...........................
fnsplit . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
fopen ..............................
FP_OFF, FP_SEG ....................
_fpreset . . . . . . . . . . . . . . . . . . . . . . . . . . ..
fprintf . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
fputc ..............................
fputchar ...........................
fputs ..............................
fread ..............................
free ...............................
freemem, _dos_freemem .............
freopen . . . . . . . . . . . . . . . . . . . . . . . . . . ..
frexp, frexpl . . . . . . . . . . . . . . . . . . . . . . ..
fscanf .............................
fseek ..............................
fsetpos ............................
_fsopen ............................
fstat, stat. . . . . . . . . . . . . . . . . . . . . . . . . ..
_fstr* ........................ , .....
ftell ...............................
ftime ..............................
_full path . . . . . . . . . . . . . . . . . . . . . . . . . ..
fwrite .............................
gcvt ...............................
geninterrupt .......................
getarccoords .......................
getaspectratio ......................
getbkcolor .........................
getc ...............................
getcbrk ............................
getch ..............................
getchar ............................
getche .............................
getcolor ............................
getcurdir ..........................
getcwd ............................
getdate, _dos_getdate, _dos_setdate,
setdate ............................
_getdcwd ..........................
getdefaultpalette ....................
getdfree ...........................

178
179
179
181
182
184
185
187
188
188
189
189
190
191
193
194
195
196
197
198
200
·203
203
204
205
206
207
208
209
210
212
213
214
214
215
216
216
218
218
219
220
221
223

getdisk,setdisk .....................
_getdrive ..........................
getdrivername ......................
getdta .............................
getenv .............................
getfat ..............................
getfatd ............................
getfillpattern .......................
getfillsettings . . . . . . . . . . . . . . . . . . . . . ..
getftime, setftime ...................
getgraphmode ..... " ...............
getimage . . . . . . . . . . . . . . . . . . . . . . . . . ..
getlinesettings ......................
getmaxcolor . . . . . . . . . . . . . . . . . . . . . . ..
getmaxmode .......................
getmaxx ...........................
getmaxy ...........................
getmodename ......................
getmoderange ......................
getpalette .................. ~. . . . . . ..
getpalettesize . . . . . . . . . . . . . . . . . . . . . ..
getpass ............................
getpid .............................
getpixel . . . . . . . . . . . . . . . . . . . . . . . . . . ..
getpsp ................ , ............
gets ...............................
gettext . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
gettextinfo .........................
gettextsettings .. . . . . . . . . . . . . . . . . . . ..
gettime, settime . . . . . . . . . . . . . . . . . . . ..
getvect, setvect .....................
getverify . . . . . . . . . . . . . . . . . . . . . . . . . ..
getviewsettings . . . . . . . . . . . . . . . . . . . ..
getw ..............................
getx ...............................
gety ................................
gmtime ............................
gotoxy .............................
graphdefaults ......................
grapherrormsg .....................
_graphfreemem .....................
_graphgetmem .....................
graphresult ........................
harderr, hardresume, hardretn . . . . . . ..

~

iii

224
224
225
226
227
228
229
230
231
233
235
236
238
240
242
243
244
245
247
248
250
251
251
252
254
254
255
256
257
259
260
262
263
264
266
267
268
269
270
271
272
274
276
278

_harderr ...........................
_hardresume .......................
_hardretn ..........................
heapcheck .........................
heapcheckfree ......................
heapchecknode .....................
heapfillfree . . . . . . . . . . . . . . . . . . . . . . . ..
heapwalk ..........................
highvideo . . . . . . . . . . . . . . . . . . . . . . . . ..
hypot, hypotl . . . . . . . . . . . . . . . . . . . . . ..
imag ..............................
imagesize . . . . . . . . . . . . . . . . . . . . . . . . ..
initgraph ..........................
inp ................................
inport .............................
inportb ............................
inpw ..............................
insline . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
installuserdriver ....................
installuserfont . . . . . . . . . . . . . . . . . . . . ..
int86 ..............................
int86x .............................
intdos .............................
intdosx ............................
intr ...............................
ioctl ................................
isalnum. . . . . . . . . . . . . . . . . . . . . . . . . . ..
isalpha ............................
isascii .............................
isatty ..............................
iscntrl .............................
isdigit .............................
isgraph ............................
islower ............................
isprint . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
ispunct ............................
isspace ............................
isupper ............................
isxdigit ............................
itoa ...............................
kbhit ..............................
keep,_dos_keep .... : ...............
labs ...............................
ldexp, ldexpl .......................

281
284
285
285
286
288
289
290
291
292
293
294
295
299
300
301
301
302
303
305
307
308
309
310
311
313
314
315
316
316
317
318
319
319
320
321
321
322
323
323
324
325
328
328

ldiv ...............................
Hind ..............................
line ...............................
linerel .............................
lineto . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
localeconv .........................
localtime . . . . . . . . . . . . . . . . . . . . . . . . . ..
lock ...............................
locking ............................
log, logl ...........................
log10, loglOl . . . . . . . . . . . . . . . . . . . . . . ..
longjmp ...........................
lowvideo ..........................
_lrotl ..............................
_lrotr . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
lsearch ............................
lseek ..............................
ltoa ...............................
_makepath . . . . . . . . . . . . . . . . . . . . . . . ..
malloc .............................
matherr, _matherrl ..................
max ...............................
mblen .............................
mbstowcs . . . . . . . . . . . . . . . . . . . . . . . . ..
mbtowc ...........................
memccpy, _fmemccpy ...............
memchr, _fmemchr . . . . . . . . . . . . . . . . ..
memcmp, _fmemcmp ...............
memcpy, _fmemcpy ................ :
memicmp,_fmemicmp ..............
memmove .........................
memset, _fmemset ..................
min ...............................
mkdir .............................
MK_FP ............................
mktemp ...........................
mktime ............................
modf, modfl . . . . . . . . . . . . . . . . . . . . . . ..
movedata . . . . . . . . . . . . . . . . . . . . . . . . ..
movmem ..........................
moverel ...........................
movetext ..........................
moveto ............................
norm ..............................

iv

329
330
331
332
333
334
335
337
338
340
341
342
343
344
345
346
347
348
349
351
352
354
355
356
356
357
358
358
360
360
361
362
363
363
364
365
366
367
368
369
369
371
372
373

normvideo ..................... . . ..
nosound ...........................
_open, _dos_open ...................
open ...............................
opend~ ............................
outp ...............................
outport,outportb ...................
outpw .............................
outtext ............................
outtextxy ..........................
_OvrInitEms .......................
_OvrInitExt ........................
parsfnm ...........................
peek ..............................
peekb .............................
perror .............................
pieslice ............................
poke ..............................
pokeb .............................
polar ..............................
poly, polyl .........................
pow, powl .........................
pow10,pow101 .....................
printf ..............................
putc ...............................
putch ..............................
putchar . . . . . . . . . . . . . . . . . . . . . . . . . . ..
putenv ............................
putimage ..........................
putpixel ...........................
puts ...............................
puttext ............................
putw ..............................
qsort ..............................
raise ..............................
rand ..............................
randbrd ...........................
randbwr ...........................
random ............................
randomize .........................
_read, _dos_read. . . . . . . . . . . . . . . . . . ..
read .............................. ~
readdir ............................
real ...............................

374
374
375
377
379
381
381
382
383
384
386
386
387
388
389
391
392
393
394
394
395
396
397
398
406
407
407
408
410
412
413
414
414
415
417
418
418
420
422
422
423
425
427
428

realloc . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
rectangle . . . . . . . . . . . . . . . . . . . . . . . . . ..
registerbgidriver . . . . . . . . . . . . . . . . . . ..
registerbgifont . . . . . . . . . . . . . . . . . . . . ..
remove ............................
rename ............................
restorecrtmode .....................
rewind ............................
rewinddir . . . . . . . . . . . . . . . . . . . . . . . . ..
rmdir .............................
rmtmp ............................
_rotl ...............................
_rotr ..............................
sbrk ...............................
scanf ..............................
_searchenv .........................
searchpath .........................
sector .............................
segread . . . . . . . . . . . . . . . . . . . . . . . . . . ..
setactivepage . . . . . . . . . . . . . . . . . . . . . ..
setallpalette ........................
setaspectratio . . . . . . . . . . . . . . . . . . . . . ..
setbkcolor . . . . . . . . . . . . . . . . . . . . . . . . ..
setblock, _dos_setblock ..............
setbuf .............................
setcbrk ............................
setcolor . . . . . . . . . . . . . . . . . . . . . . . . . . ..
_setcursortype ......................
setdta ..............................
setfillpattern .......................
setfillstyle . . . . . . . . . . . . . . . . . . . . . . . . ..
setgraphbufsize .....................
setgraphmode ......................
setjmp .............................
setlinestyle . . . . . . . . . . . . . . . . . . . . . . . ..
seflocale ........................ ~ ..
setmem ............................
setmode ...........................
set_new_handler. . . . . . . . . . . . . . . . . . ..
setpalette ..........................
setrgbpalette .......................
settextjustify .......................
settextstyle . . . . . . . . . . . . . . . . . . . . . . . ..
setusercharsize .....................

v

429
430
431
432
434
435
436
437
438
439
440
441
442
442
443
452
453
454
456
457
458
461
462
464
466
467
468
470
471
472
473
475
477
478
480
483
483
484
485
486
488
490
492
495

setvbuf .................. . . . . . . . . ..
setverify ...........................
setviewport ........................
setvisualpage . . . . . . . . . . . . . . . . . . . . . ..
setwritemode . . . . . . . . . . . . . . . . . . . . . ..
signal ....................... :.....
sin, sinl . . . . . . . . . . . . . . . . . . . . . . . . . . ..
sinh, sinhl . . . . . . . . . . . . . . . . . . . . . . . . ..
sleep ....... :......................
sopen ................ ~ ...... : . . . ..
sound .............................
spawnl, spawnle, spawnlp, spawnlpe,
spawnv, spawnve, spawnvp, and
spawnvpe . . . . . . . . . . . . . . . . . . . . . . . . ..
_splitpath . . . . . . . . . . . . . . . . . . . . . . . . ..
sprintf .. . . . . . . . . . . . . . . . . . . . . . . . . . ..
sqrt, sqrtl ..........................
srand ..............................
sscanf .............................
_status87 ..........................
stime ..............................
stpcpy .............................
strcat, _fstrcat ......... ~ . . . . . . . . . . ..
strchr, _fstrchr . . . . . . . . . . . . . . . . . . . . ..
strcmp .............................
strcmpi ..... . . . . . . . . . . . . . . . . . . . . . ..
strcoll .............................
strcpy .............................
strcspn, _fstrcspn ...................
_strdate . . . . . . . . . . . . . . . . . . . . . . . . . . ..
strdup, _fstrdup ....................
_strerror ...........................
strerror . . . . . . . . . . . . . . . . . . . . . . . . . . ..
strftime . . . . . . . . . . . . . . . . . . . . . . . . . . ..
stricmp, _fstricmp ...................
strlen, _fstrlen ......................
strlwr, _fstrlwr . . . . . . . . . . . . . . . . . . . . ..
strncat, jstrncat ....................
strncmp, _fstrncmp .................
strncmpi . . . . . . . . . . . . . . . . . . . . . . . . . ..
strncpy, _fstrncpy . . . . . . . . . . . . . . . . . ..
strnicmp, _fstrnicmp ................
strnset, _fstrnset ....................
strpbrk, _fstrpbrk ...................

496
498
499
500
501
503
507
508
509
510
512

strrchr, _fstrrchr ....................
strrev, _fstrrev . . . . . . . . . . . . . . . . . . . . ..
strset, _fstrset . . . . . . . . . . . . . . . . . . . . . ..
strspn, _fstrspn ......... . . . . . . . . . . ..
strstr, _fstrstr ............ . . . . . . . . . ..
_strtime ...........................
~trtod, _strtold . . . . . . . . . . . . . . . . . . . . ..
strtok, _fstrtok . . . . . . . . . . . . . . . . . . . . ..
strtol ................... . . . . . . . . . ..
strtoul . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
strupr, _fstrupr .....................
strxfrm ............................
swab ..............................
system ............................
tan, tanl ...........................
tanh, tanhl .........................
tell. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
tempnam ..........................
texta ttr ............................
textbackground .....................
textcolor .. . . . . . . . . . . . . . . . . . . . . . . . ..
textheight . . . . . . . . . . . . . . . . . . . . . . . . ..
textrnode ..........................
textwid th ..........................
time ...............................
tmpfile .......... :.................
tmpnam ...........................
toascii ................... . . . . . . . . ..
_tolower . . . . . . . . . . . . . . . . . . . . . . . . . ..
tolower . . . . . . . . . . . . . . . . . . . . . . . . . . ..
_toupper. . . . . . . . . . . . . . . . . . . . . . . . . ..
toupper . . . . . . . . . . . . . . . . . . . . . . . . . . ..
tzset ...............................
ultoa ..............................
umask .............................
ungetc .............................
ungetch ...........................
unixtodos . . . . . . . . . . . . . . . . . . . . . . . . ..
unlink .............................
unlock .............................
utime .............................
va_arg, va_end, va_start .............
vfprintf ............................
vfscanf ............................

513
516
518
518
519
520
522
522
523
524
524
525
526
527
528
529
529
530
531
532
532
534
535
535
536
537
538
539
539
540
541

vi

542
543
543
544
545
545
546
547
548
550
551
551
552
553
554
554
555
556
558
559
560
562
563
565
566
567
568
569
569
570
571
572
572
574
575
576
577
578
579
580
581
582
584
586

vprintf ............................
vscanf .............................
vsprintf ............................
vsscanf ............................
wcstombs . . . . . . . . . . . . . . . . . . . . . . . . ..
wctomb ............................
wherex ............................
wherey ............................
window ...........................
_write ... , .................. , ......
write ....................... , ......

587
588
590
591
592
593
593
594
594
595
597

Chapter 3 Global variables
_8087 ..............................
_argc ..............................
_argv ..............................
_ctype ... , ...................... '"
daylight ...........................
directvideo . . . . . . . . . . . . . . . . . . . . . . . ..
environ . . . . . . . . . . . . . . . . . . . . . . . . . . ..
errno, _doserrno, sys_errlist, sys_nerr ..
_fmode ............................
_heaplen ...........................
_new_handler ......................
_osmajor, _osminor .................
_ovrbuffer .........................
_psp ..............................
_stklen ............................

599
599
600
600
600
600
601
601
602
604
605
606
606
607
607
608

timezone ..........................
tzname ............................
_version ................... ;.......
_wscroll ...........................

vii

609
609
609
610

Appendix A Run-time library crossreference
Reasons to access the run-time library
source code ........................
The Borland C++ header files .........
Library routines by category ..........
Classification routines .............
Conversion routines ...............
Directory control routines ..........
Diagnostic routines ...............
Graphics routines .. . . . . . . . . . . . . . ..
Inline routines ....................
Input/output routines .............
Interface routines (DOS, 8086, BIOS) .
Manipulation routines .............
Math routines ....................
Memory routines .................
Miscellaneous routines ............
Process control routines . . . . . . . . . . ..
Text window display routines ......
Time and date routines ............
Variable argument list routines

612
612
616
616
616
616
617
617
618
618
619
620
621
622
622
623
623
623
624

Index

625

611

T

A

B

L

2.1: detectgraph constants ............. 105
2.2: Graphics drivers information ...... 106
2.3: Graphics drivers constants ......... 297

E

s

2.4: Color palettes .................... 297
2.5: Graphics modes .................. 298
2.6: Actual color table ................. 459

viii

N

T

R

o

D

u

c

T

o

N

This manual contains definitions of all the Borland C++ library
routines, common variables, and common defined types, along
with example program code to illustrate how to use most of these
routines, variables, and types.
If you are new to C or C++ programming, or if you are looking for

information on the contents of the Borland C++ manuals, see the
introduction in the User's Guide.
Here is a summary of the chapters in this manual:
Chapter 1: The main function discusses arguments to main

(including wildcard arguments), provides some example
programs, and gives some information on Pascal calling
conventions and the value that main returns.
Chapter 2: The run-time library is an alphabetical reference of all
Borland C++ library functions. Each entry gives syntax,
portability information, an operative description, and return
values for the function, together with a reference list of related
functions and examples of how the functions are used.
Chapter 3: Global variables defines and discusses Borland C++'s
global variables. You can use these to save yourself a great deal of
programming time on commonly needed variables (such as dates,
time, error messages, stack size, and so on).
Appendix A: Run-time library cross-reference contains an
overview of the Borland C++ library routines and header files.
The header files are listed; the library routines are grouped
according to the tasks they commonly perform.

Class and
member function
documentation

Introduction

Certain classes and class member functions are incorporated in
Chapter 2. Here's a list of the classes and member functions and
their page numbers.

The typefaces used in this
manual are used as
described in the User's
Guide.

2

Name

Type

abs
acos
arg
asin
atan
bcd
complex
conj
cos
cosh
exp
imag
log
log10
norm
pow
polar
real
sin
sinh
sqrt
tan
tanh

member function
member function
member function
member function
member function
class
class
member function
member function
member function
member function
member function
member function
member function
member function
member function
member function
member function
member function
member function
member function
member function
member function

Page number

11

15
21
23
25
33
86
87
90
91
144
293
340
341
373
396
394
428
507
508
518
554
554

Borland C++ Library Reference

c

H

A

p

T

R

E

1
The main function
Every C and C++ program must have a main function; where you
place it is a matter of preference. Some programmers place main
at the beginning of the file, others at the end. Regardless of its
location, the following points about main always apply.

Arguments to main
Three parameters (arguments) are passed to main by the Borland
C++ startup routine: argc, argv, and env.
an integer, is the number of command-line arguments
passed to main.
CI argv is an array of pointers to strings (char *[D.

El argc,

• Under 3.0 and higher versions of DOS, argv[O] is the full path
name of the program being run.
• Under versions of DOS before 3.0, argv[O] points to the null
string (nn).
• argv[1] points to the first string typed on the DOS command

line after the program name.
• argv[2] points to the second string typed after the program

name.
• argv[argc-ll points to the last argument passed to main.
• argv[argc] contains null.

Chapter 1, The main function

3

• env is also an array of pointers to strings. Each element of env[]
holds a string of the form ENVVAR=value .
• ENVVAR is the name of an environment variable, such as
PATH or 87 .
• value is the value to which ENVVAR is set, such as
C:\DOS;C:\ TOOLS; (for PATH) or YES (for 87).
If you declare any of these parameters, you must declare them

exactly in the order given: argc, argv, env. For example, the
following are all valid declarations of main's arguments:
main()
main (int argc)
1* legal but very unlikely *1
main(int argc, char * argyl])
main(int argc, char * argv[], char * env[])]

The declaration main (int argc) is legal, but it's very unlikely that
you would use argc in your program without also using the
elements of argv.
The argument env is also available through the global variable
environ. Refer to the environ entry in Chapter 3 and the putenv and
getenv lookup entries in Chapter 2 for more information.

argc and argv are also available via the global variables _argc and
_argv.

An example
program

Here is an example that demonstrates a simple way of using these
arguments passed to main.
1* Program ARGS.C *1

#include 
#include 
int main(int argc, char *argv[], char *env[])
{

int i;
printf("The value of argc is %d \n\n",argc);
printf("These are the %d command-line arguments passed to"
" main:\n\n",argc);
for (i = 0; i < argc; itt)
printf("
argv[%d]: %s\n", i, argv[i]);
printf("\nThe environment string(s) on this system are:\n\n");
for (i = 0; env[i] != NULL; itt)

4

Borland C++ Library Reference

printf("
return 0;

env[%d): %s\n", i, env[i));

Suppose you run ARGS.EXE at the DOS prompt with the
following command line:
C:> args first_arg "arg with blanks" 3 4 "last but one" stop!

Note that you can pass arguments with embedded blanks by
surrounding them with double quotes, as shown by "argument
with blanks" and "last but one" in this example command line.
The output of ARGS.EXE (assuming that the environment
variables are set as shown here) would then be like this:
The value of argc is 7
These are the 7 command-line arguments passed to main:
argv[O):
argv[l):
argv[2):
argv[3):
argv[ 4) :
argv[5):
argv[6):

C:\BORLANDC\ARGS.EXE
first_arg
arg with blanks
3
last but one
stop!

The environment string(s) on this system are:
env [0): COMSPEC=C: \ COMMAND . Cm1
env[l): PROMPT=$p $g
env[2): PATH=C:\SPRINT;C:\DOS;C:\BORLANDC

The maximum combined length of the command-line arguments
passed to main (including the space between adjacent arguments
and the name of the program itself) is 128 characters; this is a DOS
limit.

Wildcard
arguments Command-line arguments containing wildcard characters can be
expanded to all the matching file names, much the same way DOS
expands wildcards when used with commands like COPY. All
you have to do to get wildcard expansion is to link your program
with the WILDARGS.OBJ object file, which is included with
Borland C++.
Once WILDARGS.OBJ is linked into your program code, you can
send wildcard arguments of the type *.* to your main function.
The argument will be expanded (in the argv array) to all files

Chapter 7, The main function

5

matching the wildcard mask. The maximum size of the argv array
varies, depending on the amount of memory available in your
heap.
If no matching files are found, the argument is passed unchanged.
(That is, a string consisting of the wildcard mask is passed to
main.)

Arguments enclosed in quotes (It ... It) are not expanded.
An example program

The following commands will compile the file ARGS.C and link it
with the wildcard expansion module WILDARGS.OBJ, then run
the resulting executable file ARGS.EXE:
BCC ARGS WILDARGS.OBJ
ARGS C:\BORLANDC\INCLUDE\*.H

"*.C"

When you run ARGS.EXE, the first argument is expanded to the
names of all the *.H files in your Borland C++ INCLUDE
directory. Note that the expanded argument strings include the
entire path. The argument *.C is not expanded as it is enclosed in
quotes.
In the IDE, simply specify a project file (from the project menu)
that contains the following lines:
ARGS
WILDARGS.OBJ

Then use the Run I.Arguments option to set the command-line
parameters.
...

For more on TUB, see the
Users Guide.

6

If you prefer the wildcard expansion to be the default, modify
your standard C?LIB library files to have WILDARGS.OBJ linked
automatically. In order to accomplish that, remove SET ARGV
from the libraries and add WILDARGS. The following commands
invoke the Turbo librarian (TLIB) to modify all the standard
library files (assuming the current directory contains the standard
C and C++ libraries and WILDARGS.OBJ):
tlib
tlib
tlib
tlib
tlib

es -setargv twildargs
ee -setargv twildargs
em -setargv twildargs
c1 -setargv twildargs
eh -setargv twildargs

Borland C++ Library Reference

Using -p (Pascal calling conventions)
If you compile your program using Pascal calling conventions
(described in detail in Chapter 2, "Language structure," in the
Programmer's Guide), you must remember to explicitly declare main
as a C type. Do this with the cdecl keyword,like this:
cdecl main(int argc, char * argyll, char * envp[])

The value main returns
The value returned by main is the statu,s code of the program: an
int. If, however, your program uses the routine exit (or _exit) to
terminate, the value returned by main is the argument passed to
the call to exit (or to _exit).
For example, if your program contains the call
exit(l)

the status is 1.

Chapter 7 The main function
I

7

8

Borland C++ Library Reference

c

A

H

p

T

E

R

2
The run-time library
All programming examples in
this chapter are in the online
help system. This means you
can easilv copy them from
help and paste them into
your files.

This chapter contains a detailed description of each of the functions in the Borland C++ library. A few of the routines are
grouped by "family" (the exec ... and spawn ... functions that
create, load, and run programs, for example) because they
perform similar or related tasks. Otherwise, we have included an
individual entry for every routine. For instance, if you want to
look up information about the free routine, you would look under
free; there you would find a listing for free that
summarizes what free does
r.I gives the syntax for calling free
Ell tells you which header file(s) contains the prototype for free
c gives a detailed description of how free is implemented and
how it relates to the other memory-allocation routines
mlists other language compilers that include similar functions
II refers you to related Borland C++ functions
II if appropriate, gives an example of how the function is used, or
refers you to a function entry where there is an example
III

The following sample library lookup entry explains how to find
out such details about the Borland C++ library functions.

How to use function entries
Function

Summary of what function does.

Chapter 2, The run-time library

9

How to use function entries

Syntax

#include 
This part lists the header file(s) containing the prototype for function or
definitions of constants, enumerated types, and so on used by function.
function(modifier parameter[, .. .]);
This gives you the declaration syntax for function; parameter names are
italicized. The [, ... J indicates that other parameters and their modifiers
can follow.
DOS

I
I

UNIX

I
I

Windows

ANSI C

C++ only

The function portability is indicated by marks in the appropriate columns.
Any additional restrictions are discussed in the Remarks section.
• DOS

• UNIX

• Windows

• ANSI C

• C++ only

available for this system
available under this system
compatible with Windows. EasyWin users should see
Appendix C, "Using EasyWin," in the User's Guide for
information about using certain non-Windows compatible
functions (like printf and scant) in programs that run
under Windows.
defined by the ANSI C Standard
requires C++; is not defined by the ANSI C Standard

If more than one function is discussed and their portability features are
exactly identical, only one row is used. Otherwise, each function will be
represented by a single row.
Remarks

10

This section describes what function does, the parameters it takes, and
any details you need to use function and the related routines listed.

Return value

The value that function returns (if any) is given here. If function sets any
global variables, their values are also listed.

See also

Routines related to function that you might want to read about are listed
here. If a routine name contains an ellipsis (funcname ... , .. .funcname,
func ... name), it indicates that you should refer to a family of functions
(for example, exec ... refers to the entire family of exe functions: execl,
execl~, execlp, execlpe, execv, execve, execvp, and execvpe).

Example

/*Here you'll find a small sample program showing the use of function (and
possibly of related functions) .*/

Borland C++ Library Reference

abort

abort
Function
Syntax

Remarks
Return value

Abnormally terminates a program.
#include 
void abort(void);

abort writes a termination message (" Abnormal program termination")
on stderr, then aborts the program by a call to _exit with exit code 3.
abort returns the exit code 3 to the parent process or to DOS.

See also

assert, atexit, exit, _exit, raise, signal, spawn ...

Example

#include 
#include 
int main(void)
{

printf("Calling abort()\n");
abort() ;
return 0; /* This is never reached */

abs
Function
Syntax

Returns the absolute value of an integer.

Real version:
#include 
int abs(int x);
DOS

Rea/abs
Comp/exabs

Remarks

UNIX

•
•

•

Complex version:
#include 
double abs (complex x);

Windows

ANSI C

•
•

•

C++ only

•

abs returns the absolute value of the integer argument x. If abs is called

when stdlib.h has been included, it's treated as a macro that expands to
inline code.

Chapter 2, The run-time library

11

•

abs

If you want to use the abs function instead of the macro, include #undef
abs in your program, after the #include .
Return value

The real version of abs returns an integer in the range of 0 to 32,767, with
the exception that an argument of -32,768 is returned as -32,768. The
complex version of abs returns a double.

See also

cabs, complex, fabs, labs

Example

#include 
#include 
int main (void)
{

int number = -1234;
printf(lI number: %d absolute value: %d\nll, number, abs(number));
return 0;

absread
Function
Syntax

Remarks

Reads absolute disk sectors.
#include 
int absread(int drive, int nsects, long Isect, void *buffer);

absread reads specific disk sectors. It ignores the logical structure of a

disk and pays no attention to files, FATs, or directories.
absread uses DOS interrupt Ox25 to read specific disk sectors.

drive
nsects
Isect
buffer

drive number to read (0 = A, 1 = B, etc.)
number of sectors to read
beginning logical sector number
memory address where the data is to be read

The number of sectors to read is limited to 64K or the size of the buffer,
whichever is smaller.
Return value

If it is successful, absread returns O.

On error, the routine returns -1 and sets the global variable errno to the
value returned by the system call in the AX register.
See also

12

abswrite, biosdisk

Borland C++ Library Reference

absread

Example

#include
#include
#include
#include
#include







#define SECSIZE 512
int main(void)
{

unsigned char buf[SECSIZE];
int i, j, sector, drive;
char str[10];
printf("Enter drive letter: ");
gets (str);
drive = toupper(str[O]) - 'A';
printf("Enter sector number to read: ");
gets (str) ;
sector = atoi(str);
if (absread(drive, 1, sector, &buf) != 0) {
perror("Disk error");
exit (1) ;
printf("\nDrive: %c Sector: %d\n", 'A' + drive, sector);
for (i = 0; i < SECSIZE; i += 16) {
if ((i I 16) == 20) {
printf("Press any key to continue ... ");
getch() ;
printf("\n") ;
printf("%03d: ", i);
for (j = 0; j < 16; j++)
printf("%02X ", buf[i+j]);
printf("\t");
for (j = 0; j < 16; j++)
if (isprint(buf[i+j]))
printf("%c", buf[i+j]);
else printf(".");
printf ("\n");
return 0;

Chapter 2, The run-time library

13

•

abswrite

abswrite
Function
Syntax

Remarks

Writes absolute disk sectors.
#include 
int abswrite(int drive, int nsects, long lsect, void *buffer);

abswrite writes specific disk sectors. It ignores the logical structure of a

disk and pays no attention to files, FATs, or directories.
..

If used improperly, abswrite can overwrite files, directories, and FATs.
abswrite uses DOS interrupt Ox26 to write specific disk sectors.

drive
nsects
lsect
buffer

drive number to write to (0 = A, 1 = B, etc.)
number of sectors to write to
beginning logical sector number
memory address where the data is to be written

The number of sectors to write to is limited to 64K or the size of the buffer,
whichever is smaller.
Return value

If it is successful, abswrite returns o.
On error, the routine returns -1 and sets the global variable errno to the
value of the AX register returned by the system call.

See also

absread, biosdisk

access
Function
Syntax

Remarks

Determines accessibility of a file.
#include 
int access(const char *filename, int amode);

access checks the file named by filename to determine if it exists, and

whether it can be read, written to, or executed.
The list of amode values is as follows:

14

Borland C++ Library Reference

access

06
04
02
01
00
..

Check for read and write permission
Check for read permission
Check for write permission
Execute (ignored)
Check for existence of file

Under DOS, all existing files have read access (amode equals 04), so 00 and
04 give the same result. In the same vein, amode values of 06 and 02 are
equivalent because under DOS write access implies read access.
If filename refers to a directory, access simply determines whether the
directory exists.

Return value

If the requested access is allowed, access returns 0; otherwise, it returns a
value of -1, and the global variable errno is set to one of the following:

ENOENT
EACCES

Path or file name not found
Permission denied

See also

chmod, fstat, stat

Example

#include 
#include 
int file_exists(char *filename);
int main(void) {
printf("Does NOTEXIST.FIL exist: %s\n",
file_exists ("NOTEXISTS.FIL") ? "YES"
return 0;

"NO");

int file_exists(char *filename)
return (access (filename, 0) == 0);

Program output
Does NOTEXIST.FIL exist?

NO

acos acosl
1

Function
Syntax

Calculates the arc cosine.

Real versions:
#include 
double acos(double x);
long double acosl(long double x);

Chapter 2, The run-time library

Complex version:
#include 
complex acos(complex x);

15

acos, acosl

DOS

Realacos
Complex acos

Remarks

UNIX

•
•
•

acosl

Windows

ANSI C

C++ only

•
•
•

•

•
•

acos returns the arc cosine of the input value. acosl is the long double
version; it takes a long double argument and returns a long double result.
Real arguments to acos and acosl must be in the range -1 to I, or else
acos and acosl return NAN and set the global variable errno to

EDOM

Domain error

The complex inverse cosine is defined by
acos(z)
Return value

= -i 109(z + i sqrt(1 -

Z2))

acos and acosl of a real argument between -1 and +1 returns a value in

the range a to pi.

Error handling for these routines can be modified through the functions
matherr and _matherrl.
See Also

asin, atan, atan2, complex, cos, matherr, sin, tan

Example

#include 
#include 
int main (void)
{

double result, x

= 0.5;

result = acos(x);
printf("The arc cosine of %If is %If\n", x, result);
return 0;

olloco
Function
Syntax

16

Allocates temporary stack space.
#include 
void *alloca(size_t size);

Borland C++ Library Reference

olloca

Remarks

alloca allocates size bytes on the stack; the allocated space is automatically

freed up when the calling function exits.

I

Because alloca modifies the stack pointer, do not place calls to alloca in an
expression that is an argument to a function.

If the calling function does not contain any references to local variables in
the stack, the stack will not be restored correctly when the function exits,
resulting in a program crash. To ensure that the stack is restored correctly,
use the following code in the calling function:
char *Pi
char dummy[lli
dummy [01
p

Return value

=

0i

= alloca(nbytes) i

If enough stack space is available, alloca returns a pointer to the allocated
stack area. Otherwise, it returns NULL.

See Also

malloc

Example

#include 
#include 
void test(int a)
{

char *newstacki
int len = ai
char dummy[lli
/* force good stack frame */
dummy [01 = 0 i
printf("SP before calling alloca(Ox%X) = Ox%X\n",len,_SP);
newstack = (char *) alloca(len) i
printf("SP after calling alloca = Ox%X\n",_SP)i
if (newstack)
printf("Alloca(Ox%X) returned %p\n",len,newstack)i
else
printf("Alloca(Ox%X) failed\n",len) i
void main ( )
{

test(256)i
test(16384)i

Chapter 2, The run-time library

I

17

ollocmem, _dos_ollocmem

ollocmem, _dos_ollocmem
Function
Syntax

Remarks

Allocates DOS memory segment.
#include 
int allocmem(unsigned size, unsigned *segp);
unsigned _dos_allocmem(unsigned size, unsigned *segp);

alloemem and _dos_alloemem use the DOS system call Ox48 to allocate a
block of free memory and return the segment address of the allocated
block.

size is the desired size in paragraphs (a paragraph is 16 bytes). segp is a
pointer to a word that will be assigned the segment address of the newly
allocated block.
For alloemem, if not enough room is available, no assignment is made to
the word pointed to by segp.
For _dos_alloemem, if not enough room is available, the size of the largest
available block will be stored in the word pointed to by segp.
All allocated blocks are paragraph-aligned.
-..
Return value

alloemem and _dos_alloemem cannot coexist with malloe.
alloemem returns -1 on success. In the event of error, alloemem returns a
number indicating the size in paragraphs of the largest available block.
_dos_alloemem returns 0 on success. In the event of error,
_dos_alloemem returns the DOS error code and sets the word pointed to

by segp to the size in paragraphs of the largest available block.
An error return from alloemem or _dos_alloemem sets the global variable
_doserrno and sets the global variable errno to
ENOMEM

Not enough memory

See also

eoreleft, freemem, malloe, setbloek

Example

#incl ude 
#include 

int main (void)
{

unsigned int segp, maxb;

18

Borland C++ Library Reference

ollocmem, _dos_ollocmem

unsigned int size
int largest;

64; /* (64*16)

1024 bytes */

/* Use _dos_allocmem, _dos_setblock, and _dos_freemem. */
if (_dos_allocmem(size, &segp) == 0)
printf("Allocated memory at segment: %x\n", segp);
else {
perror("Unable to allocate block.");
printf("Maximum no. of paragraphs"
" available is %u\n", segp);
return 1;

if (_dos_setblock(size * 2, segp, &maxb) == 0)
printf("Grew memory block at segment: %X\n", segp);
else {
perror("Unable to grow block.");
printf("Maximum number of paragraphs"
" available is %u\n", maxb);
_dos_freemem(segp) ;
/* Use allocmem, setblock, and freemem. */
if ((largest = allocmem(size, &segp)) == -1)
printf("Allocated memory at segment: %x\n", segp);
else {
perror("Unable to allocate block.");
printf("Maximum number of paragraphs"
" available is %u\n", largest);
return 1;

if ((largest = setblock(segp, size * 2)) == -1)
printf ("Grew memory block at segment: %X\n", segp);
else {
perror("Unable to grow block.");
printf("Maximum number of paragraphs"
" available is %u\n", largest);
freemem(segp) ;
return 0;

arc
Function
Syntax

Draws an arc.
#include 
void far arc(int x, int y, int stangle, int endangle, int radius);

Chapter 2, The run-time library

19

•

arc

Remarks

arc draws a circular arc in the current drawing color centered at (x,y) with
a radius given by radius. The arc travels from stangle to endangle. If stangle
equals 0 and endangle equals 360, the call to arc draws a complete circle.

The angle for arc is reckoned counterclockwise, with 0 degrees at
30' clock, 90 degrees at 120' clock, and so on.
Note

The linestyle parameter does not affect arcs, circles, ellipses, or pie slices.
Only the thickness parameter is used.

..

If you're using a eGA in high resolution mode or a monochrome graphics
adapter, the examples in this book that show how to use graphics functions may not produce the expected results. If your system runs on a eGA
or monochrome adapter, pass the value 1 to those functions that alter the
fill or drawing color (setcolor, setfillstyle, and setlinestyle, for example),
instead of a symbolic color constant (defined in graphics.h).

Return value

None.

See also

circle, ellipse, fillellipse, getarccoords, getaspectratio, graphresult,
pieslice, sector

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */

int
int
int
int

gdriver = DETECT, gmode, errorcode;
midx, midy;
stangle = 45, endangle = 135;
radius = 100;

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf (" Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */

20

Borland C++ Library Reference

arc

midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor()) ;
/* draw arc */
arc (midx, midy, stangle, endangle, radius);
/* clean up */
getch() ;
closegraph() ;
return 0;

arg
Function
Syntax

Remarks

Gives the angle of a number in the complex plane.
#include 
double arg(complex x);

arg gives the angle, in radians, of the number in the complex plane.

The positive real axis has angle 0, and the positive imaginary axis has
angle pi/2. If the argument passed to arg is complex 0 (zero), arg returns

O.
Return value

arg(x) returns atan2(imag(x), real(x».

See also

complex, norm, polar

Example

#include 
int main(void)
{

double x = 3.1, y = 4.2;
complex z = complex(x,y);
cout « "z = " « z « "\n";
cout «" has real part = " « real(z) « "\n";
cout «" and imaginary part = " « imag (z) « "\n";
cout « "z has complex conjugate = n « conj(z) « "\n";
double mag = sqrt(norm(z));
double ang = arg(z);
cout « "The polar form of z is:\n";
cout«
magnitude ="« mag« "\n";
angle (in radians) = " « ang « "\n";
cout «"

Chapter 2, The run-time library

21

I

arg

cout « "Reconstructing z from its polar form gives:\n";
cout «"
z = " « polar(mag,ang) « "\n";
return 0;

asctime
Function
Syntax

Remarks

Converts date and time to ASCII.
#include 
char *asctime(const struct tm *tblock);

asctime converts a time stored as a structure in *tblock to a 26-character
string of the same form as the ctime string:
Sun Sep 16 01:03:52 1973\n\0

Return value

asctime returns a pointer to the character string containing the date and
time. This string is a static variable that is overwritten with each call to
asctime.

See also

ctime, difftime, ftime, gmtime, localtime, mktime, strftime, stime, time,
tzset

Example

#include 
#include 
#include 
int main (void)
{

struct tm t;
char str[80];
/* sample loading of tm structure */
/* Seconds */
t.tm_sec
1;
/* Minutes */
t.tm_min
30;
/* Hour */
t.tm_hour
9;
/* Day of the Month */
t.tm_mday
22;
/* Month */
t.tm_mon
11;
/* Year - does not include century */
t.tm-year
56;
/* Day of the week */
t.tm_wday
4;
/* Does not show in asctime */
t . tm-yday
0;
/* Is Daylight SavTime
t.tm_isdst
0;
Does not show in asctime */
/* converts structure to null terminated string */

22

Borland C++ Library Reference

asctime

strcpy(str, asctime(&t));
printf("%s\n", str);
return 0;

asin, asinl
Function
Syntax

Calculates the arc sine.

Real versions:
#include 
double asin(double x);
long double asinl(long double x);

asinl
Real asin
Complex asin

Remarks

DOS

UNIX

•
•
•

•

Windows

ANSI C

•
•
•

•

Complex version:
#include 
complex asin(complex x);

C++ only

•

asin of a real argument returns the arc sine of the input value.
asinl is the long double version; it takes a long double argument and
returns a long double result.

Real arguments to asin and asinl must be in the range -1 to 1, or else asin
and asinl return NAN and sets the global variable errno to
EDOM

Domain error

The complex inverse sine is defined by
asin(z)
Return value

= -i * log(i * z + sqrt(1 -

Z2»

asin and asinl of a real argument return a value in the range -pi/2 to

pi/2.

Error handling for these functions can be modified through the functions
matherr and _matherrl.
.
See Also

acos, atan, atan2, complex, cos, matherr, sin, tan

Example

#include 
#include 
int main (void)
{

double result, x = 0.5;
result = asin(x);
printf("The arc sin of %If is %If\n", x, result);

Chapter 2, The run-time library

23

I

asin, asinl

return(O) ;

assert
Function
Syntax

Remarks

Tests a condition and possibly aborts.
#include 
void assert(int test);

assert is a macro that expands to an if statement; if test evaluates to zero,
assert prints a message on stderr and aborts the program (by calling
abort).
assert prints this message:
Assertion failed: test, file filename, line linenum

The filename and linenum listed in the message are the source file name
and line number where the assert macro appears.

If you place the #define NDEBUG directive ("no debugging") in the source
code before the #include  directive, the effect is to comment out
the assert statement.
Return value

None.

See also

abort

Example

#include 
#include 
#include 
struct ITEM {
int key;
int value;
};

/* add item to list, make sure list is not null */
void additem(struct ITEM *itemptr)
assert(itemptr != NULL);
/* add item to list */
int main(void)
{

24

Borland C++ Library Reference

assert

additem(NULL) ;
return 0;

Program output
Assertion failed: itemptr != NULL,
file C:\BC\ASSERT.C, line 12

otan, otani
Function
Syntax

Calculates the arc tangent.

Real versions:

Complex version:

#include 
double atan(double x);
long double atanl(long double x);

#include 
complex atan(complex x)

DOS

alanl
Real alan
Complex alan

Remarks

UNIX

•
•
•

Windows

ANSI C

C++ only

•
•

•
•

•
•

atan calculates the arc tangent of the input value.
atanl is the long double version; it takes a long double argument and
returns a long double result.

The complex inverse tangent is defined by
atan(z) = -0.5 i 10g«(1 + i z)/(1- i z»
Return value

atan and atanl of a real argument return a value in the range -pi/2 to pi/2.

Error handling for these functions can be modified through the functions
math err and _matherrl.
See Also

acos, asin, atan2, complex, cos, matherr, sin, tan

Example

#include 
#include 
int main (void)
{

double result, x = 0.5;
result = atan(x);
printf("The arc tangent of %If is %If\n", x, result);

Chapter 2, The run-time library

25

I

atan2, atan21

return(O) ;

atan2, atan21
Function
Syntax

Calculates the arc t~ngent of y / x.
#include 
double atan2(double y, double x);
long double atan21(1ong double y, long double x);

atan2
atan21

Remarks

DOS

UNIX

•
•

•

Windows

ANSI C

•
•

•

C++ only

atan2 returns the arc tangent of y / x; it produces correct results even when

the resulting angle is near pi/2 or -pi/2 (x near 0).
If both x and yare set to 0, the function sets the global variable errno to
EDOM.
atan21 is the long double version; it takes long double arguments and

returns a long double result.
Return value

atan2 and atan21 return a value in the range -pi to

pi.

Error handling for these functions can be modified through the functions
math err and _matherrl.
See Also

acos, asin, atan, cos, matherr, sin, tan

Example

#include 
#include 
int main(void)
{

double result, x = 90.0, y = 15.0;
result = atan2(y, x);
printf ("The arc tangent ratio of %If is %If\n'', (y / x), result);
return 0;

atexit
Function

26

Registers termination function.

Borland C++ Library Reference

otexit

Syntax

Remarks

#include 
int atexit(void ( * tunc)(void»;

atexit registers the function pointed to by tunc as an exit function. Upon
normal termination of the program, exit calls (*tunc)O just before

returning to the operating system.
Each call to atexit registers another exit function. Up to 32 functions can
be registered. They are executed on a last-in, first-out basis (that is, the last
function registered is the first to be executed).
Return value

atexit returns 0 on success and nonzero on failure (no space left to register

the function).
See also

abort, _exit, exit, spawn ...

Example

#include 
#include 
void exit_fn1(void)
{

printf("Exit function #1 called\n");
void exit_fn2(void)
{

printf("Exit function #2 called\n");
int main(void)
{

/* post exit function #1 */
atexit(exit_fn1);
/* post exit function #2 */
atexit(exit_fn2);
printf("Done in main\n");
return 0;

Function

Converts a string to a floating-point number.

Chapter 2, The run-time library

27

atof, _otold

Syntax

#inc1ude 
double atof(const char *s);
long double _atold(const char *s);
DOS

UNIX

atof

•

•

_atold

•

Remarks

Windows

ANSI C

•

•

C++ only

•

atof converts a string pointed to by s to double; this function recognizes

the character representation of a floating-point number, made up of the
following:
• an optional string of tabs and spaces.
• an optional sign.
• a string of digits and an optional decimal point (the digits can be on
both sides of the decimal point).
• an optional e or E followed by an optional signed integer.
The characters must match this generic format:
[whitespace] [sign] [ddd] [.] [ddd] [e I E[sign]ddd]

atof also recognizes +INF and -INF for plus and minus infinity, and

+NAN and -NAN for Not-a-Number.
In this function, the first unrecognized character ends the conversion.
_atold is the long double version; it converts the string pointed to by s to a

long double.
strtod and _strtold are similar to atof and _atold; they provide better error
detection, and hence are preferred in some applications.
Return value

atof and _atold return the converted value of the input string.

If there is an overflow, atof (or _atold) returns plus or minus HUGE_VAL
(or _LHUGE_VAL), errno is set to ERANGE, and matherr (or _matherrl) is
not called.
See Also

atoi, atol, ecvt, fcvt, gcvt, scanf, strtod

Example

#include 
#include 
int main(void)
{

float f;
char *str

28

= "12345.678";

Borland C++ Library Reference

otof, _otold

f = atof (str) ;
printf("string = %s float

%5.3f\n", str, f);

return 0;

atoi
Function
Syntax

Remarks

Converts a string to an integer.
#include 
int atoi(const char *s);

atoi converts a string pointed to by s to int; atoi recognizes (in the
following order)

an optional string of tabs and spaces
an optional sign
II a string of digits
II
II

The characters must match this generic format:
[ws] [sn] [ddd]

In this function, the first unrecognized character ends the conversion.
There are no provisions for overflow in atoi (results are undefined).
Return value

atoi returns the converted value of the input string. If the string cannot be
converted to a number of the corresponding type (int), the return value is
O.

See also

at of, atol, ecvt, fcvt, gcvt, scanf, strtod

Example

#include 
#include 
int main(void)
int n;
char *str = "12345";
n = atoi (str);
printf("string = %s integer
return 0;

Chapter 2, The run-time library

= %d\n",

str, n);

29

I

otol

atol
Function
Syntax

Converts a

str~ng

to a long.

#include 
long atol(const char *s);
DDS

Remarks

atol converts the string pointed to by s to long. atol recognizes (in the
following order)

• an optional string of tabs and spaces
• an optional sign
• a string of digits
The characters must match this generic format:
[ws] [sn] [ddd]

In this function, the first unrecognized character ends the conversion.
There are no provisions for overflow in atol (results are undefined).
Return value

atol returns the converted value of the input string. If the string cannot be
converted to a number of the corresponding type (long), atol returns O.

See also

atof, atoi, ecvt, fcvt, gcvt, scanf, strtod, strtol, strtoul

Example

#include 
#include 
int main (void)
{

long 1;
char *lstr = "98765432";
1 = atol (lstr) ;
printf("string = %s long
return 0;

= %ld\n", lstr, 1);

bar
Function

30

Draws a two-dimensional bar.

Borland C++ Library Reference

bar

Syntax

DOS

UNIX

Windows

ANSI C

C++ only

•
Remarks

I

#include 
#include 
void far bar(int left, int top, int right, int bottom);

"II

bar draws a filled-in, rectangular, two-dimensional bar. The bar is filled
using the current fill pattern and fill color. bar does not outline the bar; to
draw an outlined two-dimensional bar, use bar3d with depth equal to o.

The upper left and lower right corners of the rectangle are giveri by (left,
top) and (right, bottom), respectively. The coordinates refer to pixels.
Return value

None.

See also

bar3d, rectangle, setcolor, setfillstyle, setlinestyle

Example

#include
#include
#include
#include






int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy, i;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, 1111);
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
print f ( Graphics error: %s \n ", grapherrormsg (errorcode) ) ;
printf("Press any key to halt:");
getch();
exit(l);
/* terminate with an error code */
II

midx = getmaxx() / 2;
midy = getmaxy() / 2;
/* loop through the fill patterns */
for (i=SOLID_FILL; i
void far bar3d(int left, int top, int right, int bottom, int depth, int topflag);
ANSI C

Remarks

c++ only

bar3d draws a three-dimensional rectangular bar, then fills it using the
current fill pattern and fill color. The three-dimensional outline of the bar
is drawn in the current line style and color. The bar's depth in pixels is
given by depth. The topflag parameter governs whether a threedimensional top is put on the bar. If topflag is nonzero, a top is put on;
otherwise, no top is put on the bar (making it possible to stack several
bars on top of one another).

The upper left and lower right corners of the rectangle are given by (left,
top) and (right, bottom), respectively.
To calculate a typical depth for bar:3d, take 25% of the width of the bar,
like this:
bar3d(left,top,right,bottom, (right-left)/4,l)i

Return value

None.

See also

bar, rectangle, setcolor, setfillstyle, setlinestyle

Example

#include
#include
#include
#include






int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcodei
int midx, midy, ii

32

Borland C++ Library Reference

bar3d

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, 1111);
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */

midx = getmaxx() / 2;
midy = getmaxy() / 2;
/* loop through the fill patterns */
for (i=EMPTY_FILL; i
bed bcd(int x);
bed bed (double x);
bed bcd(double x, int decimals);

All of the usual arithmetic operators have been overloaded to work with
bed numbers.

bed numbers have about 17 decimal digits precision, and a range of about
1 x 10-125 to 1 X 10 125.

Chapter 2, The run-time library

33

bed

Use the function real to convert a bcd number back to a float, double, or
long double.

The argument decimals is optional. You can use it to specify how many
decimal digits after the decimal point are to be carried in the conversion.
The number is rounded according to the rules of banker's rounding,
which means round to nearest whole number, with ties being rounded to
an even digit.
Return value

The bcd equivalent of the given number.

See also

real

Example

#inc1ude 
#inelude 
int main(void)
{

bed a = bed(x/3,2); II a third, rounded to nearest penny
double x = 10000.0; II ten thousand dollars
eout « "share of fortune
return 0;

= $"

« a «

"\n";

bdos
Function
Syntax

Remarks

Accesses DOS system calls.
#include 
int bdos(int dosfun, unsigned dosdx, unsigned dosal);

bdos provides direct access to many of the DOS system calls. See your

DOS reference manuals for details on each system call.
For system calls that require an integer argument, use bdos; if they
require a pointer argument, use bdosptr. In the large data models
(compact, large, and huge), it is important to use bdosptr instead of bdos
for system calls that require a pointer as the call argument.

dosfun is defined in your DOS reference manuals.
dosdx is the value of register DX.
dosal is the value of register AL.

34

Borland C++ Library Reference

bdos

Return value

•

The return value of bdos is the value of AX set by the system call.

See also

bdosptr, geninterrupt, int86, int86x, intdos, intdosx

Example

#include 
#include 
/* get current drive as 'A', 'B', ... */
char current_drive (voidl
{

char curdrive;

/ * get current disk as 0, 1, ... * /
curdrive = bdos(Ox19, 0, Ol;
return('A' + curdrivel;
int main (voidl
{

printf("The current drive is %c:\n", current_drive()l;
return 0;

Program output
The current drive is C:

bdosptr
Function
Syntax

Remarks

Accesses DOS system calls.
#include 
int bdosptrCint dosfun, void *argument, unsigned dosal);

bdosptr provides direct access to many of the DOS system calls. See your
DOS reference manuals for details of each system call.

For system calls that require an integer argument, use bdos; if they
require a pointer argument, use bdosptr. In the large data models
(compact, large, and huge), it is important to use bdosptr for system calls
that require a pointer as the call argument. In the small data models, the
argument parameter to bdosptr specifies OX; in the large data models, it
gives the DS:DX values to be used by the system call.

Chapter 2, The run-time library

35

bdosptr

dosfun is defined in your DOS reference manuals.
dosal is the value of register AL.
Return value

The return value of bdosptr is the value of AX on success or -1 on failure.
On failure, the global variables errno and _doserrno are set.

See also

bdos, geninterrupt, int86, int86x, intdos, intdosx

Example

#include 
#incl ude 
/* get current drive as 'A', 'B', ... */
char current_drive (void)
{

char curdrive;
/* get current disk as 0, 1, ... */
curdrive = bdos(Ox19, 0, 0);
return('A' + curdrive);

int rnain(void)
{

printf("The current drive is %c:\n", current_drive());
return 0;

bioscom
Function
Syntax

Remarks

Performs serial I/O.
#include 
int bioscomCint cmd, char abyte, int port);

bioscom performs various RS-232 communications over the I/O port
given in port.

A port value of 0 corresponds to COM1, 1 corresponds to COM2; and so
forth.
The value of cmd can be one of the following:

o Sets the communications parameters to the value in abyte.
1 Sends the character in abyte out over the communications line.
2 Receives a character from the communications line.

36

Bor/and C++ Library Reference

bioscom

3 Returns the current status of the communications port.

abyte is a combination of the following bits (one value is selected from
each of the groups):
Ox02
Ox03

7 data bits
8 data bits

OxOO
Ox04
OxOO
Ox08
Ox18

1 stop bit
2 stop bits
No parity
Odd parity
Even parity

OxOO
Ox20
Ox40
Ox60
Ox80
OxAO
OxCO
OxEO

110 baud
150 baud
300 baud
600 baud
1200 baud
2400 baud
4800 baud
9600 baud

For example, a value of OxEB (OxEO I Ox081 OxOO I Ox03) for abyte sets the
communications port to 9600 baud, odd parity, 1 stop bit, and 8 data bits.
bioscom uses the BIOS Ox14 interrupt.
Return value

For all values of cmd, bioscom returns a 16-bit integer, of which the upper
8 bits are status bits and the lower 8 bits vary, depending on the value of
cmd. The upper bits of the return value are defined as follows:
Bit 15
Bit 14
Bit 13
Bit 12
Bit 11
Bit 10
Bit 9
Bit 8

Time out
Transmit shift register empty
Transmit holding register empty
Break detect
Framing error
Pari ty error
Overrun error
Data ready

If the abyte value could not be sent, bit 15 is set to 1. Otherwise, the
remaining upper and lower bits are appropriately set. For example, if a
framing error has occurred, bit 11 is set to 1.
With a cmd value of 2, the byte read is in the lower bits of the return value
if there is no error. If an error occurs, at least one of the upper bits is set to
1. If no upper bits are set to I, the byte was received without error.
With a cmd value of 0 or 3, the return value has the upper bits set as
defined, and the lower bits are defined as follows:
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2

Chapter 2, The run-time library

Received line signal detect
Ring indicator
Data set ready
Clear to send
Change in receive line signal detector
Trailing edge ring detector

37

bioscom

Bit 1
Bit 0
Example

Change in data set ready
Change in clear to send

#incl ude 
#include 
#define
#define
#define
#define
#define

COMl
DATA_READY OxlOO
TRUE
1
FALSE
0
SETTINGS (Ox80 I Ox02 I OxOO I OxOO)

int main (void)
{

int in, out, status, DONE = FALSEi
bioscom(O, SETTINGS, COMl)i
cprintf(" ... BIOSCOM [ESC] to exit ... \n")i
while (! DONE) {
status = bioscom(3, 0, COMl)i
if (status & DATA_READY)
if ((out = bioscom(2, 0, COMl) & Ox7F)
putch(out)i
if (kbhit ()) {
if ((in = getch())
'\xlB')
DONE = TRUEi
bioscom(l, in, COMl)i

!=

0)

return Oi

Function
Syntax

Remarks

Issues BIOS disk drive services
#include 
unsigned _bios_disk(unsigned cmd, struct diskinfo_t *dinfo);

_bios_disk uses interrupt Ox13 to issue disk operations directly to the

BIOS. The cmd argument specifies the operation to perform, and dinfo
points to a diskinfo_t structure that contains the remaining parameters
required by the operation.
The diskinfo_t structure (defined iIi bios.h) has the following format:

38

Borland C++ Library Reference

struct diskinfo_t {
unsigned drive, head, track, sector, nsectors;
void far *buffer;
};

drive is a number that specifies which disk drive is to be used: 0 for the
first floppy disk drive, 1 for the second floppy disk drive, 2 for the third,
and so on. For hard disk drives, a drive value of Ox80 specifies the first
drive, Ox81 specifies the second, Ox82 the third, and so forth.
For hard disks, the physical drive is specified, not the disk partition. If
necessary, the application program must interpret the partition table
information itself.
Depending on the value of cmd, the other parameters in the diskinfo_t
structure mayor may not be needed.
The possible values for cmd (defined in bios.h) are the following:
_DISK_RESET
Resets disk system, forcing the drive controller to do a hard reset. All
diskinfo_t parameters are ignored.
_DISK_STATUS
Returns the status of the last disk operation. All diskinfo_t parameters
are ignored.
.
_DISK_READ
Reads one or more disk sectors into memory. The starting sector to
read is given by head, track, and sector. The number of sectors is given
by nsectors. The data is read, 512 bytes per sector, into buffer. If the
operation is successful, the high byte of the return value will be oand
the low byte will contain the number of sectors. If an error occurre-d,
the high byte of the return value will have one of the following values:
OxOl
Ox02
Ox03
Ox04
Ox05
Ox06
Ox07
Ox08
Ox09
OxOA
OxOB
OxOC
Oxl0
Oxll
Ox20

Chapter 2~ The run-time library

Bad command.
Address mark not found.
Attempt to write to write-protected disk.
Sector not found.
Reset failed (hard disk).
Disk changed since last operation.
Drive parameter activity failed.
Direct memory access (DMA) overrun.
Attempt to perform DMA across 64K boundary.
Bad sector detected.
Bad track detected.
Unsupported track.
Bad CRC/ECC on disk read.
CRC/ECC corrected data error.
Controller has failed.

39

Ox40 . Seek operation failed.
Ox80
Attachment failed to respond.
OxAA Drive not ready (hard disk only).
OxBB Undefined error occurred (hard disk only).
OxCC Write fault occurred.
OxEO Status error.
OxFF Sense operation failed.
Ox11 is not an error because the data is correct. The value is returned to
give the application an opportunity to decide for itself.
_DISK_WRITE
Writes one or more disk sectors from memory. The starting sector to
write is given by head, track, and sector. The number of sectors is given
by nsectors. The data is written, 512 bytes per sector, from buffer. See
_DISK_READ (above) for a description of the return value.
_DISK_VERIFY
Verifies one or more sectors. The starting sector is given by head, track,
and sector. The number of sectors is given by nsectors. See
_DISK_READ (above) for a description of the return value.
_DISK_FORMAT
Formats a track. The track is specified by head and track. buffer points to
a table of sector headers to be written on the named track. See the
Technical Reference Manual for the IBM PC for a description of this table
and the format operation.
Return value

_bios_disk returns the value of the AX register set by the INT Ox13 BIOS

call.
See Also

absread, abswrite, biosdisk

Example

#inc1 ude 
#include 
int main(void)
{

struct diskinfo_t dinfo;
int result;
static char dbuf[512];
dinfo.drive = 0;
dinfo.head = 0;
dinfo.track = 0;
dinfo.sector =. 1;
dinfo.nsectors = 1;
dinfo.buffer = dbuf;

/*
/*
/*
/*
/*
/*

drive number for A: */
disk head number */
track number */
sector number */
sector count */
data buffer */

printf ("Attempting to read from drive A: \n");
result = _bios_disk (_DISK_READ, &dinfo);

40

Borland C++ Library Reference

if ((result & OxffOO) == 0) {
printf("Disk read from A: successful.\n");
printf("First three bytes read are Ox%02x Ox%02x Ox%02x\n",
dbuf[O] & Oxff, dbuf[l] & Oxff, dbuf[2] & Oxff);
else
printf("Cannot read drive A, status
return 0;

=

Ox%02x\n", result);

biosdisk
Function
Syntax

Remarks

Issues BIOS disk drive services.
#include 
int biosdisk(int cmd, int drive, int head, int track, int sector, int nsects,
void *buffer);

biosdisk uses interrupt Ox13 to issue disk operations directly to the BIOS.

drive is a number that specifies which disk drive is to be used: 0 for the
first floppy disk drive, 1 for the second floppy disk drive, 2 for the third,
and so on. For hard disk drives, a drive value of Ox80 specifies the first
drive, Ox81 specifies the second, Ox82 the third, and so forth.
For hard disks, the physical drive is specified, not the disk partition. If
necessary, the application program must interpret the partition table
information itself.

cmd indicates the operation to perform. Depending on the value of cmd,
the other parameters mayor may not be needed.
Here are the possible values for cmd for the IBM PC, XT, AT, or PS/2, or
any compatible system:

o Resets disk system, forcing the drive controller to do a hard reset.
All other parameters are ignored.
1

Returns the status of the last disk operation. All other parameters
are ignored.

2

Reads one or more disk sectors into memory. The starting sector
to read is given by head, track, and sector. The number of sectors is
given by nsects. The data is read, 512 bytes per sector, into buffer.

Chapter 2, The run-time library

41

biosdisk

3

Writes one or more disk sectors from memory. The starting sector
to write is given by head, track, and sector. The number of sectors is
given by nsects. The data is written, 512 bytes per sector, from

buffer.
4

Verifies one or more sectors. The starting sector is given by head,
track, and sector. The number of sectors is given by nsects.

5

Formats a track. The track is specified by head and track. buffer
points to a table of sector headers to be written on the named
track. See the Technical Reference Manual for the IBM PC for a
description of this table and the format operation.

The following cmd values are allowed only for the XT, AT, PS/2, and
compatibles:

-..

6

Formats a track and sets bad sector flags.

7

Formats the drive beginning at a specific track.

8

Returns the current drive parameters. The drive information is
returned in buffer in the first 4 bytes.

9

Initializes drive-pair characteristics.

10

Does a long read, which reads 512 plus 4 extra bytes per sector.

11

Does a long write, which writes 512 plus 4 extra bytes per sector.

12

Does a disk seek.

13

Alterna tes disk reset.

14

Reads sector buffer.

15

Writes sector buffer.

16

Tests whether the named drive is ready.

17

Recalibrates the drive.

18

Controller RAM diagnostic.

19

Drive diagnostic.

20

Controller internal diagnostic.

biosdisk operates below the level of files on raw sectors. It can destroy file

contents and directories on a hard disk.
Return value

biosdisk returns a status byte composed of the following bits:

OxOO
Ox01

42

Opera tion successful.
Bad command.

Borland C++ Library Reference

biosdisk

Ox02
Ox03
Ox04
Ox05
Ox06
Ox07
Ox08
Ox09
OxOA
OxOB
OxOC
OxlO
Oxll
Ox20
Ox40
Ox80
OxAA
OxBB
OxCC
OxEO
OxFF

•

Address mark not found.
Attempt to write to write-protected disk.
Sector not found.
Reset failed (hard disk).
Disk changed since last operation.
Drive parameter activity failed.
Direct memory access (DMA) overrun.
Attempt to perform DMA across 64K boundary.
Bad sector detected.
Bad track detected.
Unsupported track.
Bad CRC/ECC on disk read.
CRC/ECC corrected data error.
Controller has failed.
Seek operation failed.
Attachment failed to respond.
Drive not ready (hard disk only).
Undefined error occurred (hard disk only).
Write fault occurred.
Status error.
Sense operation failed.

Oxll is not an error because the data is correct. The value is returned to
give the application an opportunity to decide for itself.
See also

absread, abswrite

Example

#incl ude 
#include 
int main (void)
{

#define
#define
#define
#define
#define
#define

CMD
DRIVE
HEAD
TRACK
SECT
NSECT 1

/*
/*
/*
/*
/*
/*

read sector command */
drive number for A: */
disk head number */
track number */
sector number */
sector count */

int result;
char buffer[5l2l;
printf ("Attempting to read from drive A: \n");
result = biosdisk(CMD, DRIVE, HEAD, TRACK, SECT, NSECT, buffer);
if (result == 0)
printf("Disk read from A: successful.\n");
else
printf ("Attempt to read from drive A: failed. \n");

Chapter 2, The run-time library

43

biosdisk

return 0 i

biosequip
Function

Checks equipment.

Syntax

#include 
int biosequip(void);

Remarks
Return value

biosequip uses BIOS interrupt axIl to return an integer describing the
equipment connected to the system.

The return value is interpreted as a collection of bit-sized fields. The IBM
PC values follow:
Bits 14-15 Number of parallel printers installed

00 = a printers
01 = 1 printer
10 = 2 printers
11 = 3 printers

DOS only sees two
ports but can be
pushed to see four;
the IBM PS/2 can
see up to eight.

44

Bit 13
Bit 12

Serial printer attached
Game I/O attached

Bits 9-11

Number of COM ports
000 = a ports
001 = 1 port
010 = 2 ports
all = 3 ports
100 = 4 ports
101 = 5 ports
110 = 6 ports
111 = 7 ports

Bit 8

Direct memory access (DMA)
a = Machine has DMA
1 = Machine does not have DMA; for example, PC Jr.

Bits 6-7

Number of disk drives
00 = 1 drive
01 = 2 drives

Borland C++ Library Reference

biosequip

10 = 3 drives
11 = 4 drives, only if bit 0 is 1

Example

Bit 4-5

Initial video mode
00 = Unused
01 = 40x25 BW with color card
10 = 80x25 BW with color card
11 = 80x25 BW with mono card

Bits 2-3

Motherboard RAM size
00 = 16K
01 = 32K
10 = 48K
11 = 64K

Bit 1
Bit 0

Floating-point coprocessor
Boot from disk
I

#include 
#include 

int main(void)
{

int equip_check;
/* get the current equipment configuration */
equip_check = biosequip();
/* check to see if there is a coprocessor installed */
if (equip_check & CO_PROCESSOR_MASK)
printf ("There is a math coprocessor installed. \n") ;
else
printf("No math coprocessor installed.\n");
return 0;

Function
Syntax

Checks equipment.
#include 
unsigned _bios_ equi plist( void);

Chapter 2, The run-time library

45

Remarks

_bios_equiplist uses BIOS interrupt Oxll to return an integer describing

the equipment connected to the system.
Return value

DOS only sees two
ports but can be
pushed to see four;
the IBM PS/2 can
see up to eight.

The return value is interpreted as a collection of bit-sized fields. The IBM
PC values follow:
Bits 14-15

Number of parallel printers installed
00 = 0 printers
01 = 1 printer
10 = 2 printers
11 = 3 printers

Bit 13
Bit 12

Serial printer attached
Game 1/0 attached

Bits 9-11

Number of COM ports
000 = 0 ports
001 = 1 port
010 = 2 ports
011 = 3 ports
100 = 4 ports
101 = 5 ports
110 = 6 ports
111 = 7 ports

Bit 8

Direct memory access (DMA)

o= Machine has DMA

1 = Machine does not have DMA; for example, PC Jr.

Example

Bits 6-7

Number of disk drives
00 = 1 drive
01 = 2 drives
10 = 3 drives
11 = 4 drives, only if bit 0 is 1

Bit 4-5

Initial video mode
00 = Unused
01 = 40x25 BW with color card
10 = 80x25 BW with color card
11 = 80x25 BW with mono card

Bits 2-3

Motherboard RAM size
00 = 16K
01 = 32K
10 = 48K
11 = 64K

Bit 1
Bit 0

Floating-point coprocessor
Boot from disk

#include 
#include 
#define CO_PROCESSOR_MASK Ox0002

46

Borland C++ Library Reference

biosequip

10 = 3 drives
11 = 4 drives, only if bit 0 is 1

Example

Bit 4-5

Initial video mode
00 = Unused
01 = 40x25 BW with color card
10 = 80x25 BW with color card
11 = 80x25 BW with mono card

Bits 2-3

Motherboard RAM size
00 = 16K
01 = 32K
10 = 48K
11 = 64K

Bit 1
Bit 0

Floating-point coprocessor
Boot from disk \

#include 
#include 

int main(void)
{

int equip_check;
/* get the current equipment configuration */
equip_check = biosequip();
/* check to see if there is a coprocessor installed */
if (equip_check & CO_PROCESSOR_MASK)
printf("There is a math coprocessor installed.\n");
else
printf ("No math coprocessor installed. \n");
return 0;

Function
Syntax

Checks equipment.
#include 
unsigned _bios_equiplist(void);

Chapter 2, The run-time library

45

Remarks

_bios_equiplist uses BIOS interrupt Oxll to return an integer describing

the equipment connected to the system.
Return value

DOS only sees two
ports but can be
pushed to see four;
the IBM PS/2 can
see up to eight.

The return value is interpreted as a collection of bit-sized fields. The IBM
PC values follow:
Bits 14-15

Number of parallel printers installed
00 = 0 printers
01 = 1 printer
10 = 2 printers
11 = 3 printers

Bit 13
Bit 12

Serial printer attached
Game 1/0 attached

Bits 9-11

Number of COM ports
000 = 0 ports
001 = 1 port
010 = 2 ports
011 = 3 ports
100 = 4 ports
101 = 5 ports
110 = 6 ports
111 = 7 ports

Bit 8

Direct memory access (DMA)

o = Machine has DMA

1 = Machine does not have DMA; for example, PC Jr.

Example

Bits 6-7

Number of disk drives
00 = 1 drive
01 = 2 drives
10 = 3 drives
11 = 4 drives, only if bit 0 is 1

Bit 4-5

Initial video mode
00 = Unused
01 = 40x25 BW with color card
10 = 80x25 BW with color card
11 = 80x25 BW with mono card

Bits 2-3

Motherboard RAM size
00 = 16K
01 = 32K
10 = 48K
11 = 64K

Bit 1
Bit 0

Floating-point coprocessor
Boot from disk

#include 
#include 
#define CO_PROCESSOR_MASK Ox0002

46

Borland C++ Library Reference

int main (void)
{

unsigned equip_check;
/* Get the current equipment configuration. */
equip_check = _bios_equiplist();
/* Check to see if there is a coprocessor installed. */
if (equip_check & CO_PROCESSOR_MASK)
printf("There is a math coprocessor installed.\n");
else
printf("No math coprocessor installed.\n");
return 0;

bioskey
Function
Syntax

Remarks
Return value

Keyboard interface, using BIOS services directly.
#include 
int bioskey(int cmd);

bioskey performs various keyboard operations using BIOS interrupt Ox16.
The parameter cmd determines the exact operation.

The value returned by bioskey depends on the task it performs,
determined by the value of cmd:

o

If the lower 8 bits are nonzero, bioskey returns the ASCII character for the next keystroke waiting in the queue or the next key
pressed at the keyboard. If the lower 8 bits are zero, the upper 8
bits are the extended keyboard codes defined in the IBM PC

Technical Reference Manual.
1

This tests whether a keystroke is available to be read. A return
value of zero means no key is available. The return value is
OxFFFFF (-1) if Ctrl-Brkhas been pressed. Otherwise, the value of
the next keystroke is returned. The keystroke itself is kept to be
returned by the next call to bioskey that has a cmd value of zero.

2

Requests the current shift key status. The value is obtained by
ORing the following values together:

Chapter 2, The run-time library

47

bioskey

Bit 7
Bit 6
Bit 5
Bit 4

Bit 3
Bit 2
Bit 1
Bit 0
Example

Ox80
Ox40
Ox20
OxlO
Ox08
Ox04
Ox02
OxOl

Insert on
Gaps on
Num Lock on
Scroll Lock on
Altpressed
Gtrl pressed
f- Shift pressed
---7 Shift pressed

#include 
#include 
#include 
#define
#define
#define
#define

RIGHT OxOl
LEFT Ox02
CTRL Ox04
ALT
Ox08

int main(void)
{

int key, modifiers;
/* function 1 returns 0 until a key is pressed */
while (bioskey(l) == 0);
/* function 0 returns the key that is waiting */

key

= bioskey(O);

/* use function 2 to determine if shift keys are used */
modifiers = bioskey(2);
if (modifiers) {
printf("[");
if (modifiers & RIGHT) printf("RIGHT");
if (modifiers & LEFT) printf ("LEFT") ;
if (modifiers & CTRL) printf("CTRL");
if (modifiers & ALT)
printf("ALT");
printf("j");
/* print out the character read */
if (isalnum(key & OxFF))
printf("'%c'\n", key);
else
printf ("%#02x\n", key);
return 0;

48

Borland C++ Library Reference

I
Function
Syntax

Remarks

Keyboard interface, using BIOS services directly.
#include 
unsigned _bios _keybrd (unsigned cmd);

_bios_keybrd performs various keyboard operations using BIOS interrupt

Ox16. The parameter cmd determines the exact operation.
Return value

The value returned by _bios_keybrd depends on the task it performs,
determined by the value of cmd (defined in bios.h):
_KEYBRD_READ
If the lower 8 bits are nonzero, _bios_keybrd returns the ASCII character for the next keystroke waiting in the queue or the next key pressed
at the keyboard. If the lower 8 bits are zero, the upper 8 bits are the
extended keyboard codes defined in the IBM PC Technical Reference
Manual.
_NKEYBRD_READ
Use this value instead of _KEYBRD_READY to read the keyboard
codes for enhanced keyboards, which have additional cursor and
function keys.
_KEYBRD _READY
This tests whether a keystroke is available to be read. A return value of
zero means no key is available. The return value is OxFFFF (-1) if etrlBrk has been pressed. Otherwise, the value of the next keystroke is
returned, as described in _KEYBRD _READ (above). The keystroke
itself is kept to be returned by the next call to _bios_keybrd that has a
cmd value of _KEYBRD _READ or _NKEYBRD _READ.
_NKEYBRD_READY
Use this value to check the status of enhanced keyboards, which have
additional cursor and function keys.
_KEYBRD_SHIFTST ATUS
Requests the current shift key status. The value will contain an OR of
zero or more of the following values:
Bit 7

Chapter 2, The run-time library

Ox80

Insert on

49

Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0

Ox40
Ox20
Ox10
Ox08
Ox04
Ox02
Ox01

Caps on
Num Lock on
Scroll Lock on

Altpressed
CtrT pressed ,
Left Shift pressed
Right Sh,lt pressed

_NKEYBRD_SHIFfST A TUS
Use this value instead of _KEYBRD_SHIFfSTATUS to request the full
16-bit shift key status for enhanced keyboards. The return value will
contain an OR of zero or more of the bits defined above in
_KEYBRD_SHIFfST ATUS, and additionally, any of the following bits:
Bit 15
Bit 14
Bit 13
Bit 12
Bit 11
Bit 10
Bit 9
Bit 8

Example

Ox8000
Ox4000
Ox2000
Ox1000
Ox0800
Ox0400
Ox0200
Ox0100

Sys Req pressed
Caps Lock pressed
Num Lock pressed
Scroll Lock pressed
Right Aft pressed
Right Ctr/pressed
Left Alt pressed
Left CtrT pressed

#include 
#include 
#include 
#define
#define
#define
#define

RIGHT
LEFT
CTRL
ALT

OxOl
Ox02
Ox04
OxOB

int main (void)
(

int key, modifiers;
/* Wait until a key is pressed */
while (_bios_keybrd(_KEYBRD_READY)

== 0);

/* Fetch the key that is waiting */

key

= _bios_keybrd(_KEYBRD_READ);

/* Determine if shift keys are used */
modifiers = _bios_keybrd(_KEYBRD_SHIFTSTATUS);
if (modifiers) {
printf (" [") ;
if (modifiers & RIGHT) printf("RIGHT");
if (modifiers & LEFT) printf("LEFT");
if (modifiers & CTRL) printf("CTRL");

50

Borland C++ Library Reference

if (modifiers & ALT)
print f ( "1" ) ;

I

printf("ALT");

/* print out the character read */
if (isalnum(key & OxFF))
printf("'%c'\n", key);
else
printf("%#02x\n", key);
return 0;

biosmemory
Function
Syntax

Remarks

Return value
Example

Returns memory size.
#include 
int biosmemory( void);

biosmemory returns the size of RAM memory using BIOS interrupt Ox12.
This does not include display adapter memory, extended memory, or
expanded memory.
biosmemory returns the size of RAM memory in lK blocks.
#include 
#include 
int main(void)
{

int memory_size;
memory_size = biosmemory();
/* returns value up to 640K */
printf("RAM size = %dK\n", memory-size);
return 0;

Function
Syntax

Returns memory size.
#include 
unsigned _bios_memsize( void);

Chapter 2, The run-time library

51

I
•I

DOS

Remarks

UNIX

I
I

Windows

I
I

ANSI C

I C++ only
I

_bios_memsize returns the size of RAM memory using BIOS interrupt

Ox12. This does not include display adapter memory, extended memory,
or expanded memory.
Return value
Example

_bios_memsize returns the size of RAM memory in lK blocks.
#include 
#include 
int main(void)
{

unsigned memory_size;
memory_size = _bios_memsize();
/* returns value up to 640K */
printf("RAM size = %dK\n", memory_size);
return 0;

biosprint
Function
Syntax

Remarks

Printer I/O using BIOS services directly.
#include 
int biosprint(int cmd, int abyte, int port);

biosprint performs various printer functions on the printer identified by
the parameter port using BIOS interrupt Ox17.

A port value of 0 corresponds to LPTl; a port value of 1 corresponds to
LPT2; and so on.
The value of cmd can be one of the following:

o
1
2

Prints the character in abyte.
Initializes the printer port.
Reads the printer status.

The value of abyte can be 0 to 255.
Return value

52

The value returned from any of these operations is the current printer
status, which is obtained by ORing these bit values together:

Borland C++ Library Reference

biosprint

Bit 0
Bit 3
Bit 4
Bit 5
Bit 6
Bit, 7
Example

OxOl
Ox08
OxlO
Ox20
Ox40
Ox80

I

Device time out
I/O error
Selected
Out of paper
Acknowledge
Not busy

#inc1ude 
#include 
#include 
int main (void)
{

#define STATUS
#define PORTNUM 0

/* printer status command */
/* port number for LPTl */

int status, abyte=Oi
printf("Please turn off your printer. Press any key to continue\n")i
getch()i
status = biosprint(STATUS, abyte, PORTNUM) i
if (status & OxOl)
printf("Device time out.\n")i
if (status & Ox08)
printf("I/O error.\n")i
if (status & OxlO)
printf("Selected.\n") i
if (status & Ox20)
printf ("Out of paper. \n ") i
if (status & Ox40)
printf("Acknowledge.\n") i
if (status & Ox80)
printf ("Not busy. \n ") i
return 0i

Function
Syntax

Remarks

Printer I/O using BIOS services directly.
#include 
unsigned _bios_printerCint cmd, int port, int abyte);

_bios_printer performs various printer functions on the printer identified
by the parameter port using BIOS interrupt Ox17.

Chapter 2, The run-time library

53

A port ,value of 0 corresponds to LPTl; a port value of 1 corresponds to
LPT2; and so on.
The value of cmd can be one of the following values (defined in bios.h):

Return value

_PRINTER_WRITE

Prints the character in abyte. The value of
abyte can be 0 to 255.

_PRINTER_IN IT

Initializes the printer port. The abyte
argument is ignored.

_PRINTER_STATUS

Reads the printer status. The abyte
argument is ignored.

The value returned from any of these operations is the current printer
status, which is obtained by ORing these bit values together:
Bit 0
Bit 3
Bit 4
Bit 5
Bit 6
Bit 7

Example

OxOl
Ox08
OxlO
Ox20
Ox40
Ox80

Device time out
I/O error
Selected
Out of paper
Acknowledge
Not busy

#include 
#include 
#include 
int main(void)
{

unsigned status, abyte = 0;
printf("Please turn off your printer. Press any key to continue\n");
getch() ;
status = _bios-printer(_PRINTER_STATUS, PORTNUM, abyte);
if (status & OxOl)
printf("Device time out.\n");
if (status & Ox08)
printf("I/O error.\n");
if (status & OxlO)
printf("Selected.\n");
if (status & Ox20)
printf ("Out of paper. \n");
if (status & Ox40)
printf ("Acknowledge. \n");
if (status & Ox80)
printf ("Not busy. \n");
return 0;

54

Borland C++ Library Reference

I

bios_serialcom
Function
Syntax

Remarks

Performs serial I/O.
#include 
unsigned _bios_serialcom(int cmd, int port, char abyte);

_bios_serialcom performs various RS-232 communications over the I/O

port given in port.
A port value of 0 corresponds to COM1, 1 corresponds to COM2, and so
forth.
The value of cmd can be one of the following values (defined in bios.h):
Sets the communications parameters to the value in

abyte.
Sends the character in abyte out over the
communications line.
_COM_RECEIVE

Receives a character from the communications line.
The abyte argument is ignored.

_COM_STATUS

Returns the current status of the communications
port. The abyte argument is ignored.

When cmd is _COM_INIT, abyte is a OR combination of the following bits:
Select only one of these:
_COM_CHR7
7 data bits
_COM_CHR8
8 data bits
Select only one of these:
_COM_STOP1
_COM_STOP2

1 stop bit
2 stop bits

Select only one of these:
_COM_NOPARITY
No parity
_COM_ODDPARITY
Odd parity
_COM_EVENPARITY
Even parity
Select only one of these:
_COM_lID

Chapter 2, The run-time library

110 baud

55

_COM_150
_COM_300
_COM_600
_COM_1200
_COM_2400
_COM_4800
_COM_9600

150 baud
300 baud
600 baud
1200 baud
2400 baud
4800 baud
9600 baud

For example, a value of ( _COM_9600 I _COM_ODOPARITY I
_COM_STOP1 I _COM_CHR8) for abyte sets the communications port to
9600 baud, odd parity, 1 stop bit, and 8 data bits. _bios_serialcom uses the
BIOS Ox14 interrupt.
Return value

For all values of cmd, _bios_serialcom returns a 16-bit integer of which
the upper 8 bits are status bits and the lower 8 bits vary, depending on the
value of cmd. The upper bits of the return value are defined as follows:
Bit 15
Bit 14
Bit 13
Bit 12
Bit 11
Bit 10
Bit 9
Bit 8

Time out
Transmit shift register empty
Transmit holding register empty
Break detect
Framing error
Parity error
Overrun error
Da ta ready

If the abyte value could not be sent, bit 15 is set to 1. Otherwise, the
remaining upper and lower bits are appropriately set. For example, if a
framing error has occurred, bit 11 is set to 1.

With a cmd value of _COM_RECEIVE, the byte read is in the lower bits of
the return value if there is no error. If an error occurs, at least one of the
upper bits is set to 1. If no upper bits are set to 1, the byte was received
without error.
With a cmd value of _COM_INIT or _COM_ST AT US, the return value has
the upper bits set as defined, and the lower bits are defined as follows:
Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
Bit 2
Bit 1
Bit 0
Example

56

Received line signal detect
Ring indicator
Data set ready
Clear to send
Change in receive line signal detector
Trailing edge ring detector
Change in data set ready
Change in clear to send

#incl ude 
#include 

Borland C++ Library Reference

#define
#define
#define
#define
#define

COMI
DATA_READY OxIOO
TRUE
1
FALSE
SETTINGS (_COM_1200

I
_COM_CHR7

_COM_STOPI

I

_COM_NOPARITY)

int main(void)
{

unsigned in, out, status;
_bios_serialcom(_COM_INIT, COM1, SETTINGS);
cprintf(" ... _BIOS_SERIALCOM [ESC] to exit ... \r\n");
for (;;) {
status = _bios_serialcom(_COM_STATUS, COM1, 0);
if (status & DATA_READY)
if ((out = _bios_serialcom(_COM_RECEIVE, COMI, 0) & Ox7F)
putch(out) ;
if (kbhi t ( )) {
if ((in = getch()) == '\xIB')
break;
_bios_serialcom(_COM_SEND, COMI, in);

!=

0)

return 0;

biostime
Function
Syntax

Remarks

Reads or sets the BIOS timer.
#include 
long biostime(int cmd, long newtime);

biostime either reads or sets the BIOS timer. This is a timer counting ticks
since midnight at a rate of roughly 18.2 ticks per second. biostime uses
BIOS interrupt OxlA.

If cmd equals 0, biostime returns the current value of the timer.
If cmd equals 1, the timer is set to the
Return value

long value in

newtime.

When biostime reads the BIOS timer (cmd = 0), it returns the timer's
current value.

Chapter 2, The run-time library

57

biostime

Example

#incl ude 
#include 
#include 
int main(void)
{

long bios_time;
clrscr () ;
cprintf(IIThe number of clock ticks since midnight is:\r\n");
cprintf("The number of seconds since midnight is:\r\n");
cprintf("The number of minutes since midnight is:\r\n");
cprintf("The number of hours since midnight is:\r\n");
cprintf("\r\nPress any key to quit:");
while(!kbhit()) {
bios_time = biostime(O, OL);
gotoxy(50, 1);
cprintf ("%lu", bios_time);
gotoxy(50, 2);
cprintf ("%. 4f", bios_time / CLK_TCK);
gotoxy (50, 3) ;
cprintf(I%.4f", bios_time CLK_TCK / 60) ;
gotoxy (50, 4) ;
cprintf(I%.4f", bios_time CLK_TCK / 3600) ;
return 0;

Function
Syntax

Reads or sets the BIOS timer.
#include 
unsigned _bios_timeofday(int cmd, long *timep);
ANSI C

Remarks

C++ only

_bios_timeofday either reads or sets the BIOS timer. This is a timer

counting ticks since midnight at a rate of roughly 18.2 ticks per second.
_bios_timeofday uses BIOS interrupt Ox1A.

The cmd parameter can be either of the following values:
_TIME_GETCLOCK

58

The functions stores the current BIOS timer value
into the location pointed to by timep. If the timer
has not been read or written since midnight, the

Borland C++ Library Reference

function returns 1. Otherwise, the function returns

O.
_TIME_SETCLOCK

Return value
Example

The function sets the BIOS timer to the long value
pointed to by timep. The function does not return a
value.

The _bios_timeofday returns the value in AX that was set by the BIOS
timer call.
#include 
#include 
#include 
int main(void)
{

long bios_time;
clrscr () ;
cprintf("The number of clock ticks since midnight is:\r\n");
cprintf("The number of seconds since midnight is:\r\n");
cprintf("The number of minutes since midnight is:\r\n");
cprintf("The number of hours since midnight is:\r\n");
cprintf("\r\nPress any key to quit:");
while(!kbhit()) {
_bios_timeofday(_TIME_GETCLOCK, &bios_time);
gotoxy (50, 1);
cprintf("%lu", bios_time);
gotoxy(50, 2);
cprintf ("%. 4f", bios_time CLK_TCK);
gotoxy (50, 3) ;
cprintf(I%.4f", bios_time / CLK_TCK / 60) ;
gotoxy(50, 4) ;
cprintf(I%.4f", bios_time / CLK_TCK / 3600) ;
return 0;

brk
Function
Syntax

Changes data-segment space allocation.
#include 
int brk(void *addr);

Chapter 2, The run-time library

59

brk

Remarks

brk dynamically changes the amount of space allocated to the calling
program's heap. The change is made by resetting the program's break
value, which is the address of the first location beyond the end of the data
segment. The amount of allocated space increases as the break value
increases.
brk sets the break value to addr and changes the allocated space
accordingly.

This function will fail without making any change in the allocated space if
such a change would allocate more space than is allowable.
Return value

Upon successful completion, brk returns a value of O. On failure, this
function returns a value of -1 and the global variable errno is set to
ENOMEM

Not enough memory

See also

coreleft, sbrk

Example

#inc1ude 
#include 
int rnain(void)
{

char *ptr;
printf("Changing allocation with brk()\n");
ptr = (char *) rnalloc(l);
printf("Before brk() call: %lu bytes free\n", coreleft());
brk (ptrtlOOO) ;
printf(" After brk() call: %lu bytes free\n", coreleft());
return 0;

bsearch
Function
Syntax

Remarks

60

Binary search of an array.
#include 
void *bsearch(const void *key, canst void *base, size_t nelem, size_t width,
int (*fcmp)(const void *, const void *»;

bsearch searches a table (array) of nelem elements in memory, and returns
the address of the first entry in the table that matches the search key. The

Borland C++ Library Reference

bsearch

array must be in order. If no match is found, bsearch returns O. Note that
because this is a binary search, the first matching entry is not necessarily
the first entry in the table.
The type size_t is defined as an unsigned integer.
EI
tI

nelem gives the number of elements in the table.
width specifies the number of bytes in each table entry.

The comparison routine *fcmp is called with two arguments: eleml and
elem2. Each argument points to an item to be compared. The comparison
function compares each of the pointed-to items (*eleml and *elem2), and
returns an integer based on the results of the comparison.
For bsearch, the *fcmp return value is

< a if *eleml < *elem2
== aif *eleml == *elem2
> a if *eleml > *elem2
Return value

bsearch returns the address of the first entry in the table that matches the
search key. If no match is found, bsearch returns O.

See also

Ifind, Isearch, qsort

Example

#include 
#include 
typedef int (*fptr) (const void*, const void*);
#define NELEMS (arr) (sizeof (arr) / sizeof (arr [0] ) )
int numarray[] = {123, 145, 512, 627, 800, 933);
int numeric (const int *p1, const int *p2)
return(*p1 - *p2);
#pragma argsused
int lookup(int key)
{

int

*itemptr;

/* The cast of (int(*) (const void *,const void*)) is needed to avoid a type
mismatch error at compile time */
itemptr = (int *) bsearch (&key, numarray, NELEMS(numarray),
sizeof (int), (fptr)numeric);
return (itemptr != NULL);
int main(void)
{

Chapter 2, The run-time library

61

II

bsearch

if (lookup(512))
printf("512 is in the table.\n");
else
printf("512 isn't in the table.\n");
return 0;

cabs, cabsl
Function
Syntax

Calculates the absolute value of complex number.
#include 
double cabs(struct complex z);
long double cabsl(struct _complexl z);
DOS

cabs

•

cabsl

•

Remarks

UNIX

Windows

ANSI C

•
•

•

•

C++ only

cabs is a macro that calculates the absolute value of z, a complex number.
z is a structure with type complex; the structure is defined in math.h as
struct complex {
double x, y;
};

where x is the real part, and y is the imaginary part.
Calling cabs is equivalent to calling sqrt with the real and imaginary
components of z as shown here:
sqrt(z.x * z.x + z.y * z.y)

cabsl is the long double version; it takes a a structure with type _complexl

as an argument, and returns a long double result. The structure is defined
in math.h as
struct _complexl {
long double x, y;
};

If you are using C++, use the complex type defined in complex.h, and the
function abs.
Return value

cabs (or cabsl) returns the absolute value of z, a double. On overflow,
cabs (or cabsl) returns HUGE_VAL (or _LHUGE_VAL) and sets the

global variable errno to

62

Borland C++ Library Reference

cabs, cabsl

ERANGE

Result out of range

Error handling for these functions can be modified through the functions
math err and matherrl.
See Also

abs, complex, fabs, labs, matherr

Example

#include 
#include 
·#ifdef _cplusplus
#include 
#endif
#ifdef _cplusplus /* if C++
void print_abs(void)

1

use class complex */

{

complex z(1.0 2.0);
double absval;
1

absval = abs(z);
printf("The absolute value of %.2lfi %.2lfj is %.2lf"1
real(z) imag(z) absval);
1

#else

1

/* Function below is for C (and not C++). */

void print_abs(void)
{

struct complex z;
double absval;
z.x

= 2.0;

z.y = 1.0;

absval

=

cabs(z);

printf("The absolute value of %.2lfi %.2lfj is %.2lf"1
Z.XI Z'YI absval);
#endif
int main(void)
{

print_abs() ;
return 0;

collac
Function

Allocates main memory.

Chapter 2, The run-time library

63

calloe

Syntax

#include 
void *calloc(size_t nitems, size_t size);
DOS

I

• I
Remarks

I
• I

UNIX

Windows

ANSI C

I C++ only

"

I
"
calloc provides access to the C memory heap. The heap is available for

dynamic allocation of variable-sized blocks of memory. Many data
structures, such as trees and lists, naturally employ heap memory
allocation.
All the space between the end of the data segment and the top of the
program stack is available for use in the small data models (tiny, small,
and medium), except for a small margin immediately before the top of the
stack. This margin is intended to allow some room for the application to
grow on the stack, plus a small amount needed by DOS.
In the large data models (compact, large, and huge), all space beyond the
program stack to the end of physical memory is available for the heap.
calloc allocates a block of size nitems x size. The block is cleared to O. If
you want to allocate a block larger than 64K, you must use farcalloc.
Return value

calloc returns a pointer to the newly allocated block. If not enough space
exists for the new block or nitems or size is 0, calloc returns null.

See also

farcalloc, free, malloc, realloc

Example

#include 
#include 
#include 
int main(void)
{

char *str

= NULL;

/* allocate memory for string */
str = (char *) calloc(lO, sizeof(char));
/* copy "Hello" into string */
strcpy(str, "Hello");
/* display string */
printf("String is %s\n", str);
/* free memory */
free (str) ;
return 0;

64

Borland C++ Library Reference

ceil, ceill

ceil/ceill
Function
Syntax

Rounds up.
#include 
double ceil(double x);
long double ceill(long double x);
DOS

ceil

•
•

ceill

Remarks

UNIX

Windows

ANSI C

•
•

•

•

C++ only

ceil finds the smallest integer not less than x.
ceill is the long double version; it takes a long double argument and

returns a long double result.
Return value

These functions return the integer found as a double (ceil) or a long
double (ceill).

See Also

floor, fmod

Example

#include 
#include 
int main(void)
{

double down, up, number = 123.54;
down = floor (number) ;
up = ceil(number);
printf(lI or iginal number
%5.2lf\n", number);
printf(" number rounded down %5.2lf\n", down);
printf(" number rounded up
%5.2lf\n", up);
return 0;

Function
Syntax

Perform _exit cleanup without terminating the program.
#include 
void _c_exit(void);

Chapter 2, The run-time library

65

Remarks

_c_exit performs the same cleanup as _exit, except that it does not

terminate the calling process. Interrupt vectors altered by the startup code
are restored; no other cleanup is performed.
Return value

None.

See Also

abort, atexit, _cexit, exec ... , exit, _exit, _dos_keep, signal, spawn ...

Example

#include
#include
#include
#include
#include







main( )
{

int fd;
char c;
if ((fd = open("_c_exit.c",O_RDONLY)) < 0) {
printf("Unable to open _c_exit.c for reading\n");
return 1;
if (read(fd,&c,l) != 1)
printf("Unable to read from open file handle %d before _c_exit\n",fd);
else
printf("Successfully read from open file handle %d before _c_exit\n",fd);
printf("Interrupt zero vector before _c_exit = %Fp\n",_dos_getvect(O));
_c_exit();
if (read(fd,&c,l) != 1)
printf("Unable to read from open file handle %d after _c_exit\n",fd);
else
printf("Suc cessfully read from open file handle %d after _c_exit\n",fd);
printf("Interrupt zero vector after _c_exit = %Fp\n",_dos_getvect(O));
return 0;

Function
Syntax

66

Perform exit cleanup without terminating the program.
#include 
void _cexit(void);

Borland C++ Library Reference

Remarks

_cexit performs the same cleanup as exit, except that it does not close files

or terminate the calling process. Buffered output (waiting to be output) is
written, any registered "exit functions" (posted with atexit) are called, and
interrupt vectors altered by the startup code are restored.
Return value

None.

See Also

abort, atexit, _c_exit, exec ... , exit, _exit, _dos_keep, signal, spawn ...

Example

#include
#include
#include
#include
#include







main( )
{

int fd;
char c;
if ((fd = open("_cexit.c",O_RDONLY)) < 0) {
printf("Unable to open _cexit.c for reading\n");
return 1;
if (read(fd,&c,1) != 1)
printf("Unable to read from open file handle %d before _cexit\n",fd);
else
printf("Successfully read from open file handle %d before _cexit\n",fd);
printf("Interrupt zero vector before _cexit = %Fp\n",_dos_getvect(O));
_cexit() ;
if (read(fd,&c,1) != 1)
printf("Unable to read from open file handle %d after _cexit\n",fd);
else
printf("Successfully read from open file handle %d after _cexit\n",fd);
printf("Interrupt zero vector after _cexit = %Fp\n",_dos_getvect(O));
return 0;

cgets
Function
Syntax

Reads a string from the console.
#include 
char *cgets(char *str);

Chapter 2, The run-time library

67

cgets

Remarks

cgets reads a string of characters from the console, storing the string (and
the string length) in the location pointed to by str.
cgets reads characters until it encounters a carriage-return/linefeed

(CR/LF) combination, or until the maximum allowable number of
characters have been read. If cgets reads a carriage return/linefeed
combination, it replaces the combination with a \0 (null terminator)
before storing the string.
Before cgets is called, set strro] to the maximum length of the string to be
read. On return, str[1] is set to the number of characters actually read. The
characters read start at str[2] and end with a null terminator. Thus, str
must be at least str[O] plus 2 bytes long.
Return value

On success, cgets returns a pointer to str[2].

See also

cputs, fgets, getch, getche, gets

Example

#include 
#include 
main( )
{

char buffer[83];
char *p;
/* there's space for 80 characters plus the NULL terminator */
buffer[O] = 81;
printf("Input some chars:");
p = cgets(buffer);
printf("\ncgets read %d characters: \"%s\"\n", buffer[1], p);
printf("The returned pointer is %p, buffer[O] is at %p\n", p, &buffer);
/* leave room for 5 characters plus the NULL terminator */
buffer[O] = 6;
printf("Input some chars:");
p = cgets(buffer);
printf("\ncgets read %d characters: \"%s\"\n", buffer[1], p);
printf("The returned pointer is %p, buffer[O] is at %p\n", p, &buffer);
return 0;

68

Borland C++ Library Reference

Function
Syntax

Remarks

Chains to another interrupt handler.
#include 
void _chain_intr(void (interrupt far *newhandler)O);

The _chain_intr functions passes control from the currently executing
interrupt handler to the new interrupt handler whose address is
newhandler. The current register set is NOT passed to the new handler.
Instead, the new handler receives the registers that were stacked (and
possibly modified in the stack) by the old handler. The new handler can
simply return, as if it were the original handler. The old handler is not
entered again.
The _chain_intr function may be called only by C interrupt functions. It is
useful when writing a TSR that needs to insert itself in a chain of interrupt
handlers (such as the keyboard interrupt).

Return value
See Also
Example

_chain intr does not return a value.
_dos_getvect, _dos_setvect, _dos_keep
#inc 1ude 
#include 
#include 
#ifdef __ cplusplus
#define __CPPARGS
#else
#define __CPPARGS
#endif
typedef void interrupt (*fptr) (__CPPARGS);
static void mesg(char *s)
{

while (*s)
bdos (2, *s++, 0);
#pragma argsused
void interrupt handler2(unsigned bp, unsigned di)
{

Chapter 2, The run-time library

69

_chainjntr

_enable();
mesg("In handler 2.\r\n");
if (di == 1)
mesg("DI is l\r\n");
else
mesg("DI is not l\r\n");
di++;
#pragma argsused
void interrupt handler1(unsigned bp, unsigned di)
{

_enable() ;
mesg("In handler 1.\r\n");
if (di == 0)
mesg("DI is O\r\n");
else
mesg("DI is not D\r\n");
di++;
mesg("Chaining to handler 2.\r\n");
_chain_intr(handler2);
void main ()
{

_dos_setvect(128, (fptr) handler1);
print f ( "About to generate interrupt 128 \n" ) ;
_01 = 0;

geninterrupt(128);
printf("DI was 0 before interrupt, is now Ox%x\n",_DI);
exit(O) ;

chdir
Function

Changes current directory.

Syntax

#include 
int chdir(const char *path);

Remarks

chdir causes the directory specified by path to become the current working

directory. path must specify an existing directory.
A drive can also be specified in the path argument, such as

70

Borland C++ Library Reference

chdir

chdir ("a: \ \BC")

but this changes only the current directory on that drive; it doesn't change
the active drive.
Return value

Upon successful completion, chdir returns a value of o. Otherwise, it
returns a value of -1, and the global variable ernlO is set to
ENOENT

Path or file name not found

See also

getcurdir, getcwd, getdisk, mkdir, rmdir, setdisk, system

Example

#include 
#include 
#include 
char old_dir[MAXDIRl;
char new_dir[~~XDIRl;
int main(void)
{

if (getcurdir(O, old_dir))
perror("getcurdir() ");
exit(l) ;
printf("Current directory is: \\%s\n", old_dir);
if (chdir("\\")) {
perror("chdir() ");
exit(l);
if (getcurdir(O, new_dir))
perror("getcurdir() ");
exit(l);
printf ("Current directory is now: \ \%s\n", new_dir);
printf("\nChanging back to orignal directory: \\%s\n", old_dir);
if (chdir(old_dir)) {
perror("chdir() ");
exit(l) ;
return 0;

_chdrive
Function
Syntax

Sets current disk drive.
#include 
int _chdrive(int drive);

Chapter 2, The run-time library

71

_chdrive

Remarks

_chdrive sets the current drive to the one associated with drive: 1 for A, 2

for B, 3 for C, and so on.
Return value

_chdrive returns 0 if the current drive was changed successfully;
otherwise, it returns -1.

See Also

_dos_setdrive, _getdrive

Example

#include 
#include 
int main{void)
{

if (_chdrive(3) == 0)
printf{"Successfully changed to drive C:\n");
else
printf{"Cannot change to drive C:\n");
return 0;

Function
Syntax

Remarks

Gets or sets DOS file attributes.
#include 
#include 
int _chmod(const char *path, int tunc [, int attrib]);

_chmod can either fetch or set the DOS file attributes. If tunc is 0, the

function returns the current DOS attributes for the file. If tunc is 1, the
attribute is set to attrib.

attrib can be one of the following symbolic constants (defined in dos.h):
FA_RDONLY
FA_HIDDEN
FA_SYSTEM
FA_LABEL
FA_DIREC
FA_ARCH

72

Read-only attribute
Hidden file
System file
Volume label
Directory
Archive

Borland C++ Library Reference

Return value

Upon successful completion, _chmod returns the file attribute word;
otherwise, it returns a value of -1.
In the event of an error, the global variable errno is set to one of the
following:
ENOENT
EACCES

See also

chmod,_creat

Example

#include
#include
#include
#include

Path or file name not found
Permission denied






int get_file_attrib(char *filename);
int main(void)
char filename[128];
int attrib;
printf("Enter a file name:");
scanf ("%s", filename);
attrib = get_file_attrib(filename);
if (attrib == -1)
switch (ermo) {
case ENOENT printf ("Path or file not found. \n");
break;
case EACCES printf ("Permission denied. \n");
break;
default:
printf("Error number: %d", ermo);
break;
else
if (attrib & FA_RDONLY)
printf("%s is read-only.\n", filename);
if (attrib & FA_HIDDEN)
printf("%s is hidden.\n", filename);
if (attrib & FA_SYSTEM)
printf("%s is a system file.\n", filename);
if (attrib & FA_LABEL)
printf ("%s is a volume label. \n", filename);
if (attrib & FA_DIREC)
printf ( "%s is a directory. \n", filename);
if (attrib & FA_ARCH)
printf("%s is an archive file.\n", filename);

Chapter 2, The run-time library

73

return 0i
/* returns the attributes of a DOS file */
int get_file_attrib(char *filename) {
return (_chmod(filename, 0)) i

chmod
Function
Syntax

Remarks

Changes file access mode.
#include 
int chmod(const char *path, int amode);

chmod sets the file-access permissions of the file given by path according
to the mask given by amode. path points to a string; *path is the first
character of that string.

amode can contain one or both of the symbolic constants S_IWRITE and
S_IREAD (defined in syi:; \stat.h).

Return value

Value of amode

Access permission

S_IWRITE
S_IREAD
S_IREAD I S_IWRITE

Permission to write
Permission to read
Permission to read and write

Upon successfully changing the file access mode, chmod returns O.
Otherwise, chmod returns a value of -1.
In the event of an error, the global variable errno is set to one of the
following:
ENOENT
EACCES

74

Path or file name not found
Permission denied

See also

access, _chmod, fstat, open, sopen, stat

Example

#incl ude
#include
#include
#include
#include







Borland C++ Library Reference

chmod

int main(void)

•

{

char filename[64];
struct stat stbuf;
int amode;
printf("Enter name of file: ");
scanf("%s", filename);
if (stat (filename, &stbuf) != 0)
perror("Unable to get file information");
return(l) ;
if (stbuf.st_mode & S_IWRITE)
printf("Changing to read-only\n");
amode = S_IREAD;
else {
printf("Changing to read-write\n");
amode = S_IREADIS_IWRITE;
if (chmod(filename, amode) != 0) {
perror("Unable to change file mode");
return(l) ;
return(O) ;

chsize
Function
Syntax

Remarks

Changes the file size.
#include 
int chsize(int handle, long size);

chsize changes the size of the file associated with handle. It can truncate or
extend the file, depending on the value of size compared to the file's
original size.

The mode in which you open the file must allow writing.
If chsize extends the file, it will append null characters (\0). If it truncates
the file, all data beyond the new end-of-file indicator is lost.

Chapter 2, The run-time library

75

I

chsize
\

Return value

On success, chsize returns O. On failure, it returns -1 and the global
variable errno is set to one of the following:
EACCESS
EBADF
. ENOSPC

Permission denied
Bad file number
UNIX-not DOS

See also

close, _creat, creat, open

Example

#include 
#include 
#incl ude 
int main(void)
{

int handle;
char buf[ll] = "0123456789";
/* create a text file containing 10 bytes */
handle = open ("DUMMY. FIL", O_CREAT);
write (handle, buf, strlen(buf));
/* truncate the file to 5 bytes in size */
chsize(handle, 5);
/* close the file */
close (handle) ;
return 0;

circle
Function
Syntax

Remarks

Draws a circle of the given radius with its center at (x,y).
#include 
void far circleCint x, int y, int radius);

circle draws a circle in the current drawing color with its center at (x,y)

and the radius given by radius.
_

The linestyle parameter does not affect arcs, circles, ellipses, or pie slices.
Only the thickness parameter is used.
If your circles are not perfectly round, adjust the aspect ratio.

Return value

76

None.

Borland C++ Library Reference

circle

See also

arc, ~lIipse, fillellipse, getaspectratio, sector, setaspectratio

Example

#inc1ude
#include
#include
#include






int main (void)
{

1* request autodetection *1
int gdriver = DETECT, gmode, errorcode;
int midx, midy, radius = 100;
1* initialize graphics and local variables *1
initgraph(&gdriyer, &gmode, "H);
1* read result of initialization *1
errorcode = graphresult();
if (errorcode != grOk) { 1* an error occurred *1
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
1* terminate with an error code *1
midx = getmaxx() I 2;
midy = getmaxy() I 2;
setcolor(getmaxcolor()) ;

1* draw the circle *1
circle (midx, midy, radius);
1* clean up *1
getch() ;
c10segraph ( ) ;
return 0;

_clear87
Function
Syntax

Clears floating-point status word.
#include 
unsigned int _clear87 (void);

Chapter 2, The run-time library

77

_clear87

Remarks

_clear87 clears the flo~ting-point status word, which is a combination of

the 80x87 status word and other conditions detected by the 80x87
exception handler.
Return value

The bits in the value returned indicate the floating-point status before it
was cleared. For information on the status word, refer to the constants
defined in float.h.

See also

_controI87, _fpreset, _status87

Example

#include 
#include 
int main(void)
{

float x;
double y = 1.Se-lOO;
printf("\nStatus 87 before error: %X\n", _status87());
x = y; /* create underflow and precision loss */
printf("Status 87 after error: %X\n", _status87());
_clear87 () ;
printf("Status 87 after clear: %X\n", _status87());
y = x;
return 0;

cleardevice
Function

Clears the graphics screen.

Syntax

#include 
void far cleardevice(void);

Remarks

cleardevice erases (that is, fills with the current background color) the

entire graphics screen and moves the CP (current position) to home (0,0).
Return value

78

None.

See also

clearviewport

Example

#include
#include
#include
#include






Borland C++ Library Reference

cleardevice

int main(void)
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) (
/* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */

midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor()) ;
/* for centering screen messages */
settextjustify(CENTER_TEXT, CENTER_TEXT);
/* output a message to the screen */
outtextxy(midx, midy, "Press any key to clear the screen:");

getch() ;
/* wait for a key */
/* clear the screen */
cleardevice() ;
/* output another message */
outtextxy(midx, midy, "Press any key to quit:");
/* clean up */
getch () ;
closegraph ( ) ;
return 0;

clearerr
Function
Syntax

Resets error indication.
#include 
void clearerr(FILE *stream);

Chapter 2, The run-time library

79

clearerr

Remarks

clearerr resets the named stream's error and end-of-file indicators to O.
Once the error indicator is set, stream operations continue to return error
status until a call is made to clearerr or rewind.

The end-of-file indicator is reset with each input operation.
Return value

None.

See also

eof, feof, ferror, perror, rewind

Example

#include 
int main (void)
{

FILE *fp;
char Chi
/* open a file for writing */
fp = fopen("DUMMY.FIL", "W");
/* force an error condition by attempting to read */
ch = fgetc(fp);
printf("%c\n",ch);
if (ferror(fp)) {
/* display an error message */
printf("Error reading from DUMMY.FIL\n");
/* reset the error and EOF indicators */
clearerr (fp) ;
fclose (fp) ;
return 0i

clearviewport
Function
Syntax

Remarks
Return value

80

Clears the current viewport.
#include 
void far clearviewport( void);

clearviewport erases the viewport and moves the CP (current position) to
home (0,0), relative to the viewport.

None.

Borland C++ Library Reference

clearviewport

See also

cleardevice, getviewsettings, setviewport

Example

#include
#include
#include
#include

I






#define CLIP_ON 1

/* activates clipping in viewport */

int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode, ht;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, no);
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */
setcolor(getmaxcolor()) ;
ht = textheight("W");
/* message in default full-screen viewport */
outtextxy(O, 0, "* <-- (0, 0) in default viewport");
/* create a smaller viewport */
setviewport(50, 50, getmaxx()-50, getmaxy()-50, CLIP_ON);
/* display some messages */
outtextxy(O, 0, "* <-- (0, 0) in smaller viewport");
outtextxy(O, 2*ht, "Press any key to clear viewport:");
getch();
/* wait for a key */
clearviewport();
/* clear ,the viewport */
/* output another message */
outtextxy(O, 0, "Press any key to quit:");
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

Chapter 2, The run-time library

81

clock

clock
Function
Syntax

Remarks

Determines processor time.
#include 
clock_t clock(void);

clock can be used to determine the time interval between two events.

To determine the time in seconds, the value returned by clock should be
divided by the value of the macro CLK_TCK.
Return value

The clock function returns the processor time elapsed since the beginning
of the program invocation. If the processor time is not available, or its
value cannot be represented, the function returns the value -1.

See also

time

Example

#include 
#include 
#include 
int main (void)
{

clock_t start, end;
start = clock ( ) ;
delay(2000) ;
end = clock ( ) ;
printf ("The time was: %f\n", (end - start) / CLK_TCK);
return 0;

_close, close
Function
Syntax

Closes a file.
#include 
int _close(int handle);
int close(int handle);
DOS

82

_close

•

close

•

UNIX

•

Windows

ANSI C

c++

only

•
•

Borland C++ Library Reference

_close, close

Remarks

_close and close close the file associated with handle, a file handle
obtained from a _creat, creat, creatnew, creattemp, dup, dup2, _open, or
open call.

t::>

These functions do not write a Ctrl-Z character at the end of the file. If you
want to terminate the file with a Ctrl-Z, you must explicitly output one.

Return value

Upon successful completion, _close and close return O. Otherwise, these
functions return a value of -1.
_close and close fail if handle is not the handle of a valid, open file, and

the global variable errno is set to
EBADF

Bad file number

See also

chsize, _close, creat, creatnew, dup, telose, open, sopen

Example

#include 
#include 
#include 
int main(void)
{

int handle;
char buf[ll]

=

"0123456789";

1* create a file containing 10 bytes *1
handle = open("DUMMY.FIL", O_CREAT);
write(handle, buf, strlen(buf));
1* close the file *1
close (handle) ;
return 0;

closedir
Function
Syntax

Remarks

Closes a directory stream.
#include 
void closedir(DIR *dirp);

On UNIX platforms, closedir is available on POSIX-compliant systems.

Chapter 2, The run-time library

83

closedir

The closedir function closes the directory stream dirp, which must have
been opened by a previous call to opendir. After the stream is closed, dirp
no longer points to a valid directory stream.
Return value

If closedir is successful, it returns O. Otherwise, closedir returns -1 and

sets the global variable errno to
EBADF

The dirp argument does not point to a valid open directory strea

See Also

opendir, readdir, rewinddir

Example

See the example for opendir.

closegraph
Function
Syntax

Remarks

Return value

Shuts down the graphics system.
#include 
void far closegraph(void);

closegraph deallocates all memory allocated by the graphics system, then
restores the screen to the mode it was in before you called initgraph. (The
graphics system deallocates memory, such as the drivers, fonts, and an
internal buffer, through a call to _graphfreemem.)

None.

See also

initgraph, setgraphbufsize

Example

#inc1ude
#include
#include
#include






int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode, x, Yi
/* initialize graphics mode */
initgraph(&gdriver,&gmode, 1111)

i

/* read result of initialization */
errorcode = graphresult()i

if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode))i

84

Borland C++ Library Reference

closegraph

printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */
x
y

= getmaxx()
=

getmaxy()

•

2;
2;

/* output a message */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "Press a key to close the graphics system:");

getch();
/* wait for a key */
/* closes down the graphics system */
closegraph ( ) ;
printf("We're now back in text mode.\n");
printf ("Press any key to halt: ");
getch () ;
return 0;

clreol
Function
Syntax

Remar!{s
Return value

Clears to end of line in text window.
#include 
void clreol( void);

clreol clears all characters from the cursor position to the end of the line
within the current text window, without moving the cursor.

None.

See also

clrscr, delline, window

Example

#include 
int main(void)
{

clrscr () ;
cprintf ("The function CLREOL clears all characte~'s from the\r\n") ;
cprintf("cursor position to the end of the line within the\r\n");
cprintf("current text window, without moving the cursor.\r\n");
cprintf("Press any key to continue . . . ");
gotoxy(14, 4);
getch() ;

Chapter 2, The run-time library

85

I

clreol

clreol () ;
getch();
return 0;

clrscr
Function
Syntax

Remarks
Return value

Clears the text-mode window.
#include 
void clrscr( void);

clrscr clears the current text window and places the cursor in the upper
left-hand corner (at position 1,1).

None.

See also

clreol, delline, ~indow

Example

#include 
int main (void)
int i;
clrscr ();
for (i = 0; i < 20; itt)
cprintf("%d\r\n", i);
cprintf("\r\nPress any key to clear screen");
getch();
clrscr () ;
cprintf("The screen has been cleared!");
getch() ;
return 0;

complex
Function
Syntax

86

Creates complex numbers.
#include 
,complex complex(double real, double imag);

Borland C++ Library Reference

complex

Remarks

Creates a complex number out of the given real and imaginary parts. The
imaginary part is taken to be a if imag is omitted.
complex is the constructor for the C++ class complex, which is defined in
complex.h. Other applicable functions (listed under See also below) are
also defined in complex.h. Some of these are overloaded versions of C
library functions declared in math.h. C++ is required for the complex
versions.
If you don't want to program in C++, but instead want to program in C,

the only constructs available to you are struct complex and cabs, which
give the absolute value of a complex number. Both of these are defined in
math.h.
complex.h also overloads the operators +, -, *, I, +=, -=, *=, 1=, =, ==, and !=.
These operators give complex arithmetic in the usual sense. You can freely
mix complex numbers in expressions with ints, doubles, and other
numeric types. The operators «and» are overloaded for stream input
and output of complex numbers, as they are for other data types in
iostream.h.
Return value

The complex number with the given real and imaginary parts.

See also

abs, acos, arg, asin, atan, atan2, conj, cos, cosh, imag, log, log10, norm,
polar, pow, real, sin, sinh, sqrt, tan, tanh

Example

#include dostream.h>
#include 
int main (void)
{

double x = 3.1, Y = 4.2;
complex z = complex(x,Y);
cout « "z = " « z « "\n";
cout « " has real part = " « real(z) « "\n";
cout « " and imaginary real part = " « imag (z) « "\n";
cout « "z has complex conjugate = " « conj (z) « "\n";
return 0;

conj
Function

Returns the complex conjugate of a complex number.

Chapter 2, The run-time library

87

I
I

conj

Syntax

Remarks
Return value

#include 
complex conj(complex x);
II

DOS

II

•

UNIX

Windows

•

ANSI C

C++ only

•

II
II

conj (z) is the same as complex (real (z), - imag (z) ).

The complex conjugate of the complex number.

See also

complex, imag, real

Example

#include dostream.h>
#include 
int main(void)
{

double x = 3.1, y = 4.2;
complex z = complex(x,Y);
cout « "z = " « z « "\n";
cout «" has real part = " « real(z) « "\n";
"« imag(z) « "\n";
cout «" and imaginary real part
cout « "z has complex conjugate = " « conj (z) « "\n";
return 0;

_controI8?
Function
Syntax

Remarks

Manipulates the floating-point control word.
#include 
unsigned int _controI87(unsigned int newcw, unsigned int mask);

_control87 retrieves or changes the floating-point control word.

The floating-point control word is an unsigned int that, bit by bit, specifies
certain modes in the floating-point package; namely, the precision,
infinity, and rounding modes. Changing these modes allows you to mask
or unmask floating-point exceptions.
_control87 matches the bits in mask to the bits in newcw. If a mask bit

equals 1, the corresponding bit in newcw contains the new value for the

88

Borland C++ Library Reference

_control87

same bit in the floating-point control word, and _control87 sets that bit in
the control word to the new value.
Here's a simple illustration:
Original control word:

0100

0011

0110

0011

mask
newcw

1000
1110

0001
1001

0100
0000

1111
0101

Changing bits

1xxx

xxxI

xOxx

0101

If mask equals 0, _control87 returns the floating-point control word
without altering it.
_control87 does not change the Denormal bit because Borland C++ uses

denormal exceptions.
Return value

See also

The bits in the value returned reflect the new floating-point control word.
For a complete definition of the bits returned by _controI87, see the
header file float.h.
_clear87, _fpreset, signal, _status87

coreleft
Function
Syntax

Returns a measure of unused RAM memory.

In the tiny, small, and medium models:
#include 
unsigned coreleft( void);
In the compact, large, and huge models:
#include 
unsigned long coreleft( void);

Remarks

coreleft returns a measure of RAM memory not in use. It gives a different
measurement value, depending on whether the memory model is of the
small data group or the large data group.

Return value

In the small data models, coreleft returns the amount of unused memory
between the top of the heap and the stack. In the large data models,
coreleft returns the amount of memory between the highest allocated
block and the end of available memory.

Chapter 2, The run-time library

89

I

coreleft

See also

allocmem, brk, farcoreleft, malloc

Example

#include 
#include 
int main(void)
{

printf("The difference between the highest allocated block and\n")i
printf("the top of the heap is: %lu bytes\n", (unsigned long) coreleft())i
return 0i

cos, cosl
Function

Calculates the cosine of a value.

Syntax

Real versions:
#include 
double cos (double x);
long double cosl(long double x);
DOS

cosl

•

Rea/cos

•

Comp/excos

•

Remarks

UNIX

Windows

ANSI C

Complex version:
#include 
complex cos(complex x);

C++ only

•
•

•

•

•

•

cos computes the cosine of the input value. The angle is specified in
radians.
cosl is the long double version; it takes a long double argument and
returns a long double result.

The complex cosine is defined by
cos(z)
Return value

= (exp(i * z) + exp(-i * z»/2

cos of a real argument returns a value in the range -1 to 1.

Error handling for these functions can be modified through matherr (or
_matherrl).
See Also

acos, asin, atan, atan2, complex, matherr, sin, tan

Example

#include 
#include 
int main(void)
{

90

Borland C++ Library Reference

cos, cosl

double result, x = 0.5;
result = cos (x) ;
printf("The cosine of %If is %If\n", x, result);
return 0;

I

cosh, coshl
Function
Syntax

Calculates the hyperbolic cosine of a value.

Real versions:

Complex version:

#include 
double cosh(double x);
long double coshl(long double x);

#inc1ude 
complex cosh(complex x);

DOS

coshl

•

Real cosh

•
•

Complex cosh

Remarks

UNIX

Windows

ANSI C

•
•
•

•

•

C++ only

•

cosh computes the hyperbolic cosine, (eX + e-X) /2.
coshl is the long double version; it takes a long double argument and
returns a long double result.

The complex hyperbolic cosine is defined by
cosh(z)
Return value

= (exp(z) + exp(-z»/2

cosh returns the hyperbolic cosine of the argument.

When the correct value would create an overflow, these functions return
the value HUGE_VAL (cosh or _LHUGE_VAL (cosh!) with the
appropriate sign, and the global variable errno is set to ERANGE.
Error handling for these functions can be modified through the functions
matherr and _matherrl.
See Also

acos, asin, atan, atan2, complex, cos, matherr, sin,
sinh, tan, tanh

Example

#include 
#include 
int main(void)
{

double result, x = 0.5;
result = cosh(x);

Chapter 2, The run-time library

91

cosh, coshl

printf (" The hyperboic cosine of %If is %If\n''
return Oi

X,

I

result) i

country
Function
Syntax

Remarks

Returns country-dependent information.
#include 
struct COUNTRY *country(int xcode, struct country *cp);

country specifies how certain country-dependent data (such as dates,

times, and currency) will be formatted. The values set by this function
depend on the DOS version being used.

If cp has a value of -1, the current country is set to the value of xcode,
which must be nonzero. Otherwise, the COUNTRY structure pointed to
by cp is filled with the country-dependent information of the current
country (if xcode is set to 0), or the country given by xcode.
The structure COUNTRY is defined as follows:
struct country {
int co_datei
char co_curr [5l i
char co_thsep[2li
char co_desep[2li
char co_dtsep[2li
, char co _tmsep [2l i
char co_currstylei
char co_digitsi
char co_timei
long co_casei
char co_dasep[2li
char co_fill[lOli

/*
/*
/*
/*
/*
/*
/*
/*

/*
/*
/*

/*

date format */
currency symbol */
thousands separator */
decimal separator */
date separator */
time separator */
currency style */
significant digits in currency */
time format */
case map */
data separator */
filler * /

}i

The date format in co_date is
0 for the U.S. style of month, day, year
• 1 for the European style of day, month, year

II

.2 for the Japanese style of year, month, day
Currency display style is given by co_currstyle as follows:

92

Borland C++ Library Reference

country

Return value
Example

a

Currency symbol precedes value with no spaces between the
symbol and the number.

1

Currency symbol follows value with no spaces between the
number and the symbol.

2

Currency symbol precedes value with a space after the symbol.

3

Currency symbol follows the number with a space before the
symbol.

On success, country returns the pointer argument cpo On error, it returns
null.
#incl ude 
#include 
#define USA 0
int main(void)
{

struct COUNTRY country_info;
country (USA, &country_info);
printf("The currency symbol for the USA is: %s\n", country-info.co_curr);
return 0;

cprintf
Function
Syntax

Remarks

See printf for details
on format specifiers.

Writes formatted output to the screen.
#include 
int cprintf(const char *formatL argument, ... J);

cprintf accepts a series of arguments, applies to each a format specifier

contained in the format string pointed to by format, and outputs the
formatted data directly to the current text window on the screen. There
must be the same number of format specifiers as arguments.
The string is written either directly to screen memory or by way of a BIOS
call, depending on the value of the global variable directvideo.
Unlike fprintf and printf, cprintf does not translate linefeed characters (\n)
into carriage-return/linefeed character pairs (\r\n).

Return value

cprintf returns the number of characters output.

Chapter 2, The run-time library

93

cprintf

See also

directvideo (global variable), fprintf, printf, putch, sprintf, vprintf

Example

#include 
int main (void)
{

clrscr ();
window(10, 10, 80, 25);
cprintf("Hello world\r\n");
getch();
return 0;

clear the screen */
create a text window */
output some text in the window */
wait for a key */

/*
/*
/*
/*

cputs
Function
Syntax

Writes a string to the screen.
#include 
int cputs(const char *str);
I
I

Remarks

DOS

UNIX

•

I

Windows

1

ANSI C

I

C++ only

I

I
JI

cputs writes the null-terminated string str to the current text window. It

does not append a newline character.
The string is written either directly to screen memory or by way of a BIOS
call, depending on the value of the global variable directvideo.
Unlike puts, cputs does not translate linefeed characters (\n) into
carriage-return/linefeed character pairs (\r\n).
Return value

cputs returns the last character printed.

See also

cgets, directvideo (global variable), fputs, putch, puts

Example

#include 
int main(void)
{

clrscr() i
/* clear the screen */
window(10, 10, 80, 25) i /* create a text window */
/* icgoutput some text in the window */
cputs("This is within the window\r\n") i
getch() i
/* wait for a key */"
return 0i

94

Borland C++ Library Reference

Function
Syntax

Creates a new file or overwrites an existing one.
#include 
int _creat(const char *path, int attrib);
unsigned _dos_creat(const char *path,int attrib,int *handlep);
DOS

creat
dos_creat

Remarks

UNIX

Windows

•
•

ANSI C

C++ only

•
•

_creat and _dos_creat open the file specified by path. The file is always

opened in binary mode. Upon successful file creation, the file pointer is set
to the beginning of the file. _dos_creat stores the file handle in the
location pointed to by handlep. The file is opened for both reading and
writing.
If the file already exists, its size is reset to O. (This is essentially the same as
deleting the file and creating a new file with the same name.)

The attrib argument to _creat is an ORed combination of the one or more
of following constants (defined in dos.h):
FA_RDONLY Read-only attribute
FA_HIDDEN Hidden file
FA_SYSTEM System file
The attrib argument to _dos_creat is an ORed combination of one or more
of the following constants (defined in dos.h):
_A_NORMAL
_A_RDONLY
_A_HIDDEN
_A_SYSTEM
Return value

Normal file
Read-only file
Hidden file
System file

Upon successful completion, _creat returns the new file handle, a nonnegative integer; otherwise, it returns -l.
Upon successful completion, _dos_creat returns O.
If an error occurs, _dos_creat returns the DOS error code.

In the event of error, _creat and _dos_creat, the global variable errno is set
to one of the following:
ENOENT
EMFILE

Chapter 2, The run-time library

Path or file name not found
Too many open files

95

EACCES

Permission denied

See also

_chmod, chsize, _close, close, creat, creatnew, creattemp

Example

#include
#include
#include
#include




do.h>

int main () {
unsigned count;
int handle;
char buf[ll] = "0123456789";
/* Create a 10-byte file using _dos_creat. */
if (_dos_creat("DUMMY.FIL", _A_NORMAL, &handle)
perror ("Unable to _dos_creat DUMMY .FIL");
return 1;

!=

0) {

if (_dos_write (handle, buf, strlen(buf), &count) != 0) {
perror("Unable to _dos_write to DUMMY.FIL");
return 1;
_dos_close (handle) ;
/* Create another 10-byte file using _creat. */
if ((handle::: _creat("DUMMY2.FIL", 0)) < 0) {
perror ("Unable to _create DUMMY2. FIL") ;
return 1;

if (_write (handle, buf, strlen(buf)) < 0) {
perror ("Unable to _write to DUMMY2. FIL") ;
return 1;
_close (handle) ;
return 0;

creat
Function
Syntax

96

Creates a new file or overwrites an existing one.
#include 
int creat(const char *path, int amode);

Borland C++ Library Reference

creat

Remarks

creat creates a new file or prepares to rewrite an existing file given by

path. amode applies only to newly created files.
A file created with creat is always created in the translation mode
specified by the global variable Jmode (a_TEXT or a_BINARY).
If the file exists and the write attribute is set, creat truncates the file to a
length of bytes, leaving the file attributes unchanged. If the existing file
has the read-only attribute set, the creat call fails and the file remains
unchanged.

°

The creat call examines only the S_IWRITE bit of the access-mode word
amode. If that bit is 1, the file can be is written to. If the bit is 0, the file is
marked as read-only. All other DOS attributes are set to 0.

amode can be one of the following (defined in sys \stat.h):

~

Return value

Value of amode

Access permission

S_IWRITE
S_IREAD
S_IREAD I S_IWRITE

Permission to write
Permission to read
Permission to read and write

In DOS, write permission implies read permission.
Upon successful completion, creat returns the new file handle, a nonnegative integer; otherwise, it returns -l.
In the event of error, the global variable errno is set to one of the following:
ENOENT
EMFILE
EACCES

Path or file name not found
Too many open files
Permission denied

See also

chmod, chsize, close, _creat, creatnew, creattemp, dup, dup2, _fmode
(global variable), fopen, open, sopen, write

Example

#include
#include
#include
#include
#include
#include
#include









int rnain(void)
{

int handle;
char buff] = "0123456789";

Chapter 2, The run-time library

97

•

ereat

/* create a binary file for reading and writing */
if ((handle = _creat("DUMMY.FIL", 0)) < 0) {
swi tch (errno) {
case ENOENT: printf("Error: Path or file not found.\n");
break;
case EMFILE: printf("Error: Too many open files.\n");
break;
case EACCES: printf("Error: Permission denied.\n");
break;
printf("Error creating file.\n");
default :
break;

exit(l);
/* write a string and NULL terminator into the file */
write (handle, buf, strlen(buf)+l);
/* close the file */
close (handle) ;
return 0;

creatnew
Function
Syntax

Creates a new file.
#include 
int creatnew(const char *path, int mode);
DOS

Remarks

creatnew is identical to _creat with one exception. If the file exists,
creatnew returns an error and leaves the file untouched.

The mode argument to creatnew can be one of the following constants
(defined in dos.h):

FA_RDONLY Read-only attribute
FA_HIDDEN Hidden file
FA_SYSTEM System file
Return value

Upon successful completion, creat returns the new file handle, a nonnegative integer; otherwise, it returns -1.
In the event of error, the global variable errno is set to one of the following:

98

Borland C++ Library Reference

creatnew

File already exists
Path or file name not found
Too many open files
Permission denied

EEXIST
ENOENT
EMFILE
EACCES
See also

close, _creat, creat, creattemp, dup, Jmode (global variable), open

Example

#include
#include
#include
#include
#include







int main(void)
{

int handle;
char buf[ll]

= "0123456789";

/* attempt to create a file that doesn't already exist */
handle = creatnew("DUMMY.FIL", 0);

if (handle == -1)
print f ( "DUMMY. FIL already exi st s. \n" ) ;
else {
printf("DUMMY.FIL successfully created.\n");
write (handle, buf, strlen(buf));
close (handle) ;
return 0;

creattemp
Function
Syntax

Creates a unique file in the directory associated with the path name.
#include 
int creattemp(char *path, int attrib);
Wi ndows

Remarks

ANS I C

A file created with creattemp is always created in the translation mode
specified by the global variable Jmode (O_TEXT or O_BINARY).

path is a path name ending with a backslash (\). A unique file name is
selected in the directory given by path. The newly created file name is
stored in the path string supplied. path should be long enough to hold the

Chapter 2, The run-time library

99

creattemp

resulting file name. The file is not automatically deleted when the
program terminates.
creattemp accepts attrib, a DOS attribute word. The file is always opened

in binary mode. Upon successful file creation, the file pointer is set to the
beginning of the file. The file is opened for both reading and writing.
The attrib argument to creattemp can be one of the following constants
(defined in dos.h):
FA_RDONLY
FA_HIDDEN
FA_SYSTEM
Return value

Read-only attribute
Hidden file
System file

Upon successful completion, the new file handle, a nonnegative integer, is
returned; otherwise, -1 is returned.
In the event of error, the global variable errno is set to one of the following:
ENOENT
EMFILE
EACCES

Path or file name not found
Too many open files
Permission denied

See also

close, _creat, creat, creatnew, dup, Jmode (global variable), open

Example

#include 
#include 
#include 
int main (void)
{

int handle;
char pathname[128);
strcpy(pathname, "\\");
/* create a unique file in the root directory */
handle = creattemp(pathname, 0);
printf ("%s was the unique file created. \n", pathname);
close(handle);
return 0;

cscanf
Function
Syntax

100

Scans and formats input from the console.
#include 
int cscanf(char *format[, address, ... J);

Borland C++ Library Reference

csconf

Remarks
See scant for details
on format specifiers.

cscanf scans a series of input fields one character at a time, reading

directly from the console. Then each field is formatted according to a
format specifier passed to cscanf in the format string pointed to by format.
Finally, cscanf stores the formatted input at an address passed to it as an
argument following format, and echoes the input directly to the screen.
There must be the same number of format specifiers and addresses as
there are input fields.
cscanf might stop scanning a particular field before it reaches the normal
end-of-field (whitespace) character, or it might terminate entirely for a
number of reasons. See scanf for a discussion of possible causes.

Return value

cscanf returns the number of input fields successfully scanned, converted,
and stored; the return value does not include scanned fields that were not
stored. If no fields were stored, the return value is O.

If cscanf attempts to read at end-of-file , the return value is EOF.
See also

fscanf, getche, scanf, sscanf

Example

#include 
int main(void)
{

char string[80];
clrscr();
/* clear the screen */
cprintf("Enter a string:"); /* prompt the user for input */
/* read the input */
cscanf (" %s", string);
/* display what was read */
cprintf("\r\nThe string entered is: %s", string);
return 0;

ctime
Function
Syntax

Converts date and time to a string.
#include 
char *ctime(const time_t *time);

Chapter 2, The run-time library

101

•

ctime

Remarks

ctime converts a time value pointed to by time (the value returned by the
function time) into a 26-character string in the following form, terminating
with a newline character and a null character:
Man Nov 21 11:31:54 1983\n\0

All the fields have constant width.
Set the global long variable timezone to the difference in seconds between
GMT and local standard time (in PST, timezone is 8x60x60). The global
variable daylight is nonzero if and only if the standard U.s. daylight saving
time conversion should be applied.
Return value

ctime returns a pointer to the character string containing the date and

time. The return value points to static data that is overwritten with each
call to ctime.
See also

asctime, daylight (global variable), difftime, ftime, getdate, gmtime,
localtime, settime, time, timezone (global variable), tzset

Example . #include
#include




int main(void)
{

time_t t;
t = time (NULL) ;
printf("Today's date and time:
return 0;

%s\n", ctime(&t));

ctrlbrk
Function
Syntax

Remarks

Sets control-break handler.
#include 
void ctrlbrk(int (*handler)(void»;

ctrlbrk sets a new control-break handler function pointed to by handler.
The interrupt vector Ox23 is modified to call the named function.
ctrlbrk establishes a DOS interrupt handler that calls the named function;

the named ftinction is not called directly.

102

Borland C++ Library Reference

ctrlbrk

The handler function can perform any number of operations and system
calls. The handler does not have to return; it can use longjrnp to return to
an arbitrary point in the program. The handler function returns 0 to abort
the current program; any other value causes the program to resume
execution.
Return value

ctrlbrk returns nothing.

See also

getcbrk, signal

Example

#include 
#include 
int c_break(void)
{

printf ("Control-Break pressed. Program aborting ... \n");
return (0) ;

void main(void)
{

ctrlbrk(c_break);
for(;;)
printf("Looping ... Press  to quit:\n");

delay
Function
Syntax

Remarks

Return value

Suspends execution for an interval (milliseconds).
#include 
void delay(unsigned milliseconds);

With a call to delay, the current program is suspended from execution for
the number of milliseconds specified by the argument milliseconds. It is no
longer necessary to make a calibration call to delay before using it. delay
is accurate to a millisecond.
None.

See also

nosound, sleep, sound

Example

/* emits a 440-Hz tone for 500 milliseconds */
#include 
int main(void)

Chapter 2, The run-time library

103

delay

sound(440) ;
delay(500) ;
nosound() ;
return 0;

delline
Function
Syntax

Deletes line in text window.
#include 
void delline( void);
DOS

Remarks
Return value

UNIX

Windows

delline deletes the line containing the cursor and moves all lines below it
one line up. delline operates within the currently active ~ext window.

None.

See also

clreol, clrscr, insline, window

Example

#include 
int main(void)
{

clrscr () ;
cprintf("The function DELLINE deletes the line containing the\r\n");
cprintf("cursor and moves all lines below it one line up.\r\n");
cprintf("DELLINE operates within the currently active text\r\n");
cprintf ("window. Press any key to continue . . .");
/* move cursor to the 2nd line, 1st column */
gotoxy (1,2) ;
getch () ;
delline () ;
getch () ;
return 0;

detectgraph
Function

104

Determines graphics driver and graphics mode to use by checking the
hardware.

Borland C++ Library Reference

detectgraph

Syntax

#inc1ude 
void far detectgraph(int far *graphdriver, int far *graphmode);

I

DOS

UNIX

Windows

ANSI C

J

•
Remarks

I C++

only

"

"

detectgraph detects your system's graphics adapter and chooses the mode
that provides the highest resolution for that adapter. If no graphics hardware is detected, *graphdriver is set to grNotDetected (-2), and graphresult

returns grNotDetected (-2).

*graphdriver is an integer that specifies the graphics driver to be used. You
can give it a value using a constant of the graphics_drivers enumeration
type, defined in graphics.h and listed in the following table.
Table 2.1
detectgraph
constants

graphics_ drivers
constant

DETECT
CGA
MCGA
EGA
EGA64
EGAMONO
IBM8514
HERCMONO
ATT400
VGA
PC3270

Numeric value

o (requests autodetection)
1
2
3
4
5
6
7

8
9
10

*graphmode is an integer that specifies the initial graphics mode (unless
*graphdriver equals DETECT; in which case, *graphmode is set to the
highest resolution available for the detected driver). You can give

*graphmode a value using a constant of the graphics_modes enumeration
type, defined in graphics.h and listed in the following table.

Chapter 2, The run-time library

105

detectgraph

Table 2.2
Graphics drivers
information

Graphics
driver

Column
graphics_modes

Value

x row

Palette

Pages

CGA

CGACO
CGAC1
CGAC2
CGAC3
CGAHI

0
1
2
3
4

320 x 200
320 x 200
320 x 200
320 x 200
640 x 200

CO
C1
C2
C3
2 color

1
1
1
1
1

MCGA

MCGACO
MCGAC1
MCGAC2
MCGAC3
MCGAMED
MCGAHI

0
1
2
3
4
5

320 x 200
320 x 200
320 x 200
320 x 200
640 x 200
640 x 480

CO
C1
C2
C3
2 color
2 color

1
1
1
1
1
1

EGA

EGALO
EGAHI

0
1

640 x 200
640 x 350

16 color
16 color

4
2

EGA64

EGA64LO
EGA64HI

0
1

640 x 200
640 x 350

16 color
4 color

1
1

EGA-MONO

EGAMONOHI
EGAMONOHI

3
3

640 x 350
640 x 350

2 color
2 color

1*
2**

HERC

HERCMONOHI

0

720 x 348

2 color

2

ATT400

ATT400CO
ATT400C1
ATT400C2
ATT400C3
ATT400MED
ATT400HI

0
1
2
3
4
5

320 x 200
320 x 200
320 x 200
320 x 200
640 x 200
640 x 400

CO
C1
C2
C3
2 color
2 color

1
1
1
1
1
1

VGA

VGALO
VGAMED
VGAHI

0
1
2

640 x 200
640 x 350
640 x 480

16 color
16 color
16 color

2
2
1

PC3270

PC3270HI

0

720 x 350

2 color

1

IBM8514

IBM8514HI
IBM8514LO

0
0

640 x 480
1024 x 768

256 color
256 color

* 64K on EGAMONO card
** 256K on EGAMONO card
Note: The main reason to call detectgraph directly is to override the
graphics mode that detectgraph recommends to initgraph.
Return value

See also
Example

106

None.
graphresult, initgraph
#include 
#include 

Borland C++ Library Reference

detectgraph

#include 
#include 
/* the names of the various cards supported */
char *dname[] =
"requests detection",
"a CGA",
"an MCGA",
"an EGA",
"a 64K EGA",
"a monochrome EGA",
"an IBM 8514",
"a Hercules monochrome",
"an AT&T 6300 PC",
"a VGA",
"an IBM 3270 PC"
}i

int main (void)
{

/* used to return detected hardware info. */
int gdriver, gmode, errorcodei
/* detect the graphics hardware available */
detectgraph(&gdriver, &gmode)i

/* read result of detectgraph call */
errorcode = graphresult() i
if (errorcode ! = grOk) { / * an error occurred * /
printf("Graphics error: %s\n", grapherrormsg(errorcode)) i
printf("Press any key to halt:") i
getch()i
exit(l);.
/* terminate with an error code */

/* display the information detected */
clrscr ();
printf("You have %s video display card.\n", dname[gdriver])i
printf (" Press any key to halt:") i
getch () i
return 0i

difftime
Function
Syntax

Computes the difference between two times.
#inc1ude 
double difftime(time_t time2, time_t timel);

Chapter 2, The run-time library

107

difffime

I

DOS

UNIX

Windows

I
Remarks
Return value
See also

I

ANSI C

I

I C++

I

only

"

I

difftime calculates the elapsed time in seconds, from timel to time2.
difftime returns the result of its calculation as a double.
asctime, ctime, daylight (global variable), gmtime, localtime, time, timezone

(global variable)
Example

#ind ude
#include
#include
#include






int main(void)
{

time_t first, second;
drscr () ;
/* gets system time */
first = time(NULL);
delay(2000) ;
/* waits 2000 millisecs or 2 secs */
second = time (NULL) ;
/* gets system time again */
printf("The difference is: %f seconds\n",difftime(second,first));
getch () ;
return 0;

disable, _disable, enable, _enable
Function
Syntax

Remarks

Disables and enables interrupts.
#inc1ude 
void disable(void);
void _disable(void);
void enable(void);
void _enable(void);

These macros are designed to provide a programmer with flexible
hardware interrupt control.
The disable and _disable macros disable interrupts. Only the NMI (nonmaskable interrupt) is allowed from any external device.

108

Borland C++ Library Reference

disable, _disable, enable, _enable

The enable and _enable macros enable interrupts, allowing any device
interrupts to occur.
Return value

•

None.

See also

getvect

Exannple

/* This is an interrupt service routine. You cannot compile this program with
Test Stack Overflow turned on and get an executable file that operates
correctly. */
#include 
#include 
#include 
#define INTR OX1C

/* The clock tick interrupt */

#ifdef __ cplusplus
#define __CPPARGS
#else
#define __CPPARGS
#endif
void interrupt (*oldhandler) (__ CPPARGS);
int count=O;
void interrupt handler (__CPPARGS) /* if C++, need the the ellipsis */
{

/* disable interrupts during the handling of the interrupt */
_disable() ;
/* increase the global counter */
countH;
/* reenable interrupts at the end of the handler */
enable() ;
/* call the old routine */
oldhandler();
int main(void)
/* save the old interrupt vector */
oldhandler = _dos_getvect(INTR);
/* install the new interrupt handler */
_dos_setvect(INTR, handler);
/* loop until the counter exceeds 20 */
while (count < 20)
printf("count is %d\n",count);
/* reset the old interrupt handler */
_dos_setvect(INTR, oldhandler);

Chapter 2, The run-time library

109

div

return 0;

div
Function
Syntax

Remarks

Divides two integers, returning quotient and remainder.
#inc1ude 
div_t div(int numer, int denam);

div divides two integers and returns both the quotient and the remainder
as a div _t type. numer and denam are the numerator and denominator,
respectively. The div_t type is a structure of integers defined (with
typedef) in stdlib.h as follows:
typedef struct
int quot;
int rem;
div_t;

Return value

/* quotient */
/* remainder */

div returns a structure whose elements are quat (the quotient) and rem (the
remainder).

See also

Idiv

Example

#include 
#include 

int main(void)
{

x = di v (10, 3 ) ;
printf("10 div 3
return 0;

=

%d remainder %d\n", x.quot, x.rem);

Program output
10 div 3

110

= 3 remainder 1

Borland C++ Library Reference

Function
Syntax

Remarks
Return value

Closes a file.
#include 
unsigned _dos_close(int handle);

dos_close closes the file associated with handle. handle is a file handle
obtained from a _dos_creat, _dos_creatnew, or _dos_open call.

Upon successful completion, _dos_close returns o. Otherwise, it returns
the DOS error code and the global variable errno is set to
EBADF

Bad file number

See Also

_dos_creat, _dos_open, _dos_read, _dos_write

Example

#include 
#include 
#include 
int main(void)
{

unsigned count;
int handle;
char buf[ll] = "0123456789";

1* create a file containing 10 bytes *1
if (_dos_creat ( "DUMMY. FIL", _A_NORMAL, &handle) ! = 0) {
perror ("Unable to create DUMMY. FIL") ;
return 1;
if (_dos_write (handle, buf, strlen(buf), &count) != 0) {
perror ("Unable to write to DUMMY. FIL") ;
return 1;
_dos_close(handle);
return 0;

Chapter 2, The run-time library

1* close the file *1

111

_dos_creatnew
Function
Syntax

Remarks

Creates a new file.
#inc1ude 
unsigned _dos_creatnew(const char *path, int attrib, int *handlep);

_dos_creatnew uses DOS function Ox5B to create and open the new file

path. The file is given the access permission attrib, a DOS attribute word.
The file is always opened in binary mode. Upon successful file creation,
the file handle is stored in the location pointed to by handlep, and the file
pointer is set to the beginning of the file. The file is opened for both
reading and writing.
If the file already exists, _dos_creatnew returns an error and leaves the
file untouched.

The attrib argument to _dos_creatnew is an OR combination of one or
more of the following constants (defined in dos.h):
_A_NORMAL
_A_RDONLY
_A_HIDDEN
_A_SYSTEM
Return value

Normal file
Read-only file
Hidden file
System file

Upon successful completion, _dos_creatnew returns O. Otherwise, it
returns the DOS error code, and the global variable errno is set to one of
the following:
EEXIST
ENOENT
EMFILE
EACCES

File already exists
Path or file name not found
Too many open files
Permission aenied

See Also
Example

#include 
#include 
#include 
int main(void)
{

unsigned count;
int handle;
char buf[ll] = "0123456789";

112

Borland C++ Library Reference

/* create a file containing 10 bytes */
if (_dos_creatnew("DUMMY.FIL", _A_NORMAL, &handle)
perror("Unable to create DUMMY.FIL");
return 1;

if (_dos_write (handle, buf, strlen(buf), &count)
perror("Unable to write to DUMMY.FIL");
return 1;

!=

!= 0)

{
I

II

0) {

/* close the file */
_dos_close (handle) ;
return 0;

dosexterr
Function
Syntax

Remarks

Gets extended DOS error information.
#include 
int dosexterr(struct DOSERROR *eblkp);

This function fills in the DOSERROR structure pointed to by eblkp with
extended error information after a DOS call has failed. The structure is
defined as follows:
struct DOSERROR {
int de_exterror;
char de_class;
char de_action;
char de_locus;

/*
/*
/*
/*

extended error */
error class */
action */
error locus */

};

The values in this structure are obtained by way of DOS call Ox59. A
de_exterror value of 0 indicates that the prior DOS call did not result in an
error.
Return value
Example

dosexterr returns the value de_exterror.
#include 
#include 
int main (void)
{

FILE *fp;

Chapter 2, The run-time library

113

dosexterr

struct DOSERROR info;
fp = fopen("perror.dat", "r");
if (! fp) perror ("Unable to open file for reading");
dosexterr(&info);
printf("Extended DOS error information:\n");
printf("
Extended error:
%d\n",info.de_exterror);
printf("
Class:
%x\n",info.de_class);
printf("
Action:
%x\n",info.de_action);
printf("
Error Locus:
%x\n",info.de_locus);
return 0;

_dos_findfirst
Function
Syntax

Searches a disk directory.
#include 
unsigned _dos_findfirstCconst char *pathname, int attrib,
struct find_t *ffblk);
Wi ndows

Remarks

ANS I C

_dos_findfirst begins a search of a disk directory by using the DOS

function Ox4E.

pathname is a string with an optional drive specifier, path, and file name of
the file to be found. The file name portion can contain wildcard match
characters (such as? or *). If a matching file is found, the find_t structure
pointed to by ffblk is filled with the file-directory information.
The format of the find_t structure is as follows:
struct find_t {
char reserved[21];
char attrib;
int wctime;
int wcdate;
long size;
char name [13] ;

1*
1*
1*
1*
1*
1*

reserved by DOS *1
attribute found *1
file time *1
file date *1
file size *1
found file name *1

};

attrib is a DOS file-attribute byte used in selecting eligible files for the
search. attrib is an OR combination of one or more of the following
constants (defined in dos.h):
Normal file

114

Borland C++ Library Reference

_A_RDONLY
_A_HIDDEN
_A_SYSTEM
_A_VOLID
_A_SUBDIR
_A_ARCH

Read-only attribute
Hidden file
System file
Volume label.
Directory
Archive

For more detailed information about these attributes, refer to your DOS
reference manuals.
Note that wr_time and wr_date contain bit fields for referring to the file's
date and time. The structure of these fields was established by DOS. Both
are 16-bit structures divided into three fields.
wr_time:

bits 0-4

The result of seconds divided by 2 (e.g., 10 here means
20 seconds)
Minutes
Hours

bits 5-10
bits 11-15
wr_date:

bits 0-4
bits 5-8
bits 9-15
Return value

Day
Month
Years since 1980 (e.g., 9 here means 1989)

_dos_findfirst returns 0 on successfully finding a file matching the search

pathname. When no more files can be found, or if there is some error in the
file name, the DOS error code is returned, and the global variable errno is
set to
ENOENT

Pa th or file name not found

See Also

_dos_find next

Example

#include 
#include 
int main(void)
{

struct find_t ffblk;
int done;
printf(IIDirectory listing of *.*\n");
done = _dos_findfirst ("*. * II ,_A_NORMAL, &ffblk) ;
while (! done) {
printf(" %s\n", ffblk.name);
done = _dos_findnext(&ffblk);
return 0;

Chapter 2, The run-time library

115

Program output
Directory listing of *.*
FINDFRST .C
FINDFRST.OBJ
FINDFRST.MAP
FINDFRST.EXE

Function
Syntax

Remarks

Continues _dos_findfirst search.
#include 
unsigned _dos_findnext(struct find_t *ffblk);

_dos_findnext is used to fetch subsequent files that match the pathname
given in _dos_findfirst. ffblk is the same block filled in by the
_dos_findfirst call. This block contains necessary information for
continuing the search. One file name for each call to _dos_find next will be

returned until no more files are found in the directory matching the

pathname.
Return value

_dos_findnext returns 0 on successfully finding a file matching the search

pathname. When no more files can be found, or if there is some error in the
file name, the DOS error code is returned, and the global variable errno is
set to
ENOENT

Path or file name not found

See Also

_dos_findfirst

Example

#include 
#include 
int main (void)
{

struct find_t ffblk;
int done;
printf ("Directory listing of *. *\n");
done = _dos_findfirst (" *. *" ,_A_NORMAL, &ffblk) ;
while (!done) {
printf (" %s\n", ffblk.name);
done = _dos_findnext(&ffblk};

116

Borland C++ Library Reference

return 0;

Program output
Directory listing of * *
FINDFRST.C
FINDFRST.OBJ
FINDFRST.MAP
FINDFRST.EXE

_dos_getdiskfree
Function
Syntax

Remarks

Gets disk free space.
#include 
unsigned _dos_getdiskfree(unsigned char drive, struct diskfree_t *dtable);

_dos_getdiskfree accepts a drive specifier in drive (0 for default, 1 for A, 2
for B, and so on) and fills in the diskfree_t structure pointed to by dtable

with disk characteristics.
The diskfree_t structure is defined as follows:
struct diskfree_t {
unsigned avail_clusters;
/*
/*
unsigned total_clusters;
unsigned bytes_per_sector;
/*
unsigned sectors_per_cluster;/*

available clusters */
total clusters */
bytes per sector */
sectors per cluster */

};

Return value

_dos_getdiskfree returns 0 if successful. Otherwise, it returns a non-zero
value and and the global variable errno is set to

EINVAL
See Also
Example

Invalid drive specified

getfat, getfatd
#include 
#include 
#include 
int main(void)
{

struct diskfree_t free;

Chapter 2, The run-time library

117

_dos_getdiskfree

long avail;
if (_dos_getdiskfree(O, &free) != 0) {
printf("Error in _dos_getdiskfree() call\n");
exit(l);
avail

(long) free.avail_clusters

* (long) free.bytes_per_sector
* (long) free.sectors-per_cluster;
printf("The current drive has %ld bytes available\n", avail);
return 0;

Function
Syntax

Remarks

Gets and sets the current drive number.
#include 
void _dos_getdrive(unsigned *drivep);
void _dos_setdrive(unsigned drivep, unsigned *ndrives);

_dos_getdrive uses DOS function Ox19 to get the current drive number.
_dos_setdrive uses DOS function OxOE to set the current drive.
_dos_setdrive stores the total number of drives at the location pointed to
by ndrives.

The drive numbers at the location pointed to by drivep are as follows:
1 for A, 2 for B, 3 for C, and so on.
Return value

None. Use _dos_getdrive to verify that the current drive was changed
successfully.

See Also

_getcwd

Example

#include 
#include 
int main(void)
{

unsigned disk, maxdrives;
/* Get the current drive. */
_dos_getdrive(&disk) ;
printf("The current drive is: %c\n", disk + 'A' - 1);

118

Borland C++ Library Reference

/* Set current drive to C: */
printf("Setting current drive to C:\n");
_dos_setdrive(3, &maxdrives);
printf("The number of logical drives is: %d\n", rnaxdrives);
return 0;

Function
Syntax

Remarks

Changes file access mode.
#include 
int _dos_getfileattr(const char *path, unsigned *attribp);
int _dos_setfileattr(const char path, unsigned attrib);

_dos_getfileattr fetches the DOS file attributes for the file

path. The

attributes are stored at the location pointed to by attribp.
_dos_setfileattr sets the DOS file attributes for the file

path to the value

attrib.
The DOS file attributes can b.e a OR combination of the following
symbolic constants (defined in dos.h):
Read-only attribute
Hidden file
System file
Volume label
Directory
Archive
Normal file (no attribute bits set)

_A_RDONLY
_A_HIDDEN
_A_SYSTEM
_A_VOLID
_A_SUBDIR
_A_ARCH
_A_NORMAL
Return value

Upon successful completion, _dos_getfileattr and _dos_setfileattr return
O. Otherwise, these functions return the DOS error code, and the global
variable errno is set to the following:
ENOENT

Path or file name not found

See Also

chmod, stat

Example

#include 
#include 
int main (void)

Chapter 2, The run-time library

119

char filename[128l;
unsigned attrib;
printf("Enter a file name:");
scanf ("%s", filename);
if (_dos_getfileattr(filename,&attrib) != 0) {
perror ("Unable to obtain file attributes");
return 1;
if (attrib & _A_RDONLY)
printf("%s currently read-only, making it read-write.\n", filename);
attrib &= -_A_RDONLY;
else {
printf("%s currently read-write, making it read-only.\n", filename);
attrib 1= _A_RDONLY;
if (_dos_setfileattr (filename, attrib) ! = 0)
perror ("Unable to set file attributes");
return 0;

Function
Syntax

Gets and sets file date and time.
#include 
unsigned _dos_getftime(int handle, unsigned *datep, unsigned *timep);
unsigned _dos_setftime(int handle, unsigned date, unsigned time);
C++ only

Remarks

_dos_getftime retrieves the file time and date for the disk file associated

with the open handle. The file must have been previously opened using
_dos_open, _dos_creat, or _dos_creatnew. _dos_getftime stores the date

and time at the locations pointed to by datep and timep.
_dos_setftime sets the file's new date and time values as specified by date

and time.
Note that the date and time values contain bit fields for referring to the
file's date and time. The structure of these fields was established by DOS.
Both are 16-bit structures divided into three fields.

120

Borland C++ Library Reference

Date:
bits 0-4
bits 5-8
bits 9-15

Day
Month
Years since 1980 (e.g., 9 here means 1989)

Time:
bits 0-4

The result of seconds divided by 2 (e.g., 10 here means
20 seconds)
Minutes
Hours

bits 5-10
bits 11-15
Return value

_dos_getftime and _dos_setftime return 0 on success.

In the event of an error return, the DOS error code is returned and the
global variable errno is set to the following:
EBADF

Bad file number

See Also

fstat, stat

Example

hncl ude 
#include 
int main(void)
{

FILE *stream;
unsigned date, time;
if ((stream = fopen ("TEST. $$$", "w")) == NULL) {
fprintf(stderr, "Cannot open output file.\n");
return 1;
_dos_getftime(fileno(stream) , &date, &time);
printf("File year of TEST.$$$: %d\n" , ((date » 9) & Ox7f) + 1980);
date = (date & Oxlff) I (21 « 9);
_dos_setftime(fileno(stream) , date, time);
printf("Set file year to 2001.\n");
fclose (stream) ;
return 0;

Function
Syntax

Gets and sets system time.
#include 
void _dos_gettime(struct dostime_t *timep);
unsigned _dos_settime(struct dostime_t *timep);

Chapter 2, The run-time library

121

Remarks

_dos_gettime fills in the dostime_t structure pointed to by timep with the

system's current time.
_dos_settime sets the system time to the values in the dostime_t structure
pointed to by timep.
The dostime_t structure is defined as follows:
struct dostime_t
unsigned char
unsigned char
unsigned char
unsigned char

{
hour;
minute;
second;
hsecond;

/*
/*
/*
/*

hours 0-23 */
minutes 0-59 */
seconds 0-59 */
hundredths of seconds 0-99 */

}i

Return value

_dos_gettime does not return a value.

If _dos_settime is successful, it returns O. Otherwise, it returns the DOS
error code, and the global variable errno is set to the following:
EINVAL

Invalid time

See Also

_dos_getdate, _dos_setdate, _dos_settime, stime, time

Example

#include
#include




int main(void)

/* Example for _dos_gettime. */

{

struct dostime_t ti
_dos_gettime(&t)i
printf("The current time is: %2d:%02d:%02d.%02d\n", t.hour, t.minute,
t.second, t.hsecond)i
return 0;

#include 
#include 
#include 
int main (void)

/* Example for _dos_settime. */

{

struct dostime_t reset;
reset.hour
= 17i
reset.minute = 0;
reset.second = Oi
reset.hsecond = 0;

122

Borland C++ Library Reference

printf("Setting time to 5 PM.\n");
_dos_settime(&reset) ;
system( "time");
return 0;

Function
Syntax

Remarks

Gets interrupt vector.
#include 
void interruptC*_dos_getvectCunsigned interruptno» 0;

Every processor of the 8086 family includes a set of interrupt vectors,
numbered 0 to 255. The 4-byte value in each vector is actually an address,
which is the location of an interrupt function.
_dos_getvect reads the value of the interrupt vector given by interruptno

and returns that value as a Cfar) pointer to an interrupt function. The value
of interruptno can be from 0 to 255.
Return value

_dos_getvect returns the current 4-byte value stored in the interrupt

vector named by interruptno.
See Also

_disable, _enable, _dos_setvect

Example

#include 
#include 
#ifdef __ cplusplus
#define __ CPPARGS
#else
#define __CPPARGS
#endif
/* interrupt prototype */
void interrupt get_out( __ CPPARGS)i
void interrupt (*oldfunc) (__CPPARGS); /* interrupt function pointer */
int looping

= 1;

int main(void)
{

puts("Press  to terminate");
/* save the old interrupt */
oldfunc = _dos_getvect(5);

Chapter 2, The run-time library

123

/* install interrupt handler */
_dos_setvect(5,get_out);

while (looping); /* do nothing */
/* restore to original interrupt routine */
_dos_setvect(5,oldfunc) ;
puts (" Success") ;
return 0;
void interrupt get_out (__CPPARGS)
looping = 0;
/* change global var to get out of loop */

Function
Syntax

Remarks

Sets interrupt vector entry.
#include 
void _dos_setvect(unsigned interruptno, void interrupt (*isr) 0);

Every processor of the 8086 family includes a set of interrupt vectors,
numbered 0 to 255. The 4-byte value in each vector is actually an address,
which is the location of an interrupt function.
_dos_setvect sets the value of the interrupt vector named by interruptno

to a new value, isr, which is a far pointer containing the address of a new
interrupt function. The address of a C routine can only be passed to isr if
that routine is declared to be an interrupt routine.
..
Return value

If you use the prototypes declared in dos.h, simply pass the address of an
interrupt function to _dos_setvect in any memory model.

None.

See Also

_dos_getvect

Example

/* This is an interrupt service routine. You can NOT compile this program with

Test Stack Overflow turned on and get an executable file which will operate
correctly. */
#include 
#include 
#include 
#define INTR OX1C

124

/* The clock tick interrupt */

Borland C++ Library Reference

#ifdef __cplusplus
#define __ CPPARGS
#else
#define __CPPARGS
#endif
void interrupt ( *oldhandler) (__ CPPARGS) ;
int count=O;
void interrupt handler (__ CPPARGS)
{

count++;
oldhandler() ;

1* increase the global counter *1
1* call the old routine *1

int main (void)
{

1* save the old interrupt vector *1
oldhandler = getvect(INTR);
1* install the new interrupt handler *1
setvect(INTR, handler);
1* loop until the counter exceeds 20 *1
while (count < 20)
printf("count is %d\n",count);
1* reset the old interrupt handler *1
setvect(INTR, oldhandler);
return 0;

Function
Syntax

Remarks

Writes to a file.
#include 
unsigned _dos_write(int handle, void far *buf,
unsigned len, unsigned *nwritten);

_dos_write uses DOS function Ox40 to write len bytes from the buffer
pointed to by the far pointer buf to the file associated with handle.
_dos_write does not translate a linefeed character (LF) to a CR/LF pair
because all its files are binary files.

Chapter 2, The run-time library

125

The actual number of bytes written is stored at the location pointed to by
nwritten. If the number of bytes actually written is less than that
requested, the condition should be considered an error and probably
indicates a full disk.
For disk files, writing always proceeds from the current file pointer. On
devices, bytes are directly sent to the device.
Return ,value

On successful completion, _dos_read returns o. Otherwise, it returns the
DOS error code and the global variable errno is set to one of the following:
EACCES
EBADF

Permission denied
Bad file number

See Also

_dos_open, _dos_creat, _dos_read

Example

#incl ude 
#include 
#include 
int main{void)
{

unsigned count;
int handle;
char buf[ll] = "0123456789";
/* create a file containing 10 bytes */
if (_dos_creat{"DUMMY.FIL", _A_NORMAL, &handle)
perror ("Unable to create DUMMY. FIL") ;
return 1;

if (_dos_write {handle, buf, strlen{buf), &count)
perror{"Unable to write to DUMMY.FIL");
return 1;
_dos_close{handle);
return 0;

~=

~=

0)

0) {

/* close the file */

dostounix
Function
Syntax

126

Converts date and time to UNIX time format.
#inc1ude 
long dostounix(struct date *d, struct time *t);

Borland C++ Library Reference

dostounix

Remarks

dostounix converts a date and time as returned from getdate and gettime
into UNIX time format. d points to a date structure, and tpoints to a time

structure containing valid DOS date and time information.
The date and time must not be earlier than or equal to Jan 11980 00:00:00.
Return value

UNIX version of current date and time parameters: number of seconds
since 00:00:00 on January 1, 1970 (GMT).

See also

unixtodos

Example

#include
#include
#include
#include






int main(void)
{

time_t ti
struct time d_timei
struct date d_datei
struct tm *locali
getdate(&d_date) i
gettime(&d_time)i
t = dostounix(&d_date, &d_time) i
local = localtime(&t) i
printf("Time and Date: %s\n", asctime(local))
return 0i

i

drawpoly
Function
Syntax

Remarks

Draws the outline of a polygon.
#include 
void far drawpoly(int numpoints, int far *polypoints);

I

drawpoly draws a polygon with numpoints points, using the current line

style and color.

*polypoints points to a sequence of (numpoints x 2) integers. Each pair of
integers gives the x and y coordinates of a point on the polygon.

Chapter 2, The run-time library

127

drawpoly

-..
Return value

In order to draw a closed figure with n vertices, you must pass n + 1
coordinates to drawpoly where the nth coordinate is equal to the Oth.
None.

See also

fillpoly, floodfill, graphresult, setwritemode

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;

int poly[lO];

/* our polygon array */

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf (" Press any key to halt:");
getch();
exit(l);
/* terminate with an error code */

maxx = getmaxx();
maxy = getmaxy();
poly[O] = 20;
poly[l] = maxy 2·,
poly[2] = maxx - 20;
poly[3] = 20;
poly[4] = maxx - 50;
poly[5] = maxy - 20;
poly[6] = maxx 2;
poly [7] = maxy 2;
poly[8] = poly[O];
poly[9] = poly[l];
drawpoly(5, poly);

/* first vertex */
/* second vertex */
/* third vertex */
/* fourth vertex */
/* drawpoly doesn't automatically close */
/* the polygon, so we close it */
/* draw the polygon */

/* clean up */
getch() i
closegraph();

128

Borland C++ Library Reference

dup

return 0;

dup
Function
Syntax

Remarks

Duplicates a file handle.
#include 
int dup(int handle);

dup creates a new file handle that has the following in common with the

original file handle:
same open file or device
r::1 same file pointer (that is, changing the file pointer of one changes the
other)
El same access mode (read, write, read/write)

II

handle is a file handle obtained from a _creat, creat, _open, open, dup, or
dup2 call.
Return value

Upon successful completion, dup returns the new file handle, a nonnegative in teger; otherwise, dup returns -1.
In the event of error, the global variable errno is set to one of the following:
EMFILE
EBADF

Too many open files
Bad file number

See also

_close, close, _creat, creat, creatnew, creattemp, dup2, fopen, _open,
open

Example

#include
#include
#include
#include






void flush(FILE *stream);
int main (void)
FILE *fpi
char msg[]

= "This is a test";

/* create a file */

Chapter 2, The run-time library

129

dup

fp = fopen("DUMMY.FIL", "W");
if (fp) {
/* write some data to the file */
fwrite(msg, strlen(msg), 1, fp);
clrscr () ;
printf (" Press any key to flush DUMMY. FIL: ") ;
getch () ;
/* flush the data to DUMMY.FIL without closing it */
flush(fp) ;
printf("\nFile was flushed, Press any key to quit:");
getch () ;
else
printf("Error opening file!\n");
return 0;
void flush(FILE *stream)
{

int duphandle;
/* flush Be's internal buffer */
fflush(stream) ;
/* make a duplicate file handle */
duphandle = dup(fileno(stream));
/* close duplicate handle to flush DOS buffer */
close(duphandle);

dup2
Function
Syntax

Remarks

Duplicates a file handle (oldhandle) onto an existing file handle (newhandle).
#include 
int dup2(int oldhandle, int newhandle);

dup2 is not available on UNIX System III.
dup2 creates a new file handle that has the following in common with the

original file handle:
• same open file or device

130

Borland C++ Library Reference

dup2

same file pointer (that is, changing the file pointer of one changes the
other)
a same access mode (read, write, read/write)
13

dup2 creates a new handle with the value of newhandle. If the file
associated with newhandle is open when dup2 is called, the file is closed.

newhandle and oldhandle are file handles obtained from a creat, open, dup,
or dup2 call.
Return value

dup2 returns

aon successful completion, -1 otherwise.

In the event of error, the global variable errno is set to one of the following:

EMFILE
EBADF

Too many open files
Bad file number

See also

_close, close, _creat, creat, creatnew, creattemp, dup, fopen, _open, open

Example

#include 
#include 
#include 
#include 
#include 
#define STDOUT 1
int main(void}
{

int fptr, oldstdout;
char msg[] = "This is a test";
/* create a file */
fptr = open ( "DUMMY. FIL", O_CREAT I O_RDWR, S_IREAD I S_IWRITE);
if (fptr) {
/* create a duplicate handle for standard output */
oldstdout = dup(STDOUT};
/* redirect standard output to DUMMY.FIL by duplicating the */
/* file handle onto the file handle for standard output */

dup2(fptr, STDOUT};
/* close the handle for DUMMY.FIL */
close (fptr) ;
/* this will be redirected into DUMMY.FIL */
write (STDOUT, msg, strlen(msg}};
/* restore original standard output handle */
dup2(oldstdout, STDOUT};
/* close the duplicate handle for STDOUT */
close(oldstdout};

Chapter 2, The run-time library

131

dup2

else
printf("Error opening file!\n");
return 0;

ecvt
Function
Syntax

Remarks

Converts a floating-point number to a string.
#include 
char *ecvt(double value, int ndig, int *dec, int *sign);

ecvt converts value to a null-terminated string of ndig digits, starting with

the leftmost significant digit, and returns a pointer to the string. The
position of the decimal point relative to the beginning of the string is
stored indirectly through dec (a negative value for dec means that the
decimal lies to the left of the returned digits). There is no decimal point in
the string itself. If the sign of value is negative, the word pointed to by sign
is nonzero; otherwise, it's O. The low-order digit is rounded.
Return value

The return value of ecvt points to static data for the string of digits whose
content is overwritten by each call to ecvt and fcvt.

See also

fcvt, gcvt, sprintf

Example

#include 
#include 
int main(void)
{

char *string;
double value;
int dec, sign, ndig = 10;
value = 9.876;
string = ecvt(value, ndig, &dec, &sign);
printf("string = %s
dec = %d sign = %d\n", string, dec, sign);
value = -123.45;
ndig= 15;
string = ecvt(value,ndig,&dec,&sign);
printf("string = %s dec = %d sign = %d\n", string, dec, sign);
value = 0.678ge5; /* scientific notation */
ndig = 5;
string = ecvt(value,ndig,&dec,&sign);
printf("string = %s
dec = %d sign = %d\n", string, dec, sign);

132

Borland C++ Library Reference

ecvt

return 0;

ellipse
Function -- Draws an elliptical arc.
Syntax

#include 
void far ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius);

Remarks

ellipse draws an elliptical arc in the current drawing color with its center
at (x,y) and the horizontal and vertical axes given by xradius and yradius,
respectively. The ellipse travels from stangle to endangle. If stangle equals 0
and endangle equals 360, the call to ellipse draws a complete ellipse.

The angle for ellipse is reckoned counterclockwise, with 0 degrees at
3 0' clock, 90 degrees at 12 a' clock, and so on.
~

Return value

The linestyle parameter does not affect arcs, circles, ellipses, or pie slices.
Only the thickness parameter is used.
None.

See also

arc, circle, fillellipse, sector

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */

int
int
int
int

gdriver = DETECT, gmode, errorcode;
midx, midy;
stangle = 0, endangle = 360;
xradius = 100, yradius = 50;

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode 1= grOk) { /* an error occurred */
print f ("Graphics error: %s \n", grapherrormsg (errorcode) ) ;
print f ( "Press any key to halt:") ;

Chapter 2, The run-time library

133

•

ellipse

getch () ;
exi t (1) ;

/* terminate with an error code */

midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor()) ;
/* draw ellipse */
ellipse (midx, midy, stangle, endangle, xradius, yradius);

/* clean up * /
getch();
closegraph ( ) ;
return 0;

Function
Syntax

Description

Inserts literal values directly into code.
#inc1ude 
void __emit__ (argument, ... );

__ernit_ _ is an inline function that lets you insert literal values directly
into object code as it is compiling. It is used to generate machine language
instructions without using inline assembly language or an assembler..

Generally the arguments of an _ _ernie _ call are single-byte machine
instructions. However, because of the capabilities of this function, more
complex instructions, complete with references to C variables, can be
constructed.
.
..

134

You should only use this function if you are familiar with the machine
language of the 80x86 processor family. You can use this function to place
arbitrary bytes in the instruction code of a function; if any of these bytes
are incorrect, the program misbehaves and can easily crash your machine.
Borland C++ does not attempt to analyze your calls for correctness in any
way. If you encode instructions that change machine registers or memory,
Borland C++ will not be aware of it and might not properly preserve
registers, as it would in many cases with inline assembly language (for
example, it recognizes the usage of SI and DI registers in inline
instructions). You are completely on your own with this function.

Borland C++ Library Reference

You must pass at least one argument to _ _emit_ _ ; any number can be
given. The arguments to this function are not treated like any other
function call arguments in the language. An argument passed to
_ _ emit_ _ will not be converted in any way.
There are special restrictions on the form of the arguments to _ _ emit__ .
Arguments must be in the form of expressions that can be used to
initialize a static object. This means that integer and floating-point
constants and the addresses of static objects can be used. The values of
such expressions are written to the object code at the point of the call,
exactly as if they were being used to initialize data. The address of a
parameter or auto variable, plus or minus a constant offset, may also be
used. For these arguments, the offset of the variable from BP is stored.
The number of bytes placed in the object code is determined from the type
of the argument, except in the following cases:
11 If

a signed integer constant (i.e. Ox90) appears that fits within the range
of 0 to 255, it is treated as if it were a character.
c If the address of an auto or parameter· variable is used, a byte is written
if the offset of the variable from BP is between -128 and 127; otherwise,
a word is written.
Simple bytes are written as follows:
__ emit __ (Ox90);

If you want a word written, but the value you are passing is under 255,
simply cast it to unsigned as follows:
__ emit __ (OxB8, (unsigned) 17) ;

or
__ emit __ (OxB8, 17u);

Two- or four-byte address values can be forced by casting an address to
void near * or void far *, respectively.
Return value
Example

None.
#include 
int main(void)
{

/* emit code that generates a print screen via int S */
__ emit __ (Oxcd,OxOS); /* INT OSh */

return 0;

Chapter 2, The run-time library

135

eof

eaf
Function
Syntax

Remarks
Return value

Checks for end-of-file.
#incIude 
int eof(int handle);

eof determines whether the file associated with handle has reached endof-file.

If the current position is end-of-file, eof returns the value 1; otherwise, it
returns O. A return value of -1 indicates an error; the global variable errno
is set to
EBADF

Bad file number

See also

clearerr, feof, ferror, perror

Example

#include
#include
#include
#include






int main(void)
{

FILE *temp_filei
int handle;
char msg[] = "This is a test", chi
/* create a unique temporary file */
if ((temp_file = tmpfile()) == NULL)
perror ( "OPENING FILE:") i
exit(l);
/* get handle associated with file */
handle = fileno(temp_file);
/* write some data to the file */
write (handle, msg, strlen(msg))i
/* seek to the beginning of the file */
lseek(handle, OL, SEEK_SET);
/* reads chars from the file until EOF is hit */
do {
read (handle, &ch, 1);
printf("%c", ch);

136

Borland C++ Library Reference

eof

} while (!eof(handle));
/* close and remove the temporary file */
fclose(temp_file) ;
return 0;

execl, execle, execlp, execlpe, execv, execve, execvp, execvpe
Function
Syntax

Loads and runs other programs.
#include 
int execl(char *path, char *argO *argl, ... , *argn, NULL);
int execle(char *path, char *argO, *argl, ... , *argn, NULL, char **env);
int execlp(char *path, char *argO, *argl, ... , *argn, NULL);
int execlpe(char *path, char *argO, *argl, ... , *argn, NULL, char **env);
int execv(char *path, char *argv[]);
int execve(char *path, char *argv[], char **env);
int execvp(char *path, char *argv[]);
int execvpe(char *path, char *argv[], char **env);
ANSI C

Remarks

C++ only

The functions in the exec ... family load and run (execute) other programs,
known as child processes. When an exec ... call succeeds, the child process
overlays the parent process. There must be sufficient memory available for
loading and executing the child process.

path is the file name of the called child process. The exec ... functions
search for path using the standard DOS search algorithm:
c If no explicit extension is given, the functions search for the file as
given. If the file is not found, they add .COM and search again. If that
search is not successful, they add .EXE and search one last time.
D If an explicit extension or a period is given, the functions search for the
file exactly as given.
The suffixes I, v, p, and e added to the exec ... "family name" specify that
the named function operate with certain capabilities.

p

The function searches for the file in those directories specified by the
DOS PATH environment variable (without the p suffix, the function
searches only the current working directory). If the path parameter

Chapter 2, The run-time library

137

execl, execle, execlp, execlpe, execv, execve, execvp, execvpe

does not contain an explicit directory, the function searches first the
current directory, then the directories set with the DOS PATH
environment variable.
I

The argument pointers (argO, argl, ... , argn) are passed as separate
arguments. Typically, the 1suffix is used when you know in advance
the number of arguments to be passed.

v

The argument pointers (argv[OJ ... , arg[nJ) are passed as an array of
pointers. Typically, the v suffix is used when a variable number of
arguments is to be passed.

e

The argument env can be passed to the child process, letting you alter
the environment for the child process. Without the e suffix, child
processes inherit the environment of the parent process.

Each function in the exec ... family must have one of the two argumentspecifying suffixes (either 1 or v). The path search and environment
inheritance suffixes (p and e) are optional.
For example,
II

execl is an exec ... function that takes separate arguments, searches only

the root or current directory for the child, and passes on the parent's
environment to the child .
• execvpe is an exec ... function that takes an array of argument pointers,
incorporates PATH in its search for the child process, and accepts the
env argument for altering the child's environment.
The exec ... functions must pass at least one argument to the child process
(argO or argv[OJ); this argument is, by convention, a copy of path. (Using a
different value for this Oth argument won't produce an error.)
Under DOS 3.x, path is available for the child process; under earlier
versions of DOS, the child process cannot use the passed value of the Oth
argument (argO or argv[OJ).
When the 1 suffix is used, argO usually points to path, and argl, ... , argn
point to character strings that form the new list of arguments. A
mandatory null following argn marks the end of the list.
When the e suffix is used, you pass a list of new environment settings
through the argument env. This environment argument is an array of
character pointers. Each element points to a null-terminated character
string of the form
envvar

138

= value

Borland C++ Library Reference

execl, execle, execlp, execlpe, execv, execve, execvp, execvpe

where envvar is the name of an environment variable, and value is the
string value to which envvar is set. The last element in env is null. When
env is null, the child inherits the parents' environment settings.
The combined length of argO + argl + ... + argll (or of argv[O] + argv[1] + ...
+ argn[n]), including space characters that separate the arguments, must
be less than 128 bytes. Null terminators are not counted.
When an exec ... function call is made, any open files remain open in the
child process.
Return value

If successful, the exec ... functions do not return. On error, the exec ...
functions return -1, and the global variable errno is set to one of the
following:
E2BIG
EACCES
EMFILE
ENOENT
ENOEXEC
ENOMEM

See also
Examples

Arg list too long
Permission denied
Too many open files
Path or file name not found
Exec format error
Not enough core

abort, atexit, _exit, exit, _fpreset, search path, spawn ... , system
#include 
#include 
int main(int argc, char *argv[])
{

int ii
printf("Child running .. . \n")i
printf("%s\n",getenv("PATH")) i
for(i = Oi i < argci itt)
printf("argv[%d]: %s\n", i, argv[i])
return Oi

Each function has
its own example
program.

i

#include 
#include 
#include 
int main(int argc, char *argv[])
{

int lOOPi
printf("%s running ... \n\n", argv[O]);
if (argc == 1) {
/* check for only one command-line parameter */
printf("%s calling itself again ... \n", argv[O]) i
execl(argv[O], argv[O], "ONE", "TWO", "THREE", NULL)i
perror ( "EXEC: " ) i

Chapter 2, The run-time library

139

execl, execle, execlp, execlpe, execv, execve, execvp, execvpe

exit (1);
printf("%s called with arguments:\n", argv[O]);
for (loop = 1; loop <= argc; loop++)
puts (argv[loop] );
/* display all command-line parameters */
return 0;

#include
#include
#include
#include
#include







int main(int argc, char *argv[], char *env[])
{

int loop;
char *new_env [] = { "TESTING", NULL };
printf("%s running ... \n\n", argv[O]);
if (argc == 1) {
/* check for only one command-line parameter */
printf("%s calling itself again ... \n", argv[O]);
execle(argv[O], argv[O], "ONE", "TWO", "THREE", NULL, new_env);
perror ( "EXEC: " ) ;
exi t (1) ;
printf("%s called with arguments:\n", argv[O]);
for (loop = 1; loop <= argc; loop++)
puts(argv[loop]);
/* display all command-line parameters */
/* display the first environment parameter */
printf("value of env[O]: %s\n",env[O]);
return 0;

#include 
#include 
#include 
int main(int argc, char *argv[], char **envp)
{

int i;
printf("Command line arguments:\n");
for (i=O; i < argc; ++i)
printf(" [%2d] %s\n", i, argv[i]);
printf("About to exec child with argl arg2 .. . \n");
execlpe("CHILD.EXE", "CHILD.EXE", "argl", "arg2", NULL, envp);
perror("exec error");
exi t (1) ;

140

Borland C++ Library Reference

execl, execle, execlp, execlpe, execv, execve, execvp, execvpe

return 0;

#include 
#include 
#include 
int main(int argc, char *argv[], char **envp)
int i;
printf ("Command line arguments: \n");
for (i=O; i < argc; tti)
printf("[%2d] %s\n", i, argv[i]);
printf ("About to exec child with arg1 arg2 ... \n");
execlpe("CHILD.EXE", "CHILD.EXE", "arg1", "arg2", NULL, envp);
perror("exec error");
return 1;

#include 
#include 
#include 
void main(int argc, char *argv[])
{

int i;
printf ("Command line arguments: \n") ;
for (i=O; i
#include 
#include 
void main(int argc, char *argv[], char **envp)
{

int i;
printf ("Command line arguments: \n") ;
for (i=O; i
#include 
#include 
void main(int argc, char *argv[])
int i;
printf("Command line arguments:\n");
for (i=O; i
#include 
#include 
void main(int argc, char *argv[], char **envp)
int i;
printf ("Command line arguments: \n");
for (i=O; i
void _exit(int status);

Borland C++ Library Reference

Remarks

_exit terminates execution without closing any files, flushing any output,

or calling any exit functions.
The calling process uses status as the exit status of the process. Typically a
value of a is used to indicate a normal exit, and a nonzero value indicates
some error.
Return value

None.

See also

abort, atexit, exec ... , exit, spawn ...

Example

#include 
#include 
void done (void) ;
int main(void)
{

atexit(done);
_exit (0);
return 0;
void done ()
{

printf("hello\n");

exit
Function
Syntax

Remarks

Terminates program.
#include 
void exit(int status);

exit terminates the calling process. Before termination, all files are closed,
buffered output (waiting to be output) is written, and any registered "exit
functions" (posted with atexit) are called.

status is provided for the calling process as the exit status of the process.
Typically a value of a is used to indicate a normal exit, and a nonzero
value indicates some error. It is set with one of the following
Normal program termination.

Chapter 2, The run-time library

143

exit

EXIT_FAILURE

Return value

Abnormal program termination; signal to
operating system that program has terminated
with an error.

None.

See also

abort, atexit, exec ... , _exit, keep, signal, spawn ...

Example

#inc1ude 
#include 
#include 
int main(void)
{

int status;
printf("Enter either 1 or 2\n");
status = getch();
exit(status - '0');
/* sets DOS error level */
return 0;
/* NOTE: This line is never reached */

exp, expl
Function
Syntax

Calculates the exponential e to the x.

Real versions:
#include 
double exp(double x);
long double expl(long double x);
DOS

expl
Realexp
Complexexp

Remarks

•
•
•

UNIX

Windows

ANSI C

Complex version:
#include 
complex exp(complex x);

C++ only

•

•

•

•

•

•

exp calculates the exponential function eX.
expl is the long double version; it takes a long double argument and

returns a long double result.
The complex exponential function is defined by
exp(x + y i)
Return value

=

exp(x) (cos(y) + i sin(y»

exp returns eX.

Sometimes the arguments passed to these functions produce results that
overflow or are incalculable. When the correct value overflows, exp

144

Borland C++ Library Reference

exp, expl

returns the value HUGE_VAL and expl returns _LHUGE_VAL. Results of
excessively large magnitude will cause the global variable errno to be set
to
ERANGE

Result out of range

On underflow, these functions return 0.0, and the global variable errno is
not changed.
Error handling for these functions can be modified through the functions
matherr and _matherrl.
See Also

frexp, Idexp, log, log10, matherr, pow, pow10, sqrt

Example

#include 
#include 
int main(void)
{

double result, x = 4.0;
result = exp (x);
printf("'e' raised to the power of %If (e
return 0;

A

%If)

=

%If\n", x, x, result);

fabs, fabsl
Function
Syntax

Returns the absolute value of a floating-point number.
#include 
double fabs(double x);
long double fabsl(long double x);

fabs
fabsl

Remarks
Return value

DOS

UNIX

•
•

•

Windows

ANSI C

•
•

•

C++ only

fabs calculates the absolute value of x, a double. fabsl is the long double
version; it takes a long double argument and returns a long double result.
fabs and fabsl return the absolute value of x.

See also

abs, cabs, labs

Example

#include 
#include 
int main(void)
{

Chapter 2, The run-time library

145

I

fabs, fabsl

float number = -1234.0;
printf("number: %f absolute value: %f\n", number, fabs(number));
return 0;

farcalloc
Function
Syntax

Remarks

Allocates memory from the far heap.
#include 
void far *farcallodunsigned long mmits, unsigned long unitsz);

farcalloc allocates memory from the far heap for an array containing

mmits elements, each unitsz bytes long.

For allocating from the far heap, note that
all available RAM can be allocated .
• blocks larger than 64K can be allocated .
• far pointers (or huge pointers if blocks are larger than 64K) are used to
access the allocated blocks.

III

In the compact, large, and huge memory models, farcalloc is similar,
though not identical, to calloc. It takes unsigned long parameters, while
calloc takes unsigned parameters.
A tiny model program cannot make use of farcalloc.
Return value

farcalloc returns a pointer to the newly allocated block, or null if not

enough space exists for the new block.
See also

calloc, farcoreleft, farfree, farmalloc, malloc

Example

#include
#include
#include
#include






int main (void)
{

char far *fptr, *str

= "Hello";

/* allocate memory for the far pointer */
fptr = (char far *) farcalloc(10, sizeof(char));
/* copy "Hello" into allocated memory */

146

Borland C++ Library Reference

farcalloc

/* Note: movedata is used because you might be in a small data model, in which

case a normal string copy routine can not be used since it assumes the
pointer size is near. */
movedata(FP_SEG(str), FP_OFF(str),
FP_SEG(fptr), FP_OFF(fptr),
strlen(str)

I

)i

II

/* display string (note the F modifier) */
printf("Far string is: %Fs\n", fptr) i
/* free the memory */

farfree (fptr)
return 0i

i

farcoreleft
Function
Syntax

Remarks

Returns a measure of unused memory in far heap.
#include 
unsigned long farcoreleft( void);

farcoreleft returns a measure of the amount of unused memory in the far
heap beyond the highest allocated block.

A tiny model program cannot make use of farcoreleft.
Return value

farcoreleft returns the total amount of space left in the far heap, between

the highest allocated block and the end of available memory.
See also

coreleft, farcalloc, farmalloc

Example

#inc1ude 
#include 
int main (void)
{

printf("The difference between the highest allocated block in the far\n")
printf("heap and the top of the far heap is: %lu bytes\n", farcoreleft())
return 0i

Chapter 2, The run-time library

i
i

147

farfree

farfree
Function
Syntax

Remarks

Frees a block from far heap.
#include 
void farfree( void far * block);

farfree releases a block of memory previously allocated from the far heap.
A tiny model program cannot make use of farfree.

In the small and medium memory models, blocks allocated by farmalloe
cannot be freed with normal free, and blocks allocated with malloe cannot
be freed with farfree. In these models, the two heaps are completely
distinct.
Return value

None.

See also

farealloe, farmalloe

Example

#inc1ude
#include
#include
#include






int main(void)
{

char far *fptr, *str

= "Hello";

/* allocate memory for the far pointer */
fptr = (char far *) farcalloc(lO, sizeof(char));

/ * copy "Hello" into allocated memory * /
/* Note: movedata is used because you might be in a small data model, in which

case a normal string copy routine can't be used since it assumes the
pointer size is near. */
movedata(FP_SEG(str), FP_OFF(str),
FP_SEG(fptr), FP_OFF(fptr),
strlen(str)) ;
/* display string (note the F modifier) */
printf("Far string is: %Fs\n", fptr);
/* free the memory */
farfree(fptr);
return 0;

148

Borland C++ Library Reference

farheapcheck

farheapcheck
Function
Syntax

Remarks
Return value

Checks and verifies the far heap.
#include 
int farheapcheck(v~id);

farheapcheck walks through the far heap and examines each block,
checking its pointers, size, and other critical attributes.

The return value is less than zero for an error and greater than zero for
success.
_HEAPEMPTY is returned if there is no heap (value 1).
_HEAPOK is returned if the heap is verified (value 2).
_HEAPCORRUPT is returned if the heap has been corrupted (value -1).

See also

heapcheck

Example

#include 
#include 
#define NUM_PTRS 10
#define NUM_BYTES 16
int main (void)
{

char far *array[ NUM_PTRS l;
int i;
for( i = 0; i < NUM_PTRS; itt
array [ i 1 = (char far *) farmalloc( NUM_BYTES );
for( i = 0; i < NUM_PTRS; i t= 2 )
far free ( array [ i 1 );
if( farheapcheck() == _HEAPCORRUPT )
printf( "Heap is corrupted.\n" );
else
printf ( "Heap is OK. \n" );
return 0;

farheapcheckfree
Function

Checks the free blocks on the far heap for a constant value.

Chapter 2, The run-time library

149

farheapcheckfree

Syntax

Return value

#include 
int farheapcheckfree(unsigned int fillvalue);

The return value is less than zero for an error and greater than zero for
success.
_HEAPEMPTY is returned if there is no heap (value 1).
_HEAPOK is returned if the heap is accurate (value 2).
_HEAPCORRUPT is returned if the heap has been corrupted (value -1).
BADVAL UE is returned if a value other than the fill value was found
(value -3).

See also

farheapfillfree, heapcheckfree

Example

#include 
#include 
#include 
#define NUM_PTRS 10
#define NUM_BYTES 16
int main(void)
{

char far *array[NUM_PTRSj;
int i j res;
I

I

for (i = 0; i < NUM_PTRS; itt)
if ((array[i] = (char far *) farmalloc(NUM_BYTES))
printf ("No memory for allocation\n");
return 1;

==

NULL) {

for (i = 0; i < NUM_PTRS; i += 2)
farfree(array[i]) ;
if(farheapfillfree(l) < 0) {
printf("Heap corrupted.\n");
return 1;
for (i = 1; i < NUM_PTRS; i += 2)
for (j = 0; j < NU~_BYTES; j++)
array [i] [j] = 0;
res = farheapcheckfree(l);
if (res < 0)
switch(res) {
case _HEAPCORRUPT:

150

Borland C++ Library Reference

farheapcheckfree

printf("Heap eorrupted.\n");
return 1;
ease _BADVALUE:
printf("Bad value in free spaee.\n");
return 1;
default :
printf ("Unknown error. \n");
return 1;

I

printf("Test sueeessful.\n");
return 0;

farheapchecknode
Function
Syntax

Remarks

Return value

Checks and verifies a single node on the far heap.
#include 
int farheapchecknode(void *node);

If a node has been freed and farheapchecknode is called with a pointer to
the freed block, farheapchecknode can return _BADNODE rather than
the expected _FREE ENTRY. This is because adjacent free blocks on the
heap are merged, and the block in question no longer exists.

The return value is less than zero for an error and greater than zero for
success.
_HEAPEMPTY is returned if there is no heap (value 1).
_HEAPCORRUPT is returned if the heap has been corrupted (value -1).
_BADNODE is returned if the node could not be found (value -2).
_FREEENTRY is returned if the node is a free block (value 3).
_USEDENTRY is returned if the node is a used block (value 4).

See also

heapchecknode

Example

#inc1 ude 
#inelude 
#define NUM_PTRS 10
#define NOM_BYTES 16
int main(void)
{

Chapter 2, The run-time library

151

farheapchecknode

char far *array[ NUM_PTRS l;
int i;
for( i = 0; i < NUM_PTRS; itt
array [ i 1 = (char far *) farrnalloc( NUM_BYTES );
for( i = 0; i < NUM_PTRS; i t= 2 )
farfree( array [ i 1 );
for( i = 0; i < NUM_PTRS; itt) {
printf ( "Node %2d ", i );
switch( farheapchecknode( array [ l)) {
case _HEAPEMPTY:
printf ("No heap. \n" );
break;
case _HEAPCORRUPT:
printf("Heap corrupt.\n" );
break;
case _BADNODE:
printf("Bad node.\n" );
break;
case _FREEENTRY:
printf("Free entry.\n" );
break;
case _USEDENTRY:
printf ("Used entry. \n" );
break;
default :
printf ("Unknown return code. \n") ;
break;

return 0;

fa rhea pfillfree
Function
Syntax

Return value

Fills the free blocks on the far heap with a constant value.
#include 
int farheapfillfree(unsigned int fillvalue);

The return value is less than zero for an error and greater than zero for
success.
_HEAPEMPTY is returned if there is no heap (value 1).

152

Borland C++ Library Reference

fcrheapfillfree

_HEAPOK is returned if the heap is accurate (value 2).
_HEAPCORRUPT is returned if the heap has been corrupted (value -1).
See also

farheapcheckfree, heapfillfree

Example

#incl ude 
#include 
#include 
#define NOM_PTRS 10
#define NOM_BYTES 16
int main(void)
{

char far *array[NUM_PTRS];
int i, j res;
I

for (i = 0; i < NUM_PTRS; itt)
if ((array[i] = (char far *) farmalloc(NUM_BYTES)) == NULL) {
printf ("No memory for allocation\n");
return 1;
for (i = 0; i < NUM_PTRS; i t= 2)
farfree(array[i]);
if(farheapfillfree(l) < 0) {
printf(IIHeap corrupted.\n");
return 1;
for (i = 1; i < NUM_PTRS; i t= 2)
for (j = 0; j < NUM_BYTES; j+t)
array[i] [j] = 0;
res = farheapcheckfree(l);
if (res < 0)
switch(res) {
case _HEAPCORRUPT:
printf(IIHeap corrupted.\n");
return 1;
case _BADVALUE:
printf("Bad value in free space.\n");
return 1;
default :
printf ("Unknown error. \n ") ;
return 1;
printf("Test successful.\n");
return 0;

Chapter 2, The run-time library

153

forheapwolk

farheapwalk
Function
Syntax

Remarks

farheapwalk is used to "walk" through the far heap node by node.

#inc1ude 
int farheapwalk(struct farheapinfo *hi);

farheapwalk assumes the heap is correct. Use farheapcheck to verify the
heap before using farheapwalk. _HEAPOK is returned with the last block
on the heap. _HEAPEND will be returned on the next call to farheapwalk.
farheapwalk receives a pointer to a structure of type heapinfo (defined in
alloc.h). For the first call to farheapwalk, set the hi.ptr field to null.
farheapwalk returns with hi.ptr containing the address of the first block.

hi.size holds the size of the block in bytes. hUn_use is a flag that's set if the
block is currently in use.
Return value

_HEAPEMPTY is returned if there is no heap (value 1).
_HEAPOK is returned if the heapinfo block contains valid data (value 2).
_HEAPEND is returned if the end of the heap has been reached (value 5).

See also

heapwalk

Example

#include 
#include 
#define NUM_PTRS 10
#define NUM_BYTES 16
int main ( void)
{

struct farheapinfo hij
char far *array[ NUM_PTRS
int ij

1j

for( i = OJ i < NUM_PTRSj itt
array [ i 1 = (char far *) farmalloc( NUM_BYTES ) j
for( i = OJ i < NUM_PTRSj i t= 2 )
farfree( array [ i 1 ) j
hi.ptr = NULLj
printf("
Size Status\n")j
printf ( "
------ \n" ) j
while( farheapwalk( &hi ) == _HEAPOK )
%s\n", hi.size, hi.in_use? "used"
printf ( "%7u

154

"free")j

Borland C++ Library Reference

farmalloc

farmalloc
Function
Syntax

Allocates from far heap.
#include 
void far *farmalloc(unsigned long nbytes);

I
Remarks

farmalloc allocates a block of memory nbytes bytes long from the far heap.

For allocating from the far heap, note that
mall available RAM can be allocated.
£.I blocks larger than 64K can be allocated.

c far pointers are used to access the allocated blocks.

In the compact, large, and huge memory models, farmalloc is similar
though not identical to malloc. It takes unsigned long parameters, while
malloc takes unsigned parameters.
A tiny model program cannot make use of farmalloc.
Return value

farmalloc returns a pointer to the newly allocated block, or null

if not

enough space exists for the new block.
See also

farcalloc, farcoreleft, farfree, farrealloc, malloc

Example

#include
#include
#include
#include






int main (void)
{

char far *fptr, *str

= "Hello";

1* allocate memory for the far pointer *1
fptr = (char far *) farmalloc(lO);
1* copy "Hello" into allocated memory *1
1* movedata is used because we might be in a small data model, in which case a
normal string copy routine can not be used since it assumes the pointer size
is near. *I
movedata (FP_SEG (str) , FP_OFF(str),
FP_SEG(fptr), FP_OFF(fptr),
strlen(str)) ;

1* display string (note the F modifier) *1
printf("Far string is: %Fs\n", fptr);

Chapter 2, The run-time library

155

farmalloc

/* free the memory */
farfree(fptr);
return 0;

farrealloc
Function
Syntax

Adjusts allocated block in far heap.
#inc1ude 
void far *farrealloc{void far *oldblock, unsigned long nbytes);
DOS

Remarks

UNIX

farrealloc adjusts the size of the allocated block to nbytes, copying the

contents to a new location, if necessary.
For allocating from the far heap, note that
all available RAM can be allocated .
• blocks larger than 64K can be allocated .
• far pointers are used to access the allocated blocks.

iii

A tiny model program cannot make use of farrealloc.
Return value

farrealloc returns the address of the reallocated block, which might be

different than the address of the original block. If the block cannot be
reallocated, farrealloc returns null.
See also

farmalloc, realloc

Example

#inc1ude 
#include 
int main(void)
{

char far *fptr;
char far *newptr;
fptr = (char far *) farmalloc(16);
printf("First address: %Fp\n", fptr);
/* We use a second pointer, newptr, so that in the case of farrealloc()
returning NULL, our original pointer is not set to NULL. */
newptr = (char far *) farrealloc(fptr,64);
printf ("New address : %Fp\n", newptr);
if (newptr != NULL)

156

Borland C++ Library Reference

farrealloc

farfree (newptr) ;
return 0;

fclose
Function
Syntax

Remarks

Return value

I

Closes a stream.
#include 
int fclose(FILE *stream);

fclose closes the named stream. All buffers associated with the stream are
flushed before closing. System-allocated buffers are freed upon dosing.
Buffers assigned with setbuf or setvbuf are not automatically freed. (But if
setvbuf is passed null for the buffer pointer, it will free it upon close.)
fclose returns 0 on success. It returns EOF if any errors were detected.

See also

close, fcloseall, fdopen, fflush, flushall, fopen, freopen

Example

#include 
#include 
int main(void)
{

FILE *fp;
char buf[ll] = "0123456789";
/* create a file containing 10 bytes */
fp = fopen("DUMMY.FIL", "w");
if (fp) {
fwrite(&buf, strlen(buf), 1, fp);
fclose(fp);
/* close the file */
else
printf ("Unable to open file! \n") ;
return 0;

fcloseall
Function

Closes open streams.

Chapter 2, The run-time library

157

fcloseall

Syntax

#include 
int fcloseall(void);
UNIX

Remarks

Wi ndows

fcloseall closes all open streams except stdin, stdout, stdprn, stderr, and

stdaux.
Return value

fcloseall returns the total number of streams it closed. It returns EOF if

any errors were detected.
See also

fclose, fdopen, flushall, fopen, freopen

Example

#include 
int main(void)
{

int streams_closed;
/* open two streams */
fopen("DUMMY.ONE", "w");
fopen("DUMMY.TWO", "w");
/* close the open streams */
streams_closed = fcloseall();
if (streams_closed == EOF)
perror("Error");
/* issue an error message */
else
/* print result of fcloseall() function */
printf("%d streams were closed.\n", streams_closed);
return 0;

fcvt
Function
Syntax

158

Converts a floating-point number to a string.
#include 
char *fcvt(double value, int ndig, int *dec, int *sign);

Borland C++ Library Reference

fcvt

Remarks

fevt converts value to a null-terminated string digits, starting with the
leftmost significant digit, with ndig digits to the right of the decimal point.
fevt then returns a pointer to the string. The position of the decimal point
relative to the beginning of the string is stored indirectly through dec (a
negative value for dec means to the left of the returned digits). There is no
decimal point in the string itself. If the sign of value is negative, the word
pointed to by sign is nonzero; otherwise, it is O.

The correct digit has been rounded for the number of digits to the right of
the decimal point specified by ndig.
Return value

The return value of fevt points to static data whose content is overwritten
by each call to fevt and eevt.

See also

eevt, gevt, sprintf

Example

#inc1ude 
#include 
int main(void)
{

char *str;
double num;
int dec, sign, ndig = 5;
/* a regular number */
num = 9.876;
str = fcvt(num, ndig, &dec, &sign);
printf("string = %10s decimal place = %d sign = %d\n", str, dec, sign);
/* a negative number */
num = -123.45;
str = fcvt(num, ndig, &dec, &sign);
printf("string = %10s decimal place = %d sign = %d\n", str, dec, sign);
/* scientific notation */
num = 0.678e5;
str = fcvt(num, ndig, &dec, &sign);
printf("string = %10s decimal place= %d sign = %d\n", str, dec, sign);
return 0;

fdopen
Function
Syntax

Associates a stream with a file handle.
#include 
FILE *fdopen(int handle, char *type);

Chapter 2, The run-time library

159

I

fdopen

Remarks

fdopen associ.ates a stream with a file handle obtained from creat, dup,
dup2, or open. The type of stream must match the mode of the open

handle.
The type string used in a call to fdopen is one of the following values:

r

Open for reading only.

w

Create for writing.

a

Append; open for writing at end-of-file or create for writing if the
file does not exist.

r+

Open an existing file for update (reading and writing).

w+

Create a new file for update.

a+

Open for append; open (or create if the file does not exist) for
update at the end of the file.

To specify that a given file is being opened or created in text mode,
append a t to the value of the type string (rt, w+t, and so on); similarly, to
specify binary mode, append a b to the type string (wb, a+b, and so on).
If a t or b is not given in the type string, the mode is governed by the
global variable Jmode.1f _fmode is set to O_BINARY, files will be opened
in binary mode. If Jmode is set to 0_TEXT, they will be opened in text
mode. These 0_ ... constants are defined in fcntl.h.

When a file is opened for update, both input and output can be done on
the resulting stream. However, output cannot be directly followed by
input without an intervening fseek or rewind, and input cannot be
directly followed by output without an intervening fseek, rewind, or an
input that encounters end-of-file.
Return value

On successful completion, fdopen returns a pointer to the newly opened
stream. In the event of error, it returns null.

See also

fclose, fopen, freopen, open

Example

#include
#include
#include
#incl ude






int main(void)
{

160

Borland C++ Library Reference

fdopen

int handle;
FILE *stream;
/* open a file */
handle = open(IDUMMY.FIL", O_CREAT, S_IREAD

I

S_IWRITE);

/* now turn the handle into a stream */
stream = fdopen(handle, "W");
if (stream == NULL)
printf("fdopen failed\n");
else {
fprintf (stream, "Hello world\n") ;
fclose (stream) ;
return 0;

feaf
Function
Syntax

Remarks

Detects end-of-file on a stream.
#include 
int feof(FILE *stream);

feof is a macro that tests the given stream for an end-of-file indicator.
Once the indicator is set, read operations on the file return the indicator
until rewind is called, or the file is closed.

The end-of-file indicator is reset with each input operation.
Return value

feof returns nonzero if an end-of-file indicator was detected on the last

input operation on the named stream, and aif end-of-file has not been
reached.

See also

clearerr, eof, ferror, perror

Example

#include 
int main (void)
{

FILE *stream;
stream = fopen(IDUMMY.FIL", "r"); /* open a file for reading */
fgetc(stream);
/* read a character from the file */
if (feof (stream))
/* check for EOF */
printf("We have reached end-of-file\n");

Chapter 2, The run-time library

161

teot

fclose (stream) ;
return 0;

/* close the file */

ferror
Function
Syntax

Remarks

Return value

Detects errors on stream.
#include 
int ferror(FILE *stream);

ferror is a macro that tests the given stream for a read or write error. If the
stream's error indicator has been set, it remains set until clearerr or rewind
is called, or until the stream is closed.
ferror returns nonzero if an error was detected on the named stream.

See also

clearerr, eof, feof, fopen, gets, perror

Example

#include 
int main (void)
{

FILE *stream;
/* open a file for writing */
stream = fopen ("DUMMY. FIL" "w");
I

/* force an error condition by attempting to read */
(void) getc(stream);
if (ferror(stream)) {
/* test for error on the stream */
/* display an error message */
printf("Error reading from DUMMY.FIL\n");
/* reset the error and EOF indicators */
clearerr(stream);
fclose (stream) ;
return 0;

fflush
Function

162

Flushes a stream.

Borland C++ Library Reference

fflush

Syntax

Remarks

#include 
int fflush(FILE *stream);

If the given stream has buffered output, fflush writes the output for stream
to the associated file.
The stream remains open after fflush has executed. fflush has no effect on
an unbuffered stream.

Return value

fflush returns

aon success. It returns EOF if any errors were detected.

See also

fclose, flushall, setbuf, setvbuf

Example

#include
#include
#include
#include






void flush(FILE *stream);
int main(void)
(

FILE *stream;
char msg[] = "This is a test";
/* create a file */
stream = fopen("DUMMY.FIL", "w");
/* write some data to the file */
fwrite(msg, strlen(msg), I, stream);
clrscr ( ) ;
printf ( "Press any key to flush DUMMY. FIL: " ) ;
getch () ;
/* flush the data to DUMMY.FIL without closing it */
flush (stream) ;
printf("\nFile was flushed, Press any key to quit:");
getch() ;
return 0;
void flush(FILE *stream)
int duphandle;
/* flush the stream's internal buffer */
fflush (stream) ;
/* make a duplicate file handle */
duphandle = dup(fileno(stream));

Chapter 2, The run-time library

163

fflush

/* close the duplicate handle to flush the DOS buffer */
close(duphandle);

fgetc
Function
Syntax

Remarks
Return value

Gets character from stream.
#include 
int fgetc(FILE *stream);

fgetc returns the next character on the named input stream.

On success, fgetc returns the character read, after converting it to an int
without sign extension. On end-of-file or error, it returns EOF.

See also

fgetchar, fputc, getc, getch, getchar, getche, ungetc, ungetch

Example

#include 
#include 
#include 
int main(void)
{

FILE *stream;
char string[]

= "This is a test", chi

/* open a file for update */
stream = fopen("DUMMY.FIL", "w+");

/* write a string into the file */
fwrite(string, strlen(string), I, stream);

/* seek to the beginning of the file */
fseek(stream, 0, SEEK_SET);
do {
ch = fgetc(stream);
/* read a char from the file */
putch(ch);
/* display the character */
while (ch != EOF);
fclose (stream) ;
return 0;

164

Borland C++ Library Reference

fgetchar

fgetchar
Function
Syntax

Remarks
Return value

Gets character from stdin.
#include 
int fgetchar(void);

fgetchar returns the next character from stdin.1t is defined as fgetc(stdin).

On success, fgetchar returns the character read, after converting it to an
int without sign extension. On end-of-file or error, it returns EOF.

See also

fgetc, fputchar, getchar

Example

#include 
int main(void)
{

char

Chi

/* prompt the user for input */

printf ("Enter a character followed by : ")

i

/* read the character from stdin */
ch = fgetchar () i
/* display what was read */
printf("The character read is: '%c'\n", ch)
return 0i

i

fgetpos
Function
Syntax

Gets the current file pointer.
#include 
int fgetpos(FILE *stream, fpos_t *pos);

Chapter 2, The run-time library

165

fgetpos

Remarks

fgetpos stores the position of the file pointer associated with the given

stream in the location pointed to by pas. The exact value is a magic cookie;
in other words, it is irrelevant to your purposes.
The type fpos_t is defined in stdio.h as typedef long fpos_t;.
Return value

On success, fgetpos returns O. On failure, it returns a nonzero value and
sets the global variable errno to EBADF or EINVAL.

See also

fseek, fsetpos, ftell, tell

Example

#include 
#include 
int main(void)
{

FILE *stream;
char string[J = "This is a test";
fpos_t filepos;
/* open a file for update */
stream = fopen("DUMMY.FIL", "Wi");
/* write a string into the file */
fwrite(string, strlen(string) , I, stream);
/* report the file pointer position */
fgetpos(stream, &filepos);
printf ("The file pointer is at byte %ld\n", filepos);
fclose(stream) ;
return 0;

fgets
Function
Syntax

Remarks

166

Gets a string from a stream.
#include 
char *fgets(char *s, int n, FILE *stream);

fgets reads characters from stream into the string s. The function stops
reading when it reads either n -1 characters or a newline character,
whichever comes first. fgets retains the newline character at the end of s.
A null byte is appended to s to mark the end of the string.

Borland C++ Library Reference

fgets

Return value

On success, fgets returns the string pointed to by s; it returns null on endof-file or error.

See also

cgets, fputs, gets

Example

#include 
#include 
int main(void)
{

FILE *streami
char string[J = "This is a test";
char msg[20Ji
/* open a file for update */
stream = fopen ( "DUMMY. FIL", "w+");

/* write a string into the file */
fwrite(string, strlen(string) , 1, stream) i
/* seek to the start of the file */
fseek(stream, 0, SEEK_SET);
/* read a string from the file */
fgets(msg, strlen(string)+l, stream);

/* display the string */
printf("%s", msg) i
fclose (stream) i
return 0i

filelength
Function
Syntax

Remarks
Return value

Gets file size in bytes.
#include 
long filelength(int handle);

file length returns the length (in bytes) of the file associated with handle.

On success, filelength returns a long value, the file length in bytes. On
error, it returns -1 and the global variable errno is set to
EBADF

See also

Bad file number

fopen, Iseek, open

Chapter 2, The run-time library

167

filelength

Example

#include
#include
#include
#include
#include







int main(void)
{

int handle;
char buf[ll]

= "0123456789";

/* create a file containing 10 bytes */
handle = open("DUMMY.FIL", O_RDWRIO_CREATIO_TRUNC, S_IREADIS_IWRITE);
write (handle, buf, strlen(buf));
/* display the size of the file */
printf("file length in bytes: %ld\n", filelength(handle));
/* close the file */
close (handle);
return 0;

fileno
Function
Syntax

Remarks

Return value

Gets file handle.
#include 
int fileno(FILE *stream);

fileno is a macro that returns the file handle for the given stream. If stream
has more than one handle, fileno returns the handle assigned to the
stream when it was first opened.
fileno returns the integer file handle associated with stream.

See also

fdopen, fopen, freopen

Example

#include 
int main(void)
{

FILE *stream;
int handle;
/* create a file */

168

Borland C++ Library Reference

fileno

stream

=

fopen("DUMMY.FIL", "w");

/* obtain the file handle associated with the stream */
handle = fileno(stream);
/* display the handle number x/
printf ("handle number: %d\n", handle);
/* close the file */
fclose (stream) ;
return 0;

fillellipse
Function
Syntax

Draws and fills an ellipse.
#include 
void far fillellipse(int x, int y, int xradius, int yradius);

I
•I

DOS

Remarks

Return value
See also
Example

UNIX

I
I

Windows

ANSI C I C++ only

/I

I

II

Draws an ellipse using (x,y) as a center point and xradius and yradius as
the horizontal and vertical axes, and fills it with the current fill color and
fill pattern.
None.
arc, circle, ellipse, pies lice
#include 
#include 
#include 
#include 
int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy, i;
int xradius = lOa, yradius = 50;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf ("Graphics error: %s\n", grapherrormsg (errorcode) ) ;

Chapter 2, The run-time library

169

fill ellipse

printf ( "Press any key to halt:") ;
getch();
exit(l);
/* terminate with an error code */
midx
midy

= getmaxx() / 2;
= getmaxy() / 2;

/* loop through the fill patterns */
for (i = EMPTY_FILL; i < USER_FILL; itt)
/* set fill pattern */
setfillstyle(i, getmaxcolor());
/* draw a filled ellipse */
fillellipse(midx, midy, xradius, yradius);
getch() ;

/* clean up */
closegraph ( ) ;
return 0;

fillpoly
Function
Syntax

Remarks

Draws and fills a polygon.
#inc1ude 
void far fillpoly(int numpoints, int far *polypoints);

fillpoly draws the outline of a polygon with numpoints points in the
current line style and color (just as drawpoly does), then fills the polygon

using the current fill pattern and fill color.

polypoints points to a sequence of (numpoints x 2) integers. Each pair of
integers gives the x and y coordinates of a point on the polygon.
Return value

None.

See also

drawpoly, floodfill, graphresult, setfillstyle

Example

#inc1ude
#include
#include
#include






int main (void)

170

Borland C++ Library Reference

fillpoly

/* request autodetection */
int gdriver = DETECT, gmode, errorcodej
int i, maxx, maXYj
/* our polygon array */
int poly[8] j
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, ""I j
/* read result of initialization */
errorcode = graphresult() j
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode))j
printf ( "Press any key to halt:") j
getch() j
exit(l) j
/* terminate with an error code */

maxx = getmaxx() j
maxy = getmaXY()j
poly[O]
poly[l]
poly[2]
poly[3]
poly[4]
poly[5]
poly[6]
poly [7]

= 20j

= maxy 2j
= maxx - 20j
= 20j
= maxx - 50j
= maxy - 20j
= maxx 2j
= maxy 2j

/* first vertex */
/* second vertex */
/* third vertex */
/* fourth, fillpoly automatically */
/* closes the polygon */

/* loop through the fill patterns */
for (i=EMPTY_FILLi i
#include 
int findfirst(const char *pathname, struct ffblk *ffblk, int attrib);

findfirst begins a search of a disk directory by using the DOS system call

Ox4E.

pathname is a string with an optional drive specifier, path, and file name of
the file to be found. The file name portion can contain wildcard match
characters (such as ? or *). If a matching file is found, the ffblk structure is
filled with the file-directory information.
The format of the structure ffblk is as follows:
struct ffblk {
char ff_reserved[2l];
char fCattrib;
int fCftime;
int fCfdate;
long fCfsize;
char ff_name[13];

/* reserved by DOS */
/* attribute found */

/* file time * /
/* file date */
/* file size 
#include 
int main(void)
{

struct ffblk ffblk;
int done;
printf("Directory listing of *.*\n");
done = findfirst(I*.*",&ffblk,O);
while (!done) {
printf (" %s\n", ffblk. fCname) ;
done = findnext(&ffblk);
return 0;

Program output
Directory listing of * *
FINDFRST.C
FINDFRST.OBJ
FINDFRST.EXE

Chapter 2, The run-time library

173

•

findnext

findnext
Function
Syntax

Remarks

Continues findfirst search.
#include 
int findnext(struct ffblk *ffblk);

findnext is used to fetch subsequent files that match the pathname given in
findfirst. ffblk is the same block filled in by the findfirst call. This block

contains necessary information for continuing the search. One file name
for each call to findnext will be returned until no more files are found in
the directory matching the pathname.
Return value

findnext returns 0 on successfully finding a file matching the search

pathname. When no more files can be found, or if there is some error in the
file name, -1 is returned, and the global variable errno is set to
ENOENT

Path or file name not found

and doserno is set to one of the following:
ENOENT
ENMFILE

Path or file ...
No more files

See also

findfirst

Example

#inc1 ude 
#include 
int main(void)
{

struct ffblk ffblk;
int done;
printf ("Directory listing of *. *\n");
done = findfirst("*.*",&ffblk,O);
while (!done) {
printf (" %s\n", ffblk. fCname);
done = findnext(&ffblk);
return 0;

174

Borland C++ Library Reference

findnext

Program output
Directory listing of * *
FINDFRST.C
FINDFRST.OBJ
FINDFRST.EXE

floodfill
Function
Syntax

Remarks

Flood-fills a bounded region.
#include 
void far floodfill(int x, int y, int border);

flood fill fills an enclosed area oil bitmap devices. (x,y) is a "seed point"
within the enclosed area to be filled. The area bounded by the color border
is flooded with the current fill pattern and fill color. If the seed point is
within an enclosed area, the inside will be filled. If the seed is outside the
enclosed area, the exterior will be filled.

Use fillpoly instead of flood fill whenever possible so that you can maintain
code compatibility with future versions.
..
Return value

floodfill does not work with the IBM-8514 driver.

If an error occurs while flooding a region, graphresult returns a value of

-7.
See also

drawpoly, fillpoly, graphresult, setcolor, setfillstyle

Example

#include
#include
#include
#include






int main(void)
{

1* request autodetection *1
int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;
1* initialize graphics and local variables *1
initgraph(&gdriver, &gmode, 1111);
1* read result of initialization *1

Chapter 2, The run-time library

175

floodfill

errorcode = graphresult();
if (errorcode != grOk) { 1* an error occurred *1
printf("Graphics error: %s\n", grapherrormsg(errorcode));
print f ( "Press any key to halt:");
getch () ;
exit(l);
1* terminate with an error code *1
maxx
maxy

= getmaxx();
= getmaxy();

1* select drawing color *1
setcolor(getmaxcolor()) ;
1* select fill color *1
setfillstyle(SOLID_FILL, getmaxcolor());
1* draw a border around the screen *1
rectangle(O, 0, max x , maxy);
1* draw some circles *1
circle(maxx I 3, maxy 12, 50);
circle(maxx I 2, 20, 100);
circle (maxx-20, maxy-50, 75);
circle(20, maxy-20, 25);
1* wait for a key *1
getch() ;
1* fill in bounded region *1
floodfill(2, 2, getmaxcolor());

1* clean up *1
getch() ;
closegraph() ;
return 0;

floor, floorl
Function
Syntax

Rounds down.
#include 
double floor(double x);
long double floorl(long double x);
DOS

floor
floorl

176

•
•

UNIX

•

Windows

ANSI C

•
•

•

C++ only

Borland C++ Library Reference

floor, floorl

Remarks

floor finds the largest integer not greater than x.
floorl is the long double version; it takes a long double argument and

returns a long double result.
Return value

floor returns the integer found as a double.
floorl returns the integer found as a long double.

See also

ceil, fmod

Example

#include 
#include 

I

int main (void)
{

double number

= 123.54,

down, up;

down = floor (number) ;
up = ceil(number);
printf ("original number
%10 .2lf\n", number);
printf(IInumber rounded down %10.2lf\n", down);
printf(IInumber rounded up
%10.2lf\n", up);
return 0;

flushall
Function
Syntax

Remarks

Flushes all streams.
#include 
int flushall(void);

flushall clears all buffers associated with open input streams, and writes

all buffers associated with open output streams to their respective files.
Any read operation following flushall reads new data into the buffers
from the input files.
Streams stay open after flushall executes.
Return value

flushall returns an integer, the number of open input and output streams.

See also

fclose, fcloseall, fflush

Example

#include 
int main(void)

Chapter 2, The run-time library

177

flushall

FILE *streamj
/* create a file */
stream = fopen("DUMMY.FIL",

"w")j

/* flush all open streams */
printf("%d streams were flushed.\n", flushall())j
/* close the file */
fclose (stream) j
return OJ

_fmemccpy
See memccpy.

-

fmemchr
See memchr.

_fmemcmp
See memcmp.

_fmemcpy
See memcpy.

_fmemicmp
See memicmp.

_fmemset
See memset.

178

Borland C++ Library Reference

floor, floorl

Remarks

floor finds the largest integer not greater than x.
floorl is the long double version; it takes a long double argument and

returns a long double result.
Return value

floor returns the integer found as a double.
floorl returns the integer found as a long double.
I

See also

ceil, fmod

Example

#include 
#include 

I

int main(void)
{

double number

= 123.54,

down, up;

down = floor (number) ;
up = ceil (number) ;
printf ("original number
%10 .2lf\n", number);
printf ("number rounded down %10. 2lf\n", down);
printf("number rounded up
%10.2lf\n", up);
return 0;

flushall
Function
Syntax

Remarks

Flushes all streams.
#include 
int flushall(void);

flush all clears all buffers associated with open input streams, and writes

all buffers associated with open output streams to their respective files.
Any read operation following flushall reads new data into the buffers
from the input files.
Streams stay open after flushall executes.
Return value

flushall returns an integer, the number of open input and output streams.

See also

fclose, fcloseall, fflush

Example

#include 
int main(void)

Chapter 2, The run-time library

177

flusholl

FILE *stream;
/* create a file */
stream = fopen("DUMMY.FIL", "w");
/* flush all open streams */
printf("%d streams were flushed.\n", flushall());
/* close the file */
fc10se (stream) ;
return 0;

_fmemccpy
See memccpy.

-

fmemchr
See memchr.

_fmemcmp
See memcmp.

_fmemcpy
See memcpy.

_fmemicmp
See memicmp.

-

fmemset
See memset.

178

Borland C++ Library Reference

fmod, fmodl

fmod, fmodl
Function
Syntax

Calculates x modulo y, the remainder of x/yo
#include 
double fmod(double x, double y);
long double fmodlOong double x, long double y);

(mod
(modI

DOS

UNIX

•
•

•

Windows

ANSI C

•
•

•

C++ only

Remarks

fmod calculates x modulo y (the remainder I, where x = ay + I for some
integer a and 0 '5:1 < y).
fmodl is the long double version; it takes long double arguments and
returns a long double result.

Return value

fmod and fmodl return the remainder I, where x = ay + f (as described).
Where y = 0, fmod and fmodl return o.

See also

ceil, floor, modf

Example

#include 
#include 
int main(void)
{

double x = 5.0, y = 2.0;
double result;
result = fmod(x,y);
printf("The remainder of (%If / %If) is %If\n", x, y, result);
return 0;

Program output
The remainder of 5.0 / 2.0 is 1.0.

fnmerge
Function
Syntax

Builds a path from component parts.
#include 

Chapter 2, The run-time library

179

fnmerge

void fnmerge(char *path, canst char *drive, canst char *dir,
canst char *name, canst char *ext);

Remarks

fnmerge makes a path name from its components. The new path name is
X:\DIR\SUBDIR\NAME.EXT

where

drive
dir
name
ext

X:
\DIR\SUBDIR\
NAME
.EXT

fnmerge assumes there is enough space in path for the constructed path
name. The maximum constructed length is MAXPA TH. MAXPATH is
defined in dir.h.
fnmerge and fnsplit are invertible; if you split a given path with fnsplit,
then merge the resultant components with fnmerge, you end up with path.

Return value

None.

See also

fnsplit

Example

#include 
#include 
#include 
int main(void)
{

char s(MAXPATH];
char drive (MAXDRIVE] ;
char dir[MAXDIR];
char file(MAXFILE];
char ext[MAXEXT];
getcwd(s,MAXPATH);
strcat(s, """);
fnsplit(s,drive,dir,file,ext);
strcpy (file, "DATA") ;
strcpy(ext,".TXT") ;
fnrnerge(s,drive,dir,file,ext);
puts(s);
return 0;

180

/* get current working directory */
/* append a trailing' character */
/* split the string to separate elems */

/* merge everything into one string */
/* display resulting string */

Borland C++ Library Reference

fnsplit

fnsplit
Function
Syntax

Remarks

Splits a full path name into its components.

I

#include 
int fnsplit(const char *path, char *drive, char *dir, char *name, char *ext);

fnsplit takes a file's full path name (path) as a string in the form

X: \DIR\ 5 UBDIR\NAME. EXT

and splits path into its four components. It then stores those components
in the strings pointed to by drive, dir, name, and ext. (All five components
must be passed, but any of them can be a null, which means the corresponding component will be parsed but not stored.)
The maximum sizes for these strings are given by the constants
MAXDRIVE, MAXDIR, MAX PATH, MAXFILE, and MAXEXT (defined in dir.h),
and each size includes space for the null-terminator.
Constant

Max

String
(80)

MAXPATH
MAXDRIVE
MAXDIR

(66)

MAXFILE
MAXEXT

(9)
(5)

(3)

path
drive; includes colon (:)
dir; includes leading and trailing
backslashes (\)

name
ext; includes leading dot (.)

fnsplit assumes that there is enough space to store each non-null

component.
When fnsplit splits path, it treats the punctuation as follows:

• drive includes the colon (C:, A:, and so on).
II dir includes the leading and trailing backslashes (\BC\include \,
\source \, and so on).
II name includes the file name.
II ext includes the dot preceding the extension ec, .EXE, and so on).
fnmerge and fnsplit are invertible; if you split a given path with fnsplit,
then merge the resultant components with fnmerge, you end up with path.

Chapter 2, The run-time library

181

fnsplit

Return value

fnsplit returns an integer (composed of five flags, defined in dir.h)

indicating which of the full path name components were present in path;
these flags and the components they represent are
EXTENSION
FILENAME
DIRECTORY
DRIVE
WILDCARDS
See also

fnmerge

Example

#inc1ude 
#include 
#include 

An extension
A file name
A directory (and possibly subdirectories)
A drive specification (see dir.h)
Wildcards (* or ?)

int main (void)
{

char *Si
char drive [MAXDRIVE] i
char dir[MAXDIR]i
char file[MAXFILE]i
char ext[MAXEXT]i
int flags i
/* get comspec environment parameter */
s = getenv("COMSPEC") i
flags = fnsplit(s,drive,dir,file,ext)i
printf ("Command processor info: \n") i
if(flags & DRIVE)
printf("\tdrive: %s\n",drive) i
if(flags & DIRECTORY)
printf("\tdirectory: %s\n",dir)i
if (flags & FILENAME) ,
printf("\tfile: %s\n",file)i
if(flags & EXTENSION)
printf("\textension: %s\n",ext)i
return Oi

fopen
Function
Syntax

182

Opens a stream.
#include 
FILE *fopen(const char *filename, const char *mode);

Borland C++ Library Reference

fopen

Remarks

fopen opens the file named by filename and associates a stream with it.
fopen returns a pointer to be used to identify the stream in subsequent

operations.
The mode string used in calls to fopen is one of the following values:
Mode

Description

r

Open for reading only.

w

Create for writing. If a file by that name already exists, it will be
overwritten.

a

Append; open for writing at end of file, or create for writing if the file
does not exist.

r+

Open an existing file for update (reading and writing).

w+

Create a new file for update (reading and writing). If a file by that name
already exists, it will be overwritten.

a+

Open for append; open for update at the end of the file, or create if the
file does not exist.

To specify that a given file is being opened or created in text mode,
append a t to the mode string (rt, w+t, and so on). Similarly, to specify
binary mode, append a b to the mode string (wb, a+b, and so on). fopen also
allows the t or b to be inserted between the letter and the + character in
the mode string; for example, rt+ is equivalent to r+t.
If a t or b is not given in the mode string, the mode is governed by the
global variable Jmode. If _fmode is set to O_BINARY, files are opened in
binary mode. If Jmode is set to O_TEXT, they are opened in text mode.
These 0_ ... constants are defined in fcntl.h.
When a file is opened for update, both input and output can be done on
the resulting stream. However, output cannot be followed directly by
input without an intervening fseek or rewind, and input cannot be
directly followed by output without an intervening fseek, rewind, or an
input that encounters end-of-file.
Return value

On successful completion, fopen returns a pointer to the newly opened
stream. In the event of error, it returns null.

See also

creat, dup, fclose, fdopen ferror, _fmode (global variable), fread, freopen,
fseek, fwrite, open, rewind, setbuf, setmode

Example

/* program to create backup of the AUTOEXEC.BAT file */

Chapter 2, The run-time library

183

topen

#include 
int main (void)
{

FILE *in, *out;
= fopen("\\AUTOEXEC.BAT", "rt")) == NULL)
fprintf(stderr, "Cannot open input file.\n");
return 1;

if ((in

if ((out = fopen("\\AUTOEXEC.BAK", "wt")) == NULL)
fprintf(stderr, "Cannot open output file.\n");
return 1;
while (!feof(in))
fputc(fgetc(in), out);
fclose (in);
fclose (out);
return 0;

FP_OFF, FP_SEG
Function
Syntax

Remarks

Gets a far address offset or segment.
#include 
unsigned FP_OFF(void far *p);
unsigned FP_SEG(void far *p);

The FP_OFF macro can be used to get or set the offset of the far pointer *p.
FP_SEG is a macro that gets or sets the segment value of the far pointer

*p.
Return value

FP_OFF returns an unsigned integer value representing an offset value.
FP_SEG returns an unsigned integer representing a segment value.

See also
Example

MK_FP, movedata, segread
#include 
#include 
#include 
/* FP_OFF */

int fp_off(void)

184

Borland C++ Library Reference

FP_OFF, FP_SEG

char *str = "fpoff.c";
printf("The offset of this file name in memory\
is: %Fp\n", FP_OFF(str));

,.

return 0;
1* FP_SEG *1

int fp_seg(void)

I

{

char *filename = "fpseg.c";
printf("The segment of this file in memory\
is: %Fp\n", FP_SEG(filename));
return (0) ;
1* MK_FP *1

int main(void)
{

int gd, gm, i;
unsigned int far *screen;
detectgraph(&gd, &gm);
if (gd == HERCMONO)
screen = (unsigned int *) MK_FP(OxBOOO, 0);
else
screen = (unsigned int *) MK_FP(OxB800, 0);
for (i=O; i<26; i++)
screen[il = Ox0700 + ('a' + i);
return 0;

_fpreset
Function
Syntax

Reinitializes floating-point math package.
#include 
void _fpreset(void);

Chapter 2, The run-time library

185

_'preset

Remarks

..

_fpreset reinitializes the floating-point math package. This function is
usually used in conjunction with system or the exec ... or spawn ...
functions.
Under ~OS, if an 80x87 coprocessor is used in a program, a child process
(executed by system or by an exec ... or spawn ... function) might alter the
parent process's floating-point state.
If you use an 80x87, take the following precautions:

Do not call system or an exec ... or spawn ... function while a floatingpoint expression is being evaluated .
• Call_fpreset to reset the floating-point state after using system, exec ... ,
or spawn ... if there is any chance that the child process performed a
floating-point operation with the 80x87.

II

Return value

None.

See also

_clear87, _control87, exec ... , spawn ... , _status87, system

Example

#inc1ude
#include
#include
#include
#include
#include








#ifdef __ cplusplus
typedef void (*fptr) (int);
#else
typedef void (*fptr) ();
#endif
jmp_buf reenter;
/* define a handler for trapping floating

point errors */
void float_trap(int sig)
{

printf("Trapping floating point error, ");
printf("signal is %d\n",sig);
printf("Press a key to continue\n");
getch() ;
/* Reset the 8087 chip or emulator to clear any extraneous garbage. */
_fpreset() ;
/* return to the problem spot */
longjmp(reenter, -1);
int main (void)

186

Borland C++ Library Reference

_'preset

float one

= 3.14,

two

= 0.0;

/* Install signal handler for floating point exception. */
signal (SIGFPE, (fptr) float_trap);
printf("Generating a math error,");
printf("press a key\n");
getch () ;
if (setjmp(reenter) == 0)
one /= two;
printf("Returned from signal trap\n");
return 0;

fprintf
Function
Syntax

Remarks
See prinff for details
on format specifiers.

Return value

Writes formatted output to a stream.
#include 
int fprintf(FILE *stream, const char *formatL argument, ... J);

fprintf accepts a series of arguments, applies to each a format specifier
contained in the format string pointed to by format, and outputs the
formatted data to a stream. There must be the same number of format
specifiers as arguments.
fprintf returns the number of bytes output. In the event of error, it returns

EOF.
See also

cprintf, fscanf, printf, putc, sprintf

Example

#include 
int main(void)
{

FILE *stream;
int i = 100;
char c = 'C';
float f = 1.234;
stream = fopen("DUMMY.FIL", "w+");
/* open a file for update */
fprintf(stream, "%d %c %f", i, c, f); /* write some data to the file */
fclose(stream);
/* close the file */
return 0;

Chapter 2, The run-time library

187

fpute

fputc
Function

Puts a character on a stream.

Syntax

#include 
int fputc(int c, FILE *stream);
c++ only

Remarks
Return value

fputc outputs character c to the named stream.

On success, fputc returns the character c. On error, it returns EOF.

See also

fgetc, putc

Example

#include 
int main(void)
{

char msg[] = "Hello world";
int i = 0;
while (msg[i]) {
fputc(msg[i], stdout);
itt;

return 0;

fputchar
Function
Syntax

Outputs a character on stdout.
#include 
int fputchar(int c);

I

Il
Remarks
Return value

188

DOS

•

UNIX

Windows

I

•

I

•

ANSI C

I C++

only

I

fputchar outputs character c to stdout. fputchar(c) is the same as
fputc(c, stdout).

On success, fputchar returns the character c. On error, it returns EOF.

See also

fgetchar, putchar

Example

#include 

Borland C++ Library Reference

fputchcr

int main(void)
(

char msg[] = "This is a test\n";
int i = 0;
while (msg[i]) {
fputchar(msg[i]) ;
itt;

•

return 0;

fputs
Function
Syntax

Remarks

Outputs a string on a stream.
#include 
int fputs(const char *s, FILE *stream);
I

DOS

I

UNIX

I

II

•

I

•

I

Windows

I

ANSI C

C++ only

I

II
II

fputs copies the null-terminated string s to the given output stream; it

does not append a newline character, and the terminating null character is
not copied.
Return value

On successful completion, fputs returns a non-negative value. Otherwise,
it returns a value of EOF.

See also

fgets, gets, puts

Example

#include 
int main(void)
{

/* write a string to standard output */
fputs("Hello world\n", stdout);
return 0;

fread
Function
Syntax

Reads data from a stream.
#include 
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);

Chapter 2, The run-time library

189

fread

Remarks

tread reads n items of data, each of length size bytes, from the given input

stream into a block pointed to by ptr.
The total number of bytes read is (n x size).
Return value

On successful completion, tread returns the number of items (not bytes)
actually read. It returns a short count (possibly 0) on end-of-file or error.

See also

topen, twrite, printf, read

Example

#include 
#include 
int main(void)
{

FILE *stream;
char msg[] = "this is a test";
char buf [20];
if ((stream = fopen("DUMMY.FIL", "w+")) == NULL) {
fprintf(stderr, "Cannot open output file.\n");
return 1;
/* write some data to the file */
fwrite(msg, strlen(msg);l, 1, stream);
/* seek to the beginning of the file */
fseek(stream, SEEK_SET, 0);
/* read the data and display it */
fread(buf, strlen(msg)+l, 1, stream);
printf("%s\n", buf);
fclose (stream) ;
return 0;

free

190

Function

Frees allocated block.

Syntax

#include 
void free(void *block);

Borland C++ Library Reference

free

Remarks
Return value

free deallocates a memory block allocated by a previous call to calloc,
malloc, or realloc.

None.

See also

calloc, freemem, malloc, realloc, strdup

Example

#include 
#include 
#include 
int main (void)
{

char *str;
/* allocate memory for string */
str = (char *) malloc(lO);
/* copy "Hello" to string */
strcpy(str, "Hello");
/* display string */
printf("String is %s\n", str);
/* free memory */
free (str) ;
return 0;

freemem, _dos_freemem
Function
Syntax

Remarks

Return value

Frees a previously allocated DOS memory block.
#include 
int freemem(unsigned segx);
unsigned _dos _freemem (unsigned segx);

freemem frees a memory block allocated by a previous call to allocmem.
_dos_freemem frees a memory block allocated by a previous call to
_dos_allocmem. segx is the segment address of that block.
freemem and _dos_freemem return

a on success.

In the event of error, freemem returns -1 and sets errno.

Chapter 2, The run-time library

191

freemem, _dos_freemem

In the event of error, _dos_freemem returns the DOS error code and sets

errno.
In the event of error, these functions set global variable errno to
ENOMEM

Insufficient memory

See also

allocmem, _dos_allocmem, free

Example

#include 
#include 
#include 
int main (void) /* Example for freemem. */
{

unsigned int size, segp;
int stat;
size
64;
/* allocmem requests blocks in 16 byte chunks,
64 of these is 1024 bytes of memory */
stat allocmem(size, &segp);
if (stat == -1)
printf("Allocated memory at segment: %x\n", segp);
else
printf("Failed: maximum number of paragraphs available is %u\n", stat);
f reemem (segp) ;
return 0;

Example 2

#incl ude 
#include 
int main(void)

/* Example for _dos_freemem. */

{

unsigned int size, segp, err, maxb;
size = 64; /* (64 x 16) = 1024 bytes */
err = _dos_allocmem(size, &segp);
if (err == 0)
printf ("Allocated memory at segment: %x\n", segp);
else {
perror("Unable to allocate block");
printf("Maximum no. of paragraphs available is %u\n", segp);
return 1;
if (_dos_setblock(size * 2, segp, &maxb) == 0)
printf("Expanded memory block at segment: %X\n", segp);
else {
perror ("Unable to expand block");
printf("Maximum no. of paragraphs available is %u\n", maxb);
_dos_freemem(segp);

192

Borland C++ Library Reference

freemem, _dos_freemem

return 0;

freopen
Function
Syntax

Remarks

II

Associates a new file with an open stream.
#include 
FILE *freopen(const char *filename, canst char *mode, FILE *stream);

freopen substitutes the named file in place of the open stream. It closes
stream, regardless of whether the open succeeds. freopen is useful for

changing the file attached to stdin, stdout, or stderr.
The mode string used in calls to fopen is one of the following values:
r

Open for reading only.

w

Create for writing.

a

Appen,d; open for writing at end-of-file, or create for writing if the
file does not exist.

r+

Open an existing file for update (reading and writing).

w+

Create a new file for update.

a+

Open for append; open (or create if the file does not exist) for
update at the end of the file.

To specify that a given file is being opened or created in text mode,
append a t to the mode string (rt, w+t, and so on); similarly, to specify
binary mode, append a b to the mode string (wb, a+b, and so on).
If a t or b is not given in the mode string, the mode is governed by the
global variable Jmode. If _fmode is set to a_BINARY, files are opened in
binary mode. If Jmode is set to a_TEXT, they are opened in text mode.
These 0_ ... constants are defined in fcntl.h.

When a file is opened for update, both input and output can be done on
the resulting stream. However, output cannot be directly followed by
input without an intervening fseek or rewind, and input cannot be
directly followed by output without an intervening fseek, rewind, or an
input that encounters end-of-file.

Chapter 2, The run-time library

193

freopen

Return value

On successful completion, freopen returns the argument stream. In the
event of error, it returns null.

See also

fclose, fdopen, fopen, open, setmode

Example

#include 
int main (void)
{

/* redirect standard output to a file */
if (freopen("OUTPUT.FIL", Ow", stdout) == NULL)
fprintf(stderr" "error redirecting stdout\n");

/* this output will go to a file */
printf("This will go into a file.");
/* close the standard output stream */
fclose (stdout) ;
return 0;

frexp, frexpl
Function
Syntax

Splits a number into mantissa and exponent.
#include 
double frexp(double x, int *exponent);
long double frexplOong double x, int *exponent);
DOS

UNIX

frexp

•

•

frexpl

•

Remarks

Return value

Windows

ANSI C

•
•

•

C++ only

frexp calculates the mantissa m (a double greater than or equal to 0.5 and
less than 1) and the integer value n, such that x (the original double value)
equals m x 2n. frexp stores n in the integer that exponent points to. frexpl is
the long double version; it takes a long double argument for x and returns
a long double result.
frexp and frexpl return the mantissa m.

Error handling for these routines can be modified through the functions
matherr and _matherrl.

194

See also

exp,ldexp

Example

#include 
#include 

Borland C++ Library Reference

frexp, frexpl

int main(void)
{

double mantissa, number = 8.0;
int exponent;
mantissa = frexp(number, &exponent);
printf("The number %If is %If times two to the power of %d\n", number,
mantissa, exponent);
return 0;

fsconf
Function
Syntax

Remarks
See scanf for details
on format specifiers.

Scans and formats input from a stream.
#include 
int fscanf(FILE *stream, const char *formatL address, ... ]);

fscanf scans a series of input fields, one character at a time, reading from a

stream. Then each field is formatted according to a format specifier passed
to fscanf in the format string pointed to by format. Finally, fscanf stores
the formatted input at an address passed to it as an argument following
format. The number of format specifiers and addresses must be the same
as the number of input fields.
fscanf can stop scanning a particular field before it reaches the normal

end-of-field character (whitespace), or it can terminate entirely for a
number of reasons. See scanf for a discussion of possible causes.
Return value

fscanf returns the number of input fields successfully scanned, converted,

and stored; the return value does not include scanned fields that were not
stored.
If fscanf attempts to read at end-of-file, the return value is EOF. If no
fields were stored, the return value is O.
See also

atof, cscanf, fprintf, printf, scanf, sscanf, vfscanf, vscanf, vsscanf

Example

#include 
#include 
int main(void)
{

int i;
printf("Input an integer: ");

Chapter 2, The run-time library

195

fscant

1* read an integer from the standard input stream *1
if (fscanf(stdin, "%d", &i))
printf("The integer read was: %i\n", i);
else {
fprintf(stderr, "Error reading an integer from stdin.\n");
exit(l) ;

return 0;

fseek
Function
Syntax

Repositions a file pointer on a stream.
#include 
int fseek(FILE *stream, long offset, int whence);
Wi ndows

Remarks

ANS I C

fseek sets the file pointer associated with stream to a new position that is
offset bytes from the file location given by whence. For text mode streams,
offset should be or a value returned by ftell.

°

whence must be one of the values 0, 1, or 2, which represent three symbolic
constants (defined in stdio.h) as follows:
File location

whence

SEEK_SET
SEEK_CUR
SEEK_END

(0)

(1)

(2)

File beginning
Current file pointer position
End-of-file

fseek discards any character pushed back using ungetc.
fseek is used with stream I/O; for file handle I/O, use Iseek.

After fseek, the next operation on an update file can be either input or
output.
Return value

fseek returns

failure.
..

196

°if the pointer is successfully moved and a nonzero on

fseek can return a zero, indicating that the pointer has been moved
successfully, when in fact it has not been. This is because DOS, which
actually resets the pointer, does not verify the setting. fseek returns an
error code only on an unopened file or device.

Borland C++ Library Reference

fseek

See also

fgetpos, fopen, fsetpos, ftell, Iseek, rewind, setbuf, tell

Example

#include 
long filesize(FILE *stream);
int main(void)
{

I

•

FILE *stream;
stream = fopen ( "MYFILE. TXT", "Wt");
fprintf (stream, "This is a test");
printf ("Filesize of MYFILE. TXT is %ld bytes\n", filesize (stream) ) ;
fclose (stream) ;
return 0;
long filesize(FILE *stream) {
long curpos, length;
/* save the current location in the file */
curpos = ftell(stream);
/* seek to the end of the file */
fseek(stream, OL, SEEK_END);
/* get the current offset into the file */
length = ftell(stream);
/* restore saved cursor position */
fseek(stream, curpos, SEEK_SET);
return length;

fsetpos
Function
Syntax

Remarks

Positions the file pointer of a stream.
#include 
int fsetpos(FILE *stream, const fpos_t *pos);

fsetpos sets the file pointer associated with stream to a new position. The
new position is the value obtained by a previous call to fgetpos on that
stream. It also clears the end-of-file indicator on the file that stream points
to and undoes any effects of ungetc on that file. After a call to fsetpos, the
next operation on the file can be input or output.

Chapter 2, The run-time library

197

fsetpos

Return value

On success, fsetpos returns O. On failure, it returns a nonzero value and
also sets the global variable errno to a nonzero value.

See also

fgetpos, fseek, ftell

Example

#include 
#include 
void showpos(FILE *stream);
int main(void)
{

FILE *stream;
fpos_t filepos;
/* open a file for update */
stream = fopen ( "DUMMY. FIL", "Wt");
/* save the file pointer position */
fgetpos(stream, &filepos);
/* write some data to the file */
fprintf(stream, "This is a test");
/* show the current file position */
showpos (stream) ;
/* set a new file position and display it */
if (fsetpos(stream, &filepos) == 0)
showpos (stream) ;
else {
fprintf(stderr, "Error setting file pointer.\n");
exit(l);
/* close the file */
fclose (st ream) ;
return 0;
void showpos(FILE *stream) {
fpos_t pos;
/* display the current file pointer position of a stream */
fgetpos(stream, &pos);
printf("File position: %ld\n", pos);

_fsopen
Function

198

Opens a stream with file sharing.

Borland C++ Library Reference

_fsopen

Syntax

#include 
#include 
FILE *_fsopen(const char *filename, const char *mode, int shflg);
DOS

Remarks

_fsopen opens the file named by filename and associates a stream with it.
_fsopen returns a pointer to be used to identify the stream in subsequent

operations.
The mode string used in calls to _fsopen is one of the following values:
Mode Description

r
w

Open for reading only.

a

Append; open for writing at end of file, or create for writing if the file
does not exist.

r+

Open an existing file for update (reading and writing).

w+

Create a new file for update (reading and writing). If a file by that name
already exists, it will be overwritten.

a+

Open for append; open for update at the end of the file, or create if the
file does not exist.

Create for writing. If a file by that name already exists, it will be
overwritten.

To specify that a given file is being opened or created in text mode,
append a t to the mode string (rt, w+t, and so on). Similarly, to specify
binary mode, append a b to the mode string (wb, a+b, and so on). _fsopen
also allows the t or b to be inserted between the letter and the + character
in the mode string; for example, rt+ is equivalent to r+t.
If a t or b is not given in the mode string, the mode is governed by the
global variable Jmode. If _fmode is set to a_BINARY, files are opened in
binary mode. If Jmode is set to a_TEXT, they are opened in text mode.
These
constants are defined in fcntl.h.

a_...

When a file is opened for update, both input and output can be done on
the resulting stream. However, output cannot be followed directly by
input without an intervening fseek or rewind, and input cannot be
directly followed by output without an intervening fseek, rewind, or an
input that encounters end-of-file.

Chapter 2, The run-time library

199

_fsopen

shflag specifies the type of file-sharing allowed on the file filename. The
file-sharing flags are ignored if the DOS SHARE command has not been
run. Symbolic constants for shflag are defined in share.h.
Value of shflag

What it does

SH COM PAT
SH-DENYRW
SH-DENYWR
SH-DENYRD
SH-DENYNONE
SH=DENYNO

Sets compatibility mode
Denies read/write access
Denies write access
Denies read access
Permits read/write access
Permits read/write access

Return value

On successful completion, _fsopen returns a pointer to the newly opened
stream. In the event of error, it returns null.

See also

creat, _dos_open, dup, fclose, fdopen, ferror, Jmode (global variable),
fopen, fread, freopen, fseek, fwrite, open, rewind, setbuf, setmode, sopen

Example

#include
#include
#include
#include

do.h>




int main(void)
{

FILE *f;

int status;
f = _fsopen("c:\\test.$$$", "r", SH_DENYNO);
if (f == NULL) {

printf("_fsopen failed\n");
exit (1) ;
status = access("c:\\test.$$$", 6);
if (status == 0)
printE("read/write access allowed\n");
else
printf("read/write access not allowed\n");
fclose (E);
return 0;

fstat, stat
Function
Syntax

200

Gets open file information.
#include 
int fstat(int handle, struct stat *statbuf>;

Borland C++ Library Reference

fstat, stat

int stat(char *path, struct stat *statbuf);

Remarks

fstat stores information in the stat structure about the open file or

directory associated with handle.
stat stores information about a given file or directory in the stat structure.

statbuf points to the stat structure (defined in sys \stat.h). That structure
contains the following fields:

st_mode·

Bit mask giving information about the open file's mode

st_dev

Drive number of disk containing the file, or file handle if the
file is on a device

st_rdev

Same as st_dev

st_nlink

Set to the integer constant 1

st_size

Size of the open file in bytes

st_atime

Most recent time the open file was modified

st_mtime Same as st_atime
st_ctime

Same as st_atime

The stat structure contains three more fields not mentioned here. They
contain values that are not meaningful under DOS.
The bit mask that gives information about the mode of the open file
includes the following bits:
One of the following bits will be set
S_IFCHR
S_IFREG

If handle refers to a device.
If an ordinary file is referred to by handle.

One or both of the following bits will be set
S_IWRITE
S_IREAD

If user has permission to write to file.
If user has permission to read to file.

The bit mask also includes the read/write bits; these are set according to
the file's permission mode.
Return value

fstat and stat return 0 if they successfully retrieved the information about

the open file. On error (failure to get the information), these functions
return -1 and set the global variable errno to

Chapter 2, The run-time library·

201

fstat, stat

EBADF
See also

access, chmod

Example

#include
#include
#include
#include
#include

Bad file handle







struct stat statbufi
void pstat(void)
{

if (statbuf.st_mode
printf("File is
if (statbuf.st_mode
printf("File is
if (statbuf.st_mode
printf("File is
if (statbuf.st_ffiode
printf("File is
if (statbuf.st_mode
printf ("File is

& S_IWRITE)
writable\n") i
& S_IREAD)
readable\n")i
& S_IFREG)
a regular file\n")i
& S_IFCHR)
a character device\n")i
& S_IFDIR)
a directory\n") i

void main(int argc, char **argv) {
char *infilenamei
int infilei
if (argc != 2) {
printf("Usage: fstatest filename\n")i
exit (1) i
infilename = argv[11i
if ((infile = open(infilename,O_RDONLY)) == -1)
perror("Unable to open file for reading")i
else {
if (fstat(infile,&statbuf) != 0)
perror ("Unable to fstat") i
exit (1) i
close(infile) i
printf("Results of fstat:\n")i
pstat()i
if (stat (infilename,&statbuf)
perror("Unable to stat")i
else {

!=

0)

\

202

Borland C++ Library Reference

fstat, stat

printf("Results of stat:\n");
pstat() ;
exit (0);

See strcat, strchr, strcspn, strdup, stricmp, strlen, strlwr, strncat,
strncmp, strncpy, strnicmp, strnset, strpbrk, strrchr, strrev, strset,
strspn, strstr, strtok, and strupr for descriptions of the far versions of each
of these functions.

fie II
Function
Syntax

Remarks

Returns the current file pointer.
#include 
long int ftell(FILE *stream);

ftell returns the current file pointer for stream. The offset is measured in
bytes from the beginning of the file (if the file is binary).

The value returned by ftell can be used in a subsequent call to fseek.
Return value

ftell returns the current file pointer position on success. It returns -1 L on

error and sets the global variable errno to a positive value.
See also

fgetpos, fseek, fsetpos, Iseek, rewind, tell

Example

#include 
int main (void)
{

FILE *stream;
stream = fopen("MYFILE.TXT", "w+");
fprintf(stream, "This is a test");
printf ("The file pointer is at byte %ld\n", ftell (stream));
fclose (stream) ;
return 0;

Chapter 2, The run-time library

203

ftime

ftime
Function
Syntax

Remarks

Stores current time in timeb structure.
#inc1ude 
void ftime(struct timeb *buf)

On UNIX platforms, ftime is only available on System V systems.
ftime determines the current time and fills in the fields in the timeb
structure pointed to by buf. The timeb structure contains four fields: time,

millitm, timezone, and dstflag:
struct timeb {
long time i
short mi 11 i tm i
short timezone
short dst flag

i

i

}i
II

time provides the time in seconds since 00:00:00 Greenwich mean time

(GMT), January 1, 1970.
!I millitm is the fractional part of a second in milliseconds.
&I timezone is the difference in minutes between GMT and the local time.
This value is computed going west from GMT. ftime gets this field from
the global variable timezone, which is set by tzset.
II dstflag is used to indicate whether daylight saving time will be taken
into account during time calculations.
..
Return value

ftime calls tzset. Therefore, it isn't necessary to call tzset explicitly when
you use ftime.

None.

See also

asctime, ctime, gmtime, localtime, stime, time, tzset

Example

#include
#include
#include
#include






/* pacific standard & daylight savings */
char *tzstr = "TZ=PST8PDT"i
int main (void)

204

Borland C++ Library Reference

ftime

struct timeb t;
putenv (tzstr) ;
tzset();
ftime(&t) ;
printf("Seconds since 1/1/1970 GMT: %ld\n", t.time);
printf(IlThousandths of a second: %d\n", t.millitm);
printf("Difference between local time and GMT: %d\n", t.timezone);
printf(IlDaylight savings in effect (1) not (0): %d\n", t.dstflag);
return 0;

II

_fullpath
Function
Syntax

Remarks

Convert a path name from relative to absolute.
#include 
char * _fullpath(char *buffer, const char *path, int bufIen);

_fullpath converts the relative path name in path to an absolute path name

that is stored in the array of characters pointed to by buffer. The maximum
number of characters that can be stored at buffer is buflen. The function
returns NULL if the buffer isn't big enough to store the absolute path
name, or if the path contains an invalid drive letter.
If buffer is NULL, the _fullpath allocates a buffer of up to _MAX_PATH
characters. This buffer should be freed using free when it is no longer
needed. _MAX_PATH is defined in stdlib.h
Return value

If successful, the _fullpath function returns a pointer to the buffer
containing the absolute path name. Otherwise, it returns NULL.

See also

_makepath, _splitpath

Example

#include 
#include 
void main(int argc, char *argv[])
{

char buf[_MAX_PATH];
for ( ; argc; argvtt, argc--) {
if (_fullpath(buf, argv[O], _MAX_PATH) == NULL)
printf("Unable to obtain full path of %s\n",argv[O]);
else

Chapter 2, The run-time library

205

_fullpath

printf("Full path of %s is %s\n",argv[O],buf);

fwrite
Function
Syntax

Remarks

Writes to a stream.
#include 
size_t fwrite(const void *ptr, size_t size, size_t n, FILE *stream);

n items of data, each of length size bytes, to the given
output file. The data written begins at ptr.

fwrite appends

The total number of bytes written is (n x size).

ptr in the declaratio1:ls is a pointer to any object.
Return value

On successful completion, fwrite returns the number of items (not bytes)
actually written. It returns a short count on error.

See also

fopen, fread

Example

#include 
struct mystruct
{

int i;
char chi
};

int main (void)
{

FILE *stream;
struct mystruct s;
/* open file TEST.$$$ */
= fopen("TEST.$$$", "wb")) == NULL) {
fprintf(stderr, "Cannot open output file.\n");
return 1;

if ((stream

s.i = 0;
s.ch = 'A';
fwrite(&s, sizeof(s), 1, stream); /* write struct s to file */
fclose(stream);
/* close file */

206

Borland C++ Library Reference

fwrite

return 0;

gcvt
Function

Converts floating-point number to a string.

Syntax

#include 
char *gcvt(double value, int ndec, char *buf>;

Remarks

Return value

I

gcvt converts value to a null-terminated ASCII string and stores the string
in buf. It produces ndec significant digits in FORTRAN F format, if
possible; otherwise, it returns the value in the printf E format (ready for
printing). It might suppress trailing zeros.
gcvt returns the address of the string pointed to by buf.

See also

ecvt fcvt, sprintf

Example

#include 
#include 
int main (void)
{

char str[25];
double num;
int sig = 5; /* significant digits */
/* a regular number */
num = 9.876;
gcvt(num, sig, str);
printf("string = %s\n", str);
/* a negative number */
num = -123.4567;
gcvt(num, sig, str);
printf("string = %s\n", str);
/* scientific notation */
num = O.678e5;
gcvt(num, sig, str);
printf("string = %s\n", str);
return(O) ;

Chapter 2, The run-time library

207

geninterrupt

geninterrupt
Function
Syntax

Generates a software interrupt.
#include 
void geninterrupt(int intr_num);
DOS

Remarks

..
Return value

The geninterrupt macro triggers a software trap for the interrupt given by
intr_num. The state of all registers after the call depends on the interrupt
called.
Interrupts can leave registers used by C in unpredictable states.
None.

See also

bdos, bdosptr, disable, enable, getvect, int86, int86x, intdos, intdosx, intr

Example

#include 
#include 
void writechar(char ch);

/* function prototype */

int rnain(void)
{

clrscr ();
gotoxy(80,25);
writechar('*');
getch() ;
return 0;
/* outputs a character at the current cursor position */
/* using the video BIOS to avoid scrolling of the screen */
/* when writing to location (80,25) */
void writechar(char ch)
struct text_info ti;
gettextinfo(&ti);
_AH = 9;

_AL

= ch;

_BH = 0;

_BL

= ti.attribute;

_ex

= 1;

geninterrupt(OxlO) ;

208

/*
/*
/*
/*
/*
/*
/*

grab current text settings */
interrupt OxlO sub-function 9 */
character to be output */
video page */
video attribute */
repetition factor */
output the char */

Borland C++ Library Reference

getarccoords

getarccoords
Function
Syntax

Remarks

Gets coordinates of the last call to arc.
#include 
void far getarccoords(struct arccoordstype far *arccoords);

getarccoords fills in the arccoordstype structure pointed to byarccoords
with information about the last call to arc. The arccoordstype structure is

defined in graphics.h as follows:
struct arccoordstype {
int x, Yi
int xstart, ystart, xend, yendi
}i

The members of this structure are used to specify the center point (x,y),
the starting position (xstart, ystart), and the ending position (xend, yend) of
the arc. These values are useful if you need to make a line meet at the end
of an arc.
Return value

None.

See also

arc, fillellipse, sector

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcodei
struct arccoordstype arcinfoi
int midx, midYi
int stangle = 45, endangle = 270i
char sstr[80l, estr[80li
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "") i
/* read result of initialization */
errorcode = graphresult()i

Chapter 2, The run-time library

209

•

getarccoords

if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */
midx
midy

= getmaxx() / 2;
=

getmaxy() / 2;

/* draw arc and get coordinates */
setcolor(getmaxcolor()) ;
arc (midx, midy, stangle, endangle, 100);
getarccoords(&arcinfo) ;
/* convert arc information into strings */
sprintf(sstr, "*- (%d, %d)", arcinfo.xstart, arcinfo.ystart);
sprintf(estr, "*- (%d, %d)", arcinfo.xend, arcinfo.yend);

/* output the arc information */
outtextxy(arcinfo.xstart, arcinfo.ystart, sstr);
outtextxy(arcinfo.xend, arcinfo.yend, estr);

/ * clean up */
getch();
closegraph ( ) ;
return 0;

getaspectratio
Function
Syntax

Remarks

Retrieves the current graphics mode's aspect ratio.
#include 
void far getaspectratio(int far *xasp, int far *yasp);

The y aspect factor, *yasp, is normalized to 10,000. On all graphics adapters
except the VGA, *xasp (the x aspect factor) is less than *yasp because the
pixels are taller than they are wide. On the VGA, which has "square"
pixels, *xasp equals *yasp. In general, the relationship between *yasp and
*xasp can be stated as

*yasp = 10,000
*xasp <= 10,000

210

Borland C++ Library Reference

getaspectratio

getaspectratio gets the values in *xasp and *yasp.
Return value

None.

See also

arc, circle, ellipse, fillellipse, pieslice, sector, setaspectratio

Example

#include
#include
#include
#include






I

main( )
{

/* request autodetection */

int gdriver = DETECT, gmode, errorcode;
int xasp, yasp, midx, midy;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf ("Graphics error: %s \n", grapherrormsg (errorcode) ) ;
printf("Press any key to halt:");
getch();
exit(l);
/* terminate with an error code */

midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor()) ;
/* get current aspect ratio settings */
getaspectratio(&xasp, &yasp);
/* draw normal circle */
circle(midx, midy, 100);
getch () ;
/* draw wide circle */
cleardevice();
setaspectratio(xasp/2, yasp);
circle (midx, midy, 100);
getch() ;
/* draw narrow circle */
cleardevice();
setaspectratio(xasp, yasp/2);
circle (midx, midy, 100);
/* clean up */

Chapter 2, The run-time library

211

getaspectratio

getch() ;
closegraph ( ) ;
return 0;

getbkcolor
Function
Syntax

Remarks
Return value

Returns the current background color.
#include 
int far getbkcolor(void);

getbkcolor returns the current background color. (See the table under
setbkcolor for details.)
getbkcolor returns the current background color.

See also

getcolor, getmaxcolor, getpalette, setbkcolor

Example

#incl ude
#include
#include
#include
#include







int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int bkcolor, midx, midy;
char bkname[35];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */

midx
midy

212

= getmaxx()
= getmaxy()

2;
2;

Borland C++ Library Reference

getbkcolor

setcolor(getmaxcolor()) ;
/* for centering text on the display */
settextjustify(CENTER_TEXT, CENTER_TEXT);

/* get the current background color */
bkcolor = getbkcolor();
/* convert color value into a string */
itoa(bkcolor, bkname, 10);
strcat(bkname, " is the current background color.");

I

/* display a message */
outtextxy(midx, midy, bkname);
/* clean up */
getch();
closegraph() ;
return 0;

getc
Function
Syntax

Remarks
Return value

Gets character from stream.
#include 
int getc(FILE *stream);

getc is a macro that returns the next character on the given input stream
and increments the stream's file pointer to point to the next character.

On success, getc returns the character read, after converting it to an int
without sign extension. On end-of-file or error, it returns EOF.

See also

fgetc, getch, getchar, getche, gets, putc, putchar, ungetc

Example

#include 
int main(void)
{

char ch;
printf("Input a character:");
/* read a character from the standard input stream */
ch = getc(stdin);
printf ("The character input was: '%c' \n", ch);

Chapter 2, The run-time library

213

getc

return 0;

getcbrk
Function
Syntax

Remarks

Gets control-break setting.
#include 
int getcbrk(void);

getcbrk uses the DOS system call Ox33 to return the current setting of

control-break checking.
Return value

getcbrk returns 0 if control-break checking is off, or 1 if checking is on.

See also

ctrlbrk, setcbrk

Example

#include 
#include 
int main (void)
if (getcbrk())
printf("Cntrl-brk flag is on\n");
else
printf("Cntrl-brk flag is off\n");
return 0;

getch
Function
Syntax

Gets character from keyboard, does not echo to screen.
#include 
int getch(void);
DOS

Remarks
Return value

214

getch reads a single character directly from the keyboard, without
echoing to the screen.
getch returns the character read from the keyboard.

Borland C++ Library Reference

getch

See also

cgets, cscanf, fgetc, getc, getchar, getche, getpass, kbhit, putch, unget ch

Example

#inc1 ude 
#include 
int main(void)
{

int Ci
int extended = Oi
c = getch () i
if (! c)
extended = getch() i
if (extended)
printf("The character is extended\n");
else
printf("The character isn't extended\n")i

I

return 0i

getchar
Function
Syntax

Remarks
Return value

Gets character from stdin.
#include 
int getchar(void);

getchar is a macro that returns the next character on the named input
stream stdin. It is defined to be getc(stdin).

On success, getchar returns the character read, after converting it to an int
without sign extension. On end-of-file or error, it returns EOF.

See also

fgetc, fgetchar, getc, getch, getche, gets, putc, putchar, scanf, ungetc

Example

#include 
int main (void)
{

int Ci
/* Note that get char reads from stdin and is line bufferedi */
/* this means it will not return until you press  */

while ((c = getchar()) != '\n')
printf("%c", C)i

Chapter 2, The run-time library

215

getchar

return 0;

getche
Function
Syntax

Remarks

Gets character from the keyboard, echoes to screen.
#include 
int getche(void);

getche reads a single character from the keyboard and echoes it to the

current text window, using direct video or BIOS.
Return value

getche returns the character read from the keyboard.

See also

cgets, cscanf, fgetc, getc, getch, getchar, kbhit, putch, ungetch

Example

#include 
#include 
int main(void}
{

char Chi .
printf("Input a character:"};
ch = getche(};
printf("\nYou input a '%c'\n", ch};
return 0;

getcolor
Function
Syntax

Returns the current drawing color.
#include 
int far getcolor( void);

I
"Il • I
DOS

Remarks

UNIX

I

Windows

ANSI C

C++ only

I

getcolor returns the current drawing color.

The drawing color is the value to which pixels are set when lines and so
on are drawn. For example, in CGACO mode,the palette contains four

216

Borland C++ Library Reference

getcolor

colors: the background color, light green, light red, and yellow. In this
mode, if getcolor returns 1, the current drawing color is light green.
Return value

getcolor returns the current drawing color.

See also

getbkcolor, getmaxcolor, getpalette, setcolor

Example

#include
#include
#include
#include
#include







I

int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int color, midx, midy;
char colname[351;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(l);
/* terminate with an error code */

midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor()) ;
/* for centering text on the display */
settextjustify(CENTER_TEXT, CENTER_TEXT);
/* get the current drawing color */
color = getcolor();
/* convert color value into a string */
itoa(color, colname, 10);
strcat(colname, " is the current drawing color.");
/* display a message */
outtextxy(midx, midy, colname);

/* clean up * /
getch();
closegraph ( ) ;

Chapter 2, The run-time library

217

getcolor

return 0;

getcurdir
Function
Syntax

Remarks

Gets current directory for specified drive.
#include 
int getcurdir(int drive, char *directory);

getcurdir gets the name of the current working directory for the drive
indicated by drive.

drive specifies a drive number (0 for default, 1 for A, and so on).
directory points to an area of memory of length MAXDIR where the nullterminated directory name will be placed. The name does not contain the
drive specification and does not begin with a backslash.
Return value
See also

getcurdir returns

a on success or -1 in the event of error.

chdir, getcwd, getdisk, mkdir, rmdir

. getcwd
Function
Syntax

Remarks

Gets current working directory.
#include 
char *getcwd(char *buf, int buflen);

getcwd gets the full path name (including the drive) of the current
working directory, up to buflen bytes long and stores it in buf. If the full
path name length (including the null terminator) is longer than buflen
bytes, an error occurs.

If buf is null, a buffer buflen bytes long is allocated for you with malloc.

You can later free the allocated buffer by passing the return value of
getcwd to the function free.

218

Borland C++ Library Reference

getcwd

Return value

getcwd returns the following values:
a If but is not null on input, getcwd returns but on success, null on error.
a If but is null on input, getcwd returns a pointer to the allocated buffer.

In the event of an error return, the global variable errno is set to one of the
following:
ENODEV
ENOMEM
ERANGE

No such device
Not enough core
Result out of range

See also

chdir, getcurdir, _getdcwd, getdisk, mkdir, rmdir

Example

#incl ude 
#include 

I

int main(void)
char buffer [MAXPATH] ;
getcwd(buffer, MAXPATH);
printf("The current directory is: %s\n", buffer);
return 0;

getdate, _dos_getdate, _dos_setdate, setdate
Function
Syntax

Remarks

Gets and sets system date.
#include 
void getdate(struct date *datep);
void _dos_getdate(struct dosdate_t *datep);
void setdate(struct date *datep);
unsigned _dos_setdate(struct dosdate_t *datep);

getdate fills in the date structure (pointed to by datep) with the system's
current date.
setdate sets the system date (month, day, and year) to that in the date
structure pointed to by datep.

The date structure is defined as follows:
struct date {

Chapter 2, The run-time library

219

getdate, _dos_getdate, _dos_setdate, setdate

/* current year */
/* day of the month */
/* month (1 = Jan) */

int da.....Year;
char da_day;
char da_mon;
};

_dos_getdate fills in the dosdate_t structure (pointed to by datep) with the

system's current date.
The dosdate_t structure is defined as follows:
struct dosdate_t
unsigned char
unsigned char
unsigned int
unsigned char

{
day;
month;
year;
dayofweek;

/* 1-31 */

/* 1-12 *1
/* 1980 - 2099 */
/* 0 - 6 (O=Sunday) */

};

Return value

_dos_getdate, getdate, and setdate, do not return a value.

If the date is set successfully, _dos_setdate returns O. Otherwise, it returns
a non-zero value and the global variable errno is set to the following:
EINVAL

Invalid date

See also

ctime, gettime, settime

Example

#incl ude 
#include 
#include 
int main (void)
{

struct dosdate_t reset;
reset.year = 2001;
reset.day = 1;
reset.month = 1;
printf("Setting date to 1/1/2001.\n");
_dos_setdate(&reset);
_dos_getdate(&reset);
printf("The new year is: %d\n", reset.year);
printf("The newday is: %d\n", reset.day);
printf("The new month is: %d\n", reset.month);
return 0;

_getdcwd
Function

220

Gets current directory for specified drive.

Borland C++ Library Reference

_getdcwd

Syntax

#include 
char * _getdcwd(int drive, char *buffer, int buflen);
C++ only

Remarks

_getdcwd gets the full path name of the working directory of the specified

drive (including the drive name), up to buflen bytes long, and stores it in
buffer. If the full path name length (including the null-terminator) is longer
than buflen, an error occurs. The drive is 0 for the default drive, l=A, 2=B,
etc.
If buffer is NULL, _getdcwd will allocate a buffer at least buflen bytes long.
You can later free the allocated buffer by passing the _getdcwd return
value to the free function.
Return value

If successful, _getdcwd returns a pointer to the buffer containing the
current directory for the specified drive. Otherwise it returns NULL, and
sets the global variable errno to one of the following:

ENOMEM
ERANGE

Not enough memory to allocate a buffer (buffer is NULL)
Directory name longer than buflen (buffer is not NULL)

See also

chdir, getcwd, _getdrive, mkdir, rmdir

Example

#include 
#include 
void main()
{

char buf[65li
if (_getdcwd(3, buf, sizeof(buf)) == NULL)
perror("Unable to get current directory of drive C")
else
printf("Current directory of drive C is %s\n",buf) i

i

getdefaultpalette
Function
Syntax

Returns the palette definition structure.
#include 
struct palettetype *far getdefaultpalette(void);

Chapter 2, The run-time library

221

I

•

getdefaultpaleHe

Remarks
Return value

getdefaultpalette finds the palettetype structure that contains the palette
initialized by the driver during initgraph.
getdefaultpalette returns a pointer to the default palette set up by the
current driver when that driver was initialized.

See also

getpalette, initgraph

Example

#inc1ude
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
/* far pointer to palette structure */
struct palettetype far *pal = NULL;
int i;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, 1111);
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */
/* return a pointer to the default palette */
pal = getdefaultpalette();
for (i=O; isize; itt) {
printf("colors[%d] = %d\n", i, pal->colors[i]);
getch () ;
/* clean up */
getch () ;
closegraph();
return 0;

222

Borland C++ Library Reference

getdfree

getdfree
Function
Syntax

Remarks

Gets disk free space.
#include 
void getdfree(unsigned char drive, struct dfree *dtable);

getdfree accepts a drive specifier in drive (0 for default, 1 for A, and so on)
and fills the dfree structure pointed to by dtable with disk attributes.

The dfree structure is defined as follows:
struct dfree {
unsigned df_avail;
unsigned df_total;
unsigned df_bsec;
unsigned df_sclus;

/*
/*
/*
/*

available clusters */
total clusters */
bytes per sector */
sectors per cluster */

};

Return value

getdfree returns no value. In the event of an error, df_sclus in the dfree
structure is set to OxFFFF.

See also

getfat, getfatd

Example

#include 
#include 
#include 
#include 
int main(void)
{

struct dfree free;
long avail;
int drive;
drive = getdisk();
getdfree(drive+l, &free);
if (free.df_sclus == OxFFFF)
printf("Error in getdfree() call\n");
exit(l)i
avail = (long) free.df_avail * (long) free.df_bsec * (long) free.df_sclus;
printf("Drive %c: has %ld bytes available\n", 'A' + drive, avail);
return 0;

Chapter 2, The run-time library

223

•

getdisk, setdisk

getdisk, setdisk
Function
Syntax

Remarks

Gets or set the current drive number.
#include 
int getdisk(void);
int setdisk(int drive);

getdisk gets the current drive number. It returns an integer: 0 for A, 1 for
B, 2 for C, and so on (equivalent to DOS function Ox19).
setdisk sets the current drive to the one associated with drive: 0 for A, 1
for B, 2 for C, and so on (equivalent to DOS call OxOE).

Return value

getdisk returns the current drive number.
setdisk returns the total number of drives available.

See also

getcurdir, getcwd

Example

#include 
#include 
int main(void)
{

int disk, maxdrives = setdisk(2);
disk = getdisk() + 'A';
printf(lI\nThe number of logical drives is:%d\n", maxdrives);
printf("The current drive is: %c\n", disk);
return 0;

_getdrive
Function
Syntax

Remarks

Gets current drive number.
#include 
int _getdrive(void);

_getdrive uses DOS function Ox19 to get the current drive number. It

returns an integer: 1 for A, 2 for B, 2 for 3, and so on.

224

Borland C++ Library Reference

_gefdrive

Return value

_getdrive returns the current drive number.

See also

_dos_getdrive, _dos_setdrive, _getdcwd

Example

#include 
#include 
int main (void)
{

int disk;
disk = _getdrive(} + 'A' - 1;
printf("The current drive is: %c\n", disk};
return 0;

•

getdrivername
Function
Syntax

Returns a pointer to a string containing the name of the current graphics
driver.
#include 
char *far getdrivername(void);

Remarks

After a call to initgraph, getdrivername returns the name of the driver that
is currently loaded.

Return value

getdrivername returns a pointer to a string with the name of the currently
loaded graphics driver.

See also

initgraph

Example

#include
#include
#include
#include






int main ()
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
/* stores the device driver name */
char *drivername;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "OJ;

Chapter 2, The run-time library

225

getdrivername

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf (" Press any key to halt:") ;
getch () ;
exit(l);
/* terminate with an error code */

setcolor(getmaxcolor()) ;
/* get the name of the device driver in use */
drivername = getdrivername();
/* for centering text onscreen */
settextjustify(CENTER_TEXT, CENTER_TEXT);
/* output the name of the driver */
outtextxy (getmaxx () / 2, getmaxy() / 2, drivername);
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

getdta
Function
Syntax

Remarks

Gets disk transfer address.
#include 
char far *getdta(void);

getdta returns the current setting of the disk transfer address (DTA).

In the small and medium memory models, it's assumed the segment is the
current data segment. If you use C exclusively, this will be the case, but
assembly routines can set the DTA to any hardware address.
In the compact, large, or huge memory models, the address returned by
getdta is the correct hardware address and can be located outside the

program.
Return value
See also

226

getdta returns a far pointer to the current DT A.

feb (structure), setdta

Borland C++ Library Reference

getdta

Example

#incl ude 
#include 
int main(void)
{

char far *dta;
dta = getdta();
printf("The current disk transfer address is: %Fp\n", dta);
return 0;

•

getenv
Function
Syntax

Remarks

Return value

t:::>

Gets a string from environment.
#include 
char *getenv(const char *name);

getenv returns the value of a specified variable. On DOS, name must be
uppercase. On other systems, name can be either uppercase or lowercase.
name must not include the equal sign (=). If the specified environment
variable does not exist, getenv returns a NULL pointer.

On success, getenv returns the value associated with name. If the specified
name is not defined in the environment, getenv returns a NULL pointer.
Environment entries must not be changed directly. If you want to change
an environment value, you must use putenv.

See also

environ (global variable), getpsp, putenv

Example

#include 
#include 
int main(void)
{

char *s;
/* get the comspec environment parameter */
s=getenv("COMSPEC");
/* display comspec parameter */
printf ("Command processor: %s\n", s);
return 0;

Chapter 2, The run-time library

227

getfat

getfat
Function
Syntax

Remarks

Gets file allocation table information for given drive.
#include 
void getfat(unsigned char drive, struct fatinfo *dtable);

getfat gets information from the file allocation table (FAT) for the drive
specified by drive (0 for default, 1 for A, 2 for B, and so on). dtable points to
the fatinfo structure to be filled in. The fatinfo structure filled in by getfat
is defined as follows:
struct fat info {
char fi_sclus;
char fi_fatid;
unsigned fi_nclus;
int fi_bysec;

1*
1*
1*
1*

sectors per cluster *1
the FAT id byte *1
number of clusters *1
bytes per sector *1

};

Return value

None.

See also

getdfree, getfatd

Example

#include 
#include 
#include 
int main ()
{

struct fat info diskinfo;
int flag = 0;
printf("Please insert a diskette in drive 'A'\n");
getch() ;
getfat(l, &diskinfo); 1* get drive information *1
printf("\nDrive A: is ");
switch((unsigned char) diskinfo.fi_fatid) {
case OxFD: printf("a 360K low density\n");
break;
case OxF9: printf("a 1.2 Meg 5-1/4\" or 720 K 3-1/2\"\n");
break;
case OxFO: printf("1.44 Meg 3-1/2\"\n");
break;
default: printf("unformatted\n");
flag = 1;

228

Borland C++ Library Reference

if (!flag) {
printf("sectors per cluster: %5d\n", diskinfo.fi_sclus);
printf("number of clusters: %5d\n", diskinfo.fi_nclus);
printf ("bytes per sector:
%5d\n", diskinfo. fi_bysec);
return 0;

getfatd
Function
Syntax

Remarks

Gets file allocation table information;
#include 
void getfatd(struct fatinfo *dtable);

getfatd gets information from the file allocation table (FAT) of the default
drive. dtable points to the fatinfo structure to be filled in. The fatinfo
structure filled in by getfatd is defined as follows:
struct fat info {
char fi_sclus;
char fi_fatid;
int fi_nclus;
int fi_bysec;

/*
/*
/*
/*

sectors per cluster */
the FAT id byte */
number of clusters */
bytes per sector */

};

Return value

None.

See also

getdfree, getfat

Example

#include 
#include 
int main ()
{

struct fat info diskinfo;
/* get default drive information */
getfatd(&diskinfo) ;
printf("\nDefault Drive:\n");
printf("sectors per cluster: %5d\n",diskinfo.fi_sclus);
%5X\n",diskinfo.fi_fatid & OxFF);
printf("FAT 10 byte:
printf ("number of clusters %5d\n" , diskinfo. fLnclus) ;
%5d\n" ,diskinfo.fi_bysec);
printf ("bytes per sector.
return 0;

Chapter 2, The run-time library

229

getfillpattern

getfillpattern
Function
Syntax

Remarks

Copies a user-defined fill pattern into memory.
#include 
void far getfillpattern(char far *pattern);

getfillpattern copies the user-defined fill pattern, as set by setfillpattern,
into the 8-byte area pointed to by pattern.
pattern is a pointer to a sequence of 8 bytes, with each byte corresponding

to 8 pixels in the pattern. Whenever a bit in a pattern byte is set to 1, the
corresponding Fixel will be plotted. For example, the following userdefined fill pattern represents a checkerboard:
char checkboard[8] = {
OxAA, Ox55, OxAA, Ox55, OxAA, Ox55, OxAA, Ox55
};

Return value

None.

See also

getfillsettings, setfillpattern

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;
char pattern[8] = {OxOO, Ox70, Ox20, Ox27, Ox25, Ox27, Ox04, Ox04};
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:") i
getch() ;

230

Borland C++ Library Reference

getfillpattern

exi t (1) ;

/* terminate with an error code */

maxx = getmaxx();
maxy = getmaXY()i
setcolor(getmaxcolor()) ;
/* select a user-defined fill pattern */
setfillpattern(pattern, getmaxcolor());

/* fill the screen with the pattern */
bartO, 0, maxx, maxy);
getch () ;
/* get the current user-defined fill pattern */
getfillpattern(pattern) ;
/* alter the pattern we grabbed */
pattern[4] -= 1i
pattern[5] -= 3;
pattern [6] += 3;
pattern[7] -= 4;
/* select our new pattern */
setfillpattern(pattern, getmaxcolor());
/* fill the screen with the new pattern */
bartO, 0, maxx, maxy);

/ * clean up */
getch() ;
closegraph ( ) ;
return 0;

getfillsettings
Function
Syntax

Remarks

Gets information about current fill pattern and color.
#include 
void far getfillsettings(struct fillsettingstype far *fillinfo);

getfillsettings fills in the fillsettingstype structure pointed to by fillinfo
with information about the current fill pattern and fill color. The
fillsettingstype structure is defined in graphics.h as follows:

Chapter 2, The run-time library

231

getfillseHings

struct fillsettingstype
int patterni
int colori

/* current fill pattern */
/* current fill color */

}i

The functions bar, bar3d, fillpoly, floodfill, and pieslice all fill an area with
the current fill pattern in the current fill color. There are 11 predefined fill
pattern styles (such as solid, crosshatch, dotted, and so on). Symbolic
names for the predefined patterns are provided by the enumerated type
fi1Cpatterns in graphics.h (see the following table). In addition, you can
define your own fill pattern.
If pattern equals 12 (USER_FILL), then a user-defined fill pattern is being
used; otherwise, pattern gives the number of a predefined pattern.

The enumerated type fill_patterns, defined in graphics.h, gives names for
the predefined fill patterns, plus an indicator for a user-defined pattern.
Name

Value

EMPTY_FILL
SOLID_FILL
LINE_FILL
LTSLASH_FILL
SLASH_FILL
BKSLASH_FILL
LTBKSLASH_FILL
HATCH_FILL
XHATCH_FILL
INTERLEAVE_FILL
WIDE_DOT_FILL
CLOSE_DOT_FILL
USER_FILL

a
1
2

3
4
5
6
7
8
9
10
11
12

Description

Fill with background color
Solid fill
Fill with-Fill with / / /
Fill with / / /, thick lines
Fill with \ \ \, thick lines
Fill with \ \ \
Light hatch fill
Heavy crosshatch fill
Interleaving line fill
Widely spaced dot fill
Closely spaced dot fill
User-defined fill pattern

All but EMPTY_FILL fill with the current fill color; EMPTY_FILL uses the
current background color.
Return value

None.

See also

getfillpattern, setfillpattern, setfillstyle

Example

#incl ude
#include
#include
#include






/* the names of the fill styles supported */
char *fname[] = { "EMPTY_FILL", "SOLID_FILL", "LINE_FILL", "LTSLASH_FILL",
"SLASH_FILL", "BKSLASH_FILL", "LTBKSLASH_FILL", "HATCH_FILL",
"XHATCH_FILL", "INTERLEAVE_FILL", "WIDE_DOT_FILL",
"CLOSE_DOT_FILL", "USER_FILL" }i

232

Borland C++ Library Reference

getfillseHings

int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
struct fillsettingstype fillinfo;
int midx, midy;
char patstr[40J, colstr[40J;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

•

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode) I;
printf("Press any key to halt:");
getch();
exit(l);
/* terminate with an error code */

midx =°getmaxx()
midy = getmaxy()

2;
2;

/* get info about current fill pattern and color */
getfillsettings(&fillinfo) ;
/* convert fill information into strings */
sprintf(patstr, "%s is the fill style.", fname[fillinfo.patternJ);
sprintf (colstr, "%d is the fill color.", fillinfo.color);
/* display the information */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, patstr);
outtextxy (midx, midy+2*textheight ("W"), colstr);

/* clean up */
getch () ;
closegraph ( ) ;
return 0;

getftime, setftime
Function
Syntax

Gets and set the file date and time.
#include 
int getftime(int handle, struct ftime *ftimep);
int setftime(int handle, struct ftime *ftimep);

Chapter 2, The run-time library

233

getftime, setftime

Remarks

getftime retrieves the file time and date for the disk file associated with
the open handle. The ftime structure pointed to by ftimep is filled in with
the file's time and date.
setftime sets the file date and time of the disk file associated with the open
handle to the date and time in the ftime structure pointed to by ftimep. The
file must not be written to after the setftime call or the changed

information will be lost.
The ftime structure is defined as follows:
struct £time {
unsigned ft_tsec: 5;
unsigned ft_min: 6;
unsigned ft_hour: 5;
unsigned ft_day: 5;
unsigned ft_month: 4;
unsigned ft-year: 7;

/*
/*
/*
/*
/*
/*

two seconds· */
minutes */
hours */
days */
months */
year - 1980*/

};

Return value

getftime and setftime return 0 on success.

In the event of an error return, -1 is returned and the global variable errno
is set to one of the following:

EINVFNC
EBADF

Invalid function number
Bad file number

See also

fflush, open, setftime

Example

#include 
#include 
int main ()
{

FILE *stream;
struct ftime ft;
printf("Creating new file TEST.$$$\n");
if ((stream = fopen("TEST.$$$", "wt")) ==NULL)
printf("Cannot open output file.\n");
return 1;
if (getftime(fileno(stream), &ft) != 0)
perror("Unable to get file time");
return 1;

234

Borland C++ Library Reference

getftime, setftime

printf("File time: %02u:%02u:%02u\n",
ft.ft_hour, ft.ft_min, ft.ft_tsec * 2);
printf("File date: %02u/%02u/%04u\n",
ft.ft_month, ft.ft_day, ft.ft-year+1980);
printf("Setting file year to 2001.\n");
ft.ft-year = 2001 - 1980;
if (setftime(fileno(stream), &ft) != 0)
perror("Unable to set file time");
fclose (stream) ;
return 0;

I

I

I

I

•

getgraphmode
Function
Syntax

Returns the current graphics mode.
#include 
int far getgraphmode(void);
C++ only

Remarks

Your program must make a successful call to initgraph before calling
getgraphmode.

The enumeration graphics_mode, defined in graphics.h, gives names for the
predefined graphics modes. For a table listing these enumeration values,
refer to the description for initgraph.
Return value

getgraphmode returns the graphics mode set by initgraph or
setgraphmode.

See also

getmoderange, restorecrtmode, setgraphmode

Example

#include
#include
#include
#include






int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy, mode;
char numname[80] , modename[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

Chapter 2, The run-time library

235

getgraphmode

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf ("Graphics error: %s\n", grapherrormsg (errorcode) ) ;
. print f ( "Press any key to hal t : " ) ;
getch () ;
exit(l);
/* terminate with an error code */
midx = getmaxx() / 2;
midy = getmaxy() / 2;
/* get mode number and name strings */
mode = getgraphrnode();
sprintf(nurnname, "%d is the current mode number.", mode);
sprintf(modename, "%s is the current graphics mode.", getmodename(mode));
/* display the information */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, nurnname);
outtextxy (midx, midy+2*textheight ("W"), modename);
/* clean up */
getch() i
closegraph ( ) ;
return 0;

getimage
Function
Syntax

Remarks

Saves a bit image of the specified region into memory.
#include 
void far getimage(int left, int top, int right, int bottom, void far *bitmap);

getimage copies an image from the screen to memory.

left, top, right, and bottom define the screen area to which the rectangle is
copied. bitmap points to the area in memory where the bit image is stored.
The first two words of this area are used for the width and height of the
rectangle; the remainder holds the image itself.
Return value
See also

236

None.
imagesize, putimage, putpixel

Borland c++ Library Reference

getimage

Example

#include
#include
#include
#include
#include







void save_screen(void far *buf[4]);
void restore_screen(void far *buf[4]);
int maxx, maxy;
int main (void)

I

int gdriver=DETECT, grnode, errorcode;
void far *ptr[4];
/* autodetect the graphics driver and mode */
initgraph(&gdriver, &gmode, 1111);
errorcode = graphresult(); /* check for any errors */
if (errorcode != grOk) {
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf (" Press any key to halt: ") ;
getch () ;
exit(l) ;
maxx
maxy

getmaxx();
getmaxy();

/* draw an image on the screen
rectangle (0, 0, maxx, maxy);
line(O, 0, maxx, maxy);
line(O, maxy, max x , 0);
save_screen(ptr);
/*
getch() ;
/*
cleardevice () ;
/*
restore_screen(ptr);
/*
getch() ;
/*
closegraph ( ) ;
return 0;

*/

save the current screen */
pause screen */
clear screen */
restore the screen */
pause screen */

void save_screen(void far *buf[4])
unsigned size;
int ystart=O, yend, yincr, block;
yincr = (maxytl) / 4;
yend = yincr;
/* get byte size of image */
size = imagesize(O, ystart, maxx, yend);
for (block=O; block<=3; blocktt) {

Chapter 2, The run-time library

237

getimoge

if ((buf[block] = farmalloc(size)) == NULL) {
c10segraph ( ) ;
printf("Error: not enough heap space in save_screen() .\n");
exit(l);
getimage(O, ystart, maxx, yend, buf[block]);
ystart = yend t 1;
yend t= yincr t 1;

void restore_screen(void far *buf[4])
{

int ystart=O, yend, yincr, block;
yincr = (maxyt1) / 4;
yend = yincr;
for (block=O; block<=3; blocktt) {
put image (0, ystart, buf[block] , COPY_PUT);
farfree(buf[block]) ;
ystart = yend t 1;
yend t= yincr t 1;

getlinesettings
Function
Syntax

Remarks

Gets the current line style, pattern, and thickness.
#include 
void far getlinesettings(struct line?ettingstype far *lineinfo);

getlinesettings fills a linesettingstype structure pointed to by lineinfo with
information about the current line style, pattern, and thickness.

The linesettingstype structure is defined in graphics.h as follows:
struct linesettingstype
int linestyle;
unsigned upattern;
int thickness;
};

238

Borland C++ Library Reference

getlinesettings

linestyle specifies in which style subsequent lines will be drawn (such as
solid, dotted, centered, dashed). The enumeration line_styles, defined in
graphics.h, gives names to these operators:
Name

Value

SOLID_LINE
DOTTED_LINE
CENTER_LINE
DASHED _LINE
USERBIT_LINE

o
1
2

3
4

Description

Solid line
Dotted line
Centered line
Dashed line
User-defined line style

•

thickness specifies whether the width of subsequent lines drawn will be
normal or thick.
Name

Value

NORM_WIDTH
THICK_WIDTH

1

3

Description

1 pixel wide
3 pixels wide

upattern is a 16-bit pattern that applies only if linestyle is USERBIT_LINE
(4). In that case, whenever a bit in the pattern word is 1, the corresponding
pixel in the line is drawn in the current drawing color. For example, a
solid line corresponds to a upattern of OxFFFF (all pixels drawn), while a
dashed line can correspond to a upattern of Ox3333 or OxOFOF. If the
linestyle parameter to setlinestyle is not USERBIT_LINE (!=4), the upattern
parameter must still be supplied but is ignored.
Return value

None.

See also

setlinestyle

Example

#include
#include
#include
#include






/* the names of the line styles supported */
char *lname[] = { "SOLID_LINE", "DOTTED_LINE", "CENTER_LINE", "DASHED_LINE",
"USERBIT_LINE" };
int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
struct linesettingstype lineinfo;
int midx, midy;
char lstyle[80], lpattern[80] , lwidth[80];

Chapter 2, The run-time library

239

getlineseHings

1* initialize graphics and local variables *1
initgraph(&gdriver, &gmode, "");
1* read result of initialization *1
errorcode = graphresult();
if (errorcode != grOk) { 1* an error occurred *1
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
1* terminate with an error code *1
midx
midy

= getmaxx()
= getmaxy()

I 2;
I 2;

1* get information about current line settings *1
getlinesettings(&lineinfo) ;
1* convert line information into strings */
sprintf(lstyle, "%s is the line style.", lname[lineinfo.linestyle]);
sprintf(lpattern, "Ox%X is the user-defined line pattern.",
lineinfo.upattern) ;
sprintf(lwidth, "%d is the line thickness.", lineinfo.thickness);
1* display the information *1
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, lstyle);
outtextxy (midx, midy+2*textheight ("W"), lpattern);
outtextxy (midx, midy+4 *textheight ("W"), lwidth);
1* clean up *1
getch () ;
closegraph ( ) ;
return 0;

getmaxcolor
Function
Syntax

Remarks

240

Returns maximum color value that can be passed to the setcolor function.
#include 
int far getmaxcolor(void);

getmaxcolor returns the highest valid color value for the current graphics
driver and mode that can be passed to setcolor.

Borland C++ Library Reference

getmaxcolor '

For example, on a 256K EGA, getmaxeolor always returns IS, which
means that any call to seteolor with a value from 0 to 15 is valid. On a
eGA in high-resolution mode or on a Hercules monochrome adapter,
getmaxeolor returns a value of 1.
Return value

getmaxeolor returns the highest available color value.

See also

getbkeolor, geteolor, getpalette, getpalettesize, seteolor

Example

#include
#include
#include
#include

I






int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
char colstr[80);
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */

midx = getmaxx() / 2;
midy = getmaxy() / 2;
/* grab the color info. and convert it to a string */
sprintf(colstr, "This mode supports colors O.. %d", getmaxcolor());
/* display the information */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, colstr);
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

Chapter 2, The run-time library

241

getmaxmode

getmoxmode
Function
Syntax

Remarks

Return value

Returns the maximum mode number for the current driver.
#include 
int far getmaxmode(void);

getmaxmode lets you find out the maximum mode number for the
currently loaded driver, directly from the driver. This gives it an
advantage over getmoderange, which works for Borland drivers only.
The minimum mode is O.
getmaxmode returns the maximum mode number for the current driver.

See also

getmodename, getmoderange

Example

#inc1ude
#include
#include
#include






int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
char modestr[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, 1111);
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf(IIGraphics error: %s\nll, grapherrormsg(errorcode));
printf ( I Press any key to halt: I ) ;
getch () ;
exit(l);
/* terminate with an error code */

midx = getmaxx() / 2;
midy = getmaxy() / 2;
/* grab the mode info. and convert it to a string */
sprintf(modestr, IIThis driver supports modes O.. %d l , getmaxmode());

/* display the information */

242

Borland C++ Library Reference

getmaxmode

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, modestr);
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

getmaxx
Function
Syntax

Remarks

•
Returns maximum x screen coordinate.
#include 
int far getmaxx(void);

getmaxx returns the maximum (screen-relative) x value for the current
graphics driver and mode.

For example, on a eGA in 320x200 mode, getmaxx returns 319. getmaxx is
invaluable for centering, determining the boundaries of a region onscreen,
and so on.
Return value

getmaxx returns the maximum x screen coordinate.

See also

getmaxy, getx

Example

#include
#include
#include
#include






int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
char xrange[80l, yrange[80l;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, 1111);
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */

Chapter 2, The run-time library

243

getmoxx

printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf ("Press any key to halt:");
getch () ;
exit(l);
1* terminate with an error code *1
midx
midy

= getmaxx()
= getmaxy()

I 2;
I 2;

1* convert max resolution values to strings. *1
sprintf(xrange, "X values range from O.. %d", getmaxx());
sprintf (yrange, lOy values range from 0 .. %d", getmaxy () ) ;
1* display the information *1
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, xrange);
outtextxy (midx, midy + textheight ("W"), yrange);
1* clean up *1
getch() ;
closegraph ( ) ;
return 0;

getmaxy
Function
Syntax

Returns maximum y screen coordinate.
#include 
int far getmaxy(void);
ANSI C

Remarks

c++

only

getmaxy returns the maximum (screen-relative)

y value for the current

graphics driver and mode.
For example, on a eGA in 320x200 mode, getmaxy returns 199. getmaxy is
invaluable for centering, determining the boundaries of a region onscreen,
and so on.
Return value
See also
Example

244

getmaxy returns the maximum y screen coordinate.
getmaxx, getx, gety
#include
#include
#include
#include






Borland C++ Library Reference

getmoxy

int main (void)
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
char xrange[80j, yrange[80j;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

•

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) {
/* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
print f ( "Press any key to hal t : " ) ;
getch() ;
exit(l);
/* terminate with an error code */

midx
midy

getmaxx() / 2;
getmaxy() / 2;

/* convert max resolution values into strings */
sprintf(xrange, "X values range from o.. %d", getmaxx());
sprintf (yrange, "Y values range from 0.. %d", getmaxy () ) ;
/* display the information */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, xrange);
outtextxy (midx, midy+textheight ("\'I"), yrange);

/* clean up */
getch() ;
closegraph ( ) ;
return 0;

getmodename
Function
Syntax

Returns a pointer to a string containing the name of a specified graphics
mode.
#include 
char *far getmodename(int mode_number);

Chapter 2, The run-time library

245

getmodename

Remarks

getmodename accepts a graphics mode number as input and returns a

string containing the name of the corresponding graphics mode. The
mode names are embedded in each driver. The return values ( I/320x200
CGA PI," I/640x200 CGA", and so on) are useful for building menus or
displaying status.
Return value

getmodename returns a pointer to a string with the name of the gr'aphics

mode.
See also

getmaxmode, getmoderange

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy, mode;
char numname[80], modename[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, '"');
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */
midx
midy

= getmaxx() / 2;
= getmaxy() / 2;

/* get mode number and name strings */
mode = getgraphmode();
sprintf(numname, "%d is the current mode number.", mode);
sprintf(modename, "%s is the current graphics mode.", getmodename(mode));
/* display the information */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, numname);
outtextxy (midx, midy+2 *textheight ("W"), modename);
/* clean up */
getch() ;
closegraph ( ) ;

246

Borland C++ Library Reference

getmoderange

return 0;

getmoderange
Function
Syntax

Remarks

Return value

Gets the range of modes for a given graphics driver.
#include 
void far getmoderange(int graph driver, int far *lomode, int far *himode);

getmoderange gets the range of valid graphics modes for the given
graphics driver, graphdriver. The lowest permissible mode value is
returned in *lomode, and the highest permissible value is *himode. If
graphdriver specifies an invalid graphics driver, both *lomode and *himode
are set to -1. If the value of graphdriver is -1, the currently loaded driver
modes are given.

None.

See also

getgraphmode, getmaxmode, getmodename, initgraph, setgraphmode

Example

#include
#include
#include
#include






int main(void)
{

1* request autodetection *1
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
int low, high;
char mrange[80];

1* initialize graphics and local variables *1
initgraph(&gdriver, &gmode, 1111);
1* read result of initialization *1
errorcode = graphresult();
if (errorcode != grOk) { 1* an error occurred *1
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf ( Press any key to halt: ") ;
getch() ;
exit(l);
1* terminate with an error code */
II

Chapter 2, The run-time library

247

getmoderange

midx
midy

= getmaxx() / 2;
= getmaxy() / 2;

/* get the mode range for this driver */
getmoderange(gdriver, &low, &high);
/* convert mode range info. into strings */
sprintf(mrange, "This driver supports modes %d .. %d", low, high);
/* display the information */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, mrange);

/ * clean up * /
getch () ;
closegraph ( ) ;
return 0;

getpalette
Function
Syntax

Gets information about the current palette.
#include 
void far getpalette(struct palettetype far *palette);
DOS

I
• I

Remarks

UNIX

Windows

ANSI C

I C++ only
I

I
I

getpalette fills the palettetype structure pointed to by palette with
information about the current palette's size and colors.

The MAXCOLORS constant and the palettetype structure used by
getpalette are defined in graphics.h as follows:
#define MAXCOLORS

15

struct palettetype {
unsigned char size;
signed char colors[MAXCOLORS + 1];
};

size gives the number of colors in the palette for the current graphics
driver in the current mode.

colors is an array of size bytes containing the actual raw color numbers for
each entry in the palette.
..

248

getpalette cannot be used with the IBM-8S14 driver.

Borland C++ Library Reference

getpaleHe

Return value

None.

See also

getbkcolor, getcolor, getdefaultpalette, getmaxcolor, setallpalette,
setpalette

Example

#incl ude
#include
#include
#include






I

int main ()
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
struct palettetype pal;
char psize[80], pval[20];
int i, ht;
int y = 10;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf ("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(1);
/* terminate with an error code */
/* grab a copy of the palette */
getpalette(&pal);
/* convert palette info into strings */
sprintf(psize, "The palette has %d modifiable entries.", pal.size);
/* display the information */
outtextxy(O, y, psize);
if (pal.size != 0) {
ht = textheight("W");
y += 2*ht;
outtextxy(O, y, "Here are the current values:");
y t= 2*ht;
for (i=O; i
int far getpalettesize(void);

getpalettesize is used to determine how many palette entries can be set
for the current graphics mode. For example, the EGA in color mode
returns 16.
getpalettesize returns the number of palette entries in the current palette.

See also

setpalette, setallpalette

Example

hncl ude
#include
#include
#include






int main ()
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
char psize[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
print f ( "Graphics error: %s \n", grapherrormsg (errorcode) ) ;
printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */

midx
midy

250

= getmaxx()
= getmaxy()

2;
2;

Borland C++ Library Reference

getpolettesize

/* convert palette size info into string */
sprintf(psize, "The palette has %d modifiable entries.", getpalettesize());
/* display the information */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, psize);
/* clean up */
getch () ;
closegraph ( ) ;
return 0;

getpass
Function
Syntax

Remarks

Return value

Reads a password.
#include 
char *getpass(const char *prompt);

getpass reads a password from the system console, after prompting with
the null-terminated string prompt and disabling the echo. A pointer is
returned to a null-terminated string of up to eight characters (not
counting the null-terminator).

The return value is a pointer to a static string, which is overwritten with
each call.

See also

getch

Example

#incl ude 

int main ()
{

char *password;
password = getpass("Input a password:");
cprintf("The password is: %s\r\n", password);
return 0;

getpid
Function

Gets the process ID of a program.

Chapter 2, The run-time library

251

getpid

Syntax

Remarks

Return value

#include 
unsigned getpid (void)

A process 10 uniquely identifies a program. The concept is borrowed
from multitasking operating systems like UNIX, where each process is
associated with a unique process number.
getpid returns the segment value of a program's PSP.

See also

getpsp, -psp (global variable)

Example

#include 
#include 
int main ()
{

printf("This program's process identification number (PID) "
"number is %X\n", getpid () ) ;
printf("Note: under DOS it is the PSP segment\n");
return 0;

getpixel
Function

Gets the color of a specified pixel.

Syntax

#include 
unsigned far getpixel(int x, int y);
Wi ndows

Remarks
Return value

252

ANS I C

c++ on 1y

getpixel gets the color of the pixel located at (x,y).
getpixel returns the color of the given pixel.

See also

getimage, putpixel

Example

#include
#include
#include
#include
#include







Borland C++ Library Reference

getpixel

#define PIXEL_COUNT 1000
#define DELAY_TIME 100 /* in milliseconds */
int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int i, x, y, color, maxx, maxy, maxcolor, seed;

I

,

/* initialize graphics and local variables */

•

initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf ("Graphics error: %s\n", grapherrormsg (errorcode) ) ;
printf ( "Press any key to halt:") ;
getch() ;
exit(l);
/* terminate with an error code */

I

maxx = getmaxx() t 1;
maxy = getmaxy() t 1;
maxcolor = getmaxcolor() t 1;
while (!kbhit()) {
seed = random(32767); /* seed the random number generator */
srand(seed) ;
for (i=O; i
unsigned getpsp(void);

getpsp gets the segment address of the program segment prefix (PSP)
using DOS call Ox62.
getpsp returns the address of the Program Segment Prefix (PSP).

See also

getenv, -psp (global variable)

Example

#include 
#include 
int main(void)
{

static char command[128];
char far *cp;
int len, i;
printf("The program segment prefix is: %x\n", getpsp());
/* -psp is preset to the segment of the Program Segment Prefix (PSP).
The remainder of the command line is located at offset Ox80
from the start of PSP. Try passing this program arguments. */
cp = MK_FP(-psp, Ox80);
len = *cp;
for (i = 0; i < len; itt)
command[i] = cp[itl];
printf ("Command line: %s\n", command);
return 0;

gets
Function
Syntax

254

Gets a string from stdin.
#include 
char *gets(char *s);

Borland C++ Library Reference

gets

Remarks

gets collects a string of characters terminated by a new line from the
standard input stream stdin and puts it into s. The new line is replaced by
a null character (\0) in s.
gets allows input strings to contain certain whitespace characters (spaces,
tabs). gets returns when it encounters a new line; everything up to the

new line is copied into s.
Return value

On success, gets returns the string argument s; it returns null on end-offile or error.

See also·

cgets, ferror, fgets, fopen, fputs, fread, getc, puts, scanf

Example

#include 
int main (void)
{

char string[80];
printf ( I Input a string: ") ;
gets (string) ;
printf(IIThe string input was: %s\n", string);
return 0 i

gettext
Function
Syntax

Remarks

Copies text from text mode screen to memory.
#include 
int gettext(int left, int top, int right, int bottom, void *destin);

gettext stores the contents of an onscreen text rectangle defined by left, top,

right, and bottom into the area of memory pointed to by destin.
All coordinates are absolute screen coordinates, not window-relative. The
upper left corner is (1,1).
gettext reads the contents of the rectangle into memory sequentially from
left to right and top to bottom.

Each position onscreen takes 2 bytes of memory: The first byte is the
character in the cell, and the second is the cell's video attribute. The space
required for a rectangle w columns wide by h rows high is defined as

Chapter 2, The run-time library

255

I

•

I

geHext

bytes = (h rows) x (w columns) x 2
Return value

gettext returns 1 if the operation succeeds. It returns 0 if it fails (for
example, if you gave coordinates outside the range of the current screen
mode).

See also

movetext, puttext

Example

#inc1ude 
char buffer[4096];
int main(void)
{

int i;
c1rscr () ;
for (i = 0; i <= 20; itt)
cprintf("Line #%d\r\n", i);
gettext(l, 1, 80,25, buffer);
gotoxy(l, 25);
cprintf ("Press any key to clear screen ... ");
getch () ;
clrscr () ;
gotoxy(l, 25);
cprintf("Press any key to restore screen ... ");
getch () ;
puttext(l, 1, 80, 25, buffer);
gotoxy (1, 25);
cprintf("Press any key to quit ... ");
getch () ;
return 0;

gettextinfo
Function
Syntax

Remarks

Gets text mode video information.
#include 
void gettextinfo(struct text_info *r);

gettextinfo fills in the text_info structure pointed to by r with the current
text video information.

The text_info structure is defined in conio.h as follows:

256

Borland C++ Library Reference

gettextinfo

struct text_info
unsigned char
unsigned char
unsigned char
unsigned char
unsigned char
unsigned char
unsigned char
unsigned char
unsigned char
unsigned char
unsigned char

{
winleft;
wintop;
winright;
winbottom;
attribute;
normattr;
currmode;
screenheight;
screenwidth;
curx;
cury;

/*
/*
/*
/*

/*
/*
/*
/*
/*
/*
/*

left window coordinate */
top window coordinate */
right window coordinate */
bottom window coordinate */
text attribute */
normal attribute */
BW40, BWSO, C40, CSO, or C4350 */
text screen's height */
text screen's width */
x-coordinate in current window */
y-coordinate in current window */

};

Return value

gettextinfo returns nothing; the results are returned in the structure
pointed to by r.

See also

textattr, textbackground, textcolor, textmode, wherex, wherey, window

Example

#inc1ude 
int main(void)
{

struct text_info ti;
gettextinfo(&ti);
cprintf ("window left
cprintf("window top
cprintf("window right
cprintf ("window bottom
cprintf("attribute
cprintf ("normal attribute
cprintf (" current mode
cprintf("screen height
cprintf("screen width
cprintf("current x
cprintf("current y
return 0;

%2d\r\n",ti.winleft);
%2d\r\n",ti.wintop);
%2d\r\n",ti.winright);
%2d\r\n",ti.winbottom);
%2d\r\n",ti.attribute);
%2d\r\n", ti .normattr);
%2d\r\n" , ti. currmode) ;
%2d\r\n",ti.screenheight);
%2d\r\n",ti.screenwidth);
%2d\r\n",ti.curx);
%2d\r\n",ti.cury) ;

gettextsettings
Function
Syntax

Gets information about the current graphics text font.
#include 
void far gettextsettings(struct textsettingstype far *texttypeinfo);

Chapter 2, The run-time library

257

geHextseHings

Remarks

gettextsettings fills the textsettingstype structure pointed to by textinfo
with information about the current text font, direction, size, and
justification.

The textsettingstype structure used by gettextsettings is defined in
graphics.h as follows:
struct
int
int
int
int
int

text settings type
font;
direction;
charsize;
horiz;
vert;

};

See settextstyle for a description of these fields.
Return value
( See also
Example

None.
outtext, outtextxy, registerbgifont, settextjustify, settextstyle,
setusercharsize, textheight, textwidth
#include
#include
#include
#include






/* the names of the supported fonts */
char *font[] = { "DEFAULT_FONT", "TRIPLEX]ONT", "SMALL_FONT", "SANS_SERIF_FONT",
"GOTHIC]ONT" };
/* the names of the text directions supported */
char *dir [1 = { "HORIZ_DIR", "VERT_DIR" };
/* horizontal text justifications supported */
char *hjust[] = { "LEFT_TEXT", "CENTER_TEXT", "RIGHT_TEXT" };
/* vertical text justifications supported */
char *vjust[] = { "BOTTOM_TEXT", "CENTER_TEXT", "TOP_TEXT" };
int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
struct textsettingstype textinfo;
int midx, midy, ht;
char fontstr[80], dirstr[80], sizestr[80];

258

Borland C++ Library Reference

gettextsettings

char hjuststr[SO] , vjuststr[SO];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode ! = grOk) { / * an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
print f ( "Press any key to halt:");
getch();
exit(l);
/* terminate with an error code */

midx
midy

I

I

•

getmaxx() / 2;
getmaxy() / 2;

/* get information about current text settings */
gettextsettings(&textinfo) ;
/* convert text information into strings */
sprintf(fontstr, "%s is the text style.", font[textinfo.font]);
sprintf(dirstr, "%s is the text direction.", dir[textinfo.direction]);
sprintf(sizestr, "%d is the text size.", textinfo.charsize);
sprintf(hjuststr, "%s is the horizontal justification.",
hjust[textinfo.horiz]) ;
sprintf(vjuststr, "%s is the vertical justification.", vjust[textinfo.vert]);
/* display the information */
ht = textheight ( OW" ) ;
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, fontstr);
outtextxy(midx, midy+2*ht, dirstr);
outtextxy(midx, midy+4*ht, sizestr);
outtextxy(midx, midy+6*ht, hjuststr);
outtextxy(midx, midy+S*ht, vjuststr);
/* clean up */
getch () ;
closegraph() ;
return 0;

gettime settime
I

Function
Syntax

Gets and sets the system time.
#include 
void gettime(struct time *timep);
void settime(struct time *timep);

Chapter 2, The run-time library

259

I

geHime, seHime

I
• I

DOS

Remarks

UNIX

I
I

Wi ndows

ANSI C

I C++

I

only

I

I

gettime fills in the time structure pointed to by timep with the system's
current time.
settime sets the system time to the values in the time structure pointed to
by timep.

The time structure is defined as follows:
struct time
unsigned
unsigned
unsigned
unsigned

{
char
char
char
char

ti_min;
ti_hour;
ti_hund;
ti_sec;

1*
1*
1*
1*

minutes *1
hours *1
hundredths of seconds *1
seconds *1

};

Return value

None.

See also

_dos_gettime, _dos_settime, getdate, setdate, stime, time

Example

#include 
#include 
int main (voidl
{

struct time t;
gettime(&tl;
printf("The current
printf(IIThe current
printf("The current
printf("The current

minute is: %d\n", t.ti_minl;
hour is: %d\n", t.ti_hourl;
hundredth of a second is: %d\n", t.ti_hundli
second is: %d\n", t.ti_secli

1* add 1 to minutes struct element, then call settime *1
t.ti_min++i
settime(&tli
return Oi

getvect, setvect
Function
Syntax

260

Gets and sets interrupt vector.
#include 
void interrupt(*getvect(int interruptno» 0;
void setvect(int interruptno, void interrupt (*isr) 0);

Borland C++ Library Reference

getvect, setvect

Remarks

Every processor of the 8086 family includes a set of interrupt vectors,
numbered 0 to 255. The 4-byte value in each vector is actually an address,
which is the location of an interrupt function.
getvect reads the value of the interrupt vector given by interruptno and

I

returns that value as a (far) pointer to an interrupt function. The value of
interruptno can be from 0 to 255.
setvect sets the value of the interrupt vector named by interruptno to a
new value, isr, which is a far pointer containing the address of a new
interrupt function. The address of a C routine can only be passed to isr if
that routine is declared to be an interrupt routine.

_
Return value

If you use the prototypes declared in dos.h, simply pass the "address of an
interrupt function to setvect in any memory model.
getvect returns the current 4-byte value stored in the interrupt vector
named by interruptno.
setvect does not return a value.

See also

disable, _dos_getvect, _dos_setvect, enable, geninterrupt

Example

#include 
#include 
#ifdef __ cplusplus
#define __ CPPARGS
#else
#define __CPPARGS
#endif
void interrupt get_out( __ CPPARGS);
1* interrupt prototype *1
void interrupt (*oldfunc) (__ CPPARGS); 1* interrupt function pointer *1
int looping

= 1;

int main(void)
{

puts("Press  to terminate");

1* save the old interrupt *1
oldfunc = getvect(5);
1* install interrupt handler *1
setvect(5,get_out) ;
1* do nothing *1
while (looping);

Chapter 2, The run-time library

261

•

I

getvect, setvect

/* restore to original interrupt routine */
setvect(S,oldfunc);

puts ( Success ") ;
return 0;
II

void interrupt get_out (__CPPARGS)
{

looping

= 0;

/* change global variable to get out of loop */

getverify
Function
Syntax

Remarks

Returns the state of the DOS verify flag.
#include 
int getverify(void);

getverify gets the current state of the verify flag.

The verify flag controls output to the disk. When verifyis off, writes are
not verified; when verify is on, all disk writes are verified to ensure
proper writing of the data.
Return value

getverify returns the current state of the verify flag, either a or 1.

• A return of a = verify flag off.
• A return of 1 = verify flag on.
See also

setverify

Example

#include 
#include 
int main (void)
{

if (getverify())
printf("DOS verify flag is on\n");
else
printf("DOS verify flag is off\n");
return 0;

262

Borland C++ Library Reference

getviewsettings

getviewsettings
Function
Syntax

Remarks

Gets information about the current viewport.
#include 
void far getviewsettings(struct viewporttype far *viewport);

getviewsettings fills the viewporttype structure pointed to by viewport
with information about the current viewport.

The viewporttype structure used by getviewport is defined in graphics.h
as follows:
struct viewporttype
int left, top, right, bottom;
int clip;
};

Return value

None.

See also

clearviewport, getx, gety, setviewport

Example

#incl ude
#include
#include
#include






char *clip[]

= {

"OFF", "ON" };

int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
struct viewport type viewinfo;
int midx, midy, ht;
char topstr[80], botstr[80], clipstr[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read" result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");

Chapter 2, The run-time library

263

getviewsettings

getch () ;
exit (1);
midx
midy

/* terminate with an error code */

= getmaxx() / 2;
= getmaxy() / 2;

/* get information about current viewport */
getviewsettings(&viewinfo) ;
/* convert text information into strings */
sprintf(topstr, "(%d, %d) is the upper left viewport corner. ", viewinfo.left,
viewinfo. top) ;
sprintf(botstr, (%d, %d) is the lower right viewport corner.
viewinfo.right, viewinfo.bottom);
sprintf(clipstr, "Clipping is turned %s.", clip[viewinfo.clipJ);
II

11 ,

/* display the information */
settextjustify(CENTER_TEXT, CENTER_TEXT);
ht = textheight("W");
outtextxy(midx, midy, topstr);
outtextxy(midx, midy+2*ht, botstr);
outtextxy(midx, midy+4*ht, clipstr);
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

getw
Function
Syntax

Gets integer from stream.
#include 
int getw(FILE *stream);
DOS

•
Remarks

I
• I

UNIX

Windows

•

ANSI C

I

I

C++ only

II
II

getw returns the next integer in the named input stream. It assumes no
special alignment in the file.
getw should not be used when the stream is opened in text mode.

Return value

264

getw returns the next integer on the input stream. On end-of-file or error,
getw returns EOF. Because EOF is a legitimate value for getw to return,
feof or ferror should be used to detect end-of-file or error.

Borland C++ Library Reference

getw

See also

putw

Example

#include 
#include 
#define FNAME test. $$$
II

II

int main(void)
{

FILE *fp;
int word;
/* place the word in a file */
fp = fopen (FNAME, "wb");
if (fp == NULL) {
printf("Error opening file %s\n", FNAME);
exit (1);
word = 94;
putw(word, fp);
if (ferror(fp))
printf("Error writing to file\n");
else
printf("Successful write\n");
fclose(fp);
/* reopen the file */
fp = fopen(FNAME, "rb");
if (fp == NULL) {
printf ("Error opening file %s\n", FNAME);
exit(l);
/* extract the word */
word = getw(fp);
if (ferror(fp))
printf("Error reading file\n");
else
printf (" Successful read: word = %d\n ", word);
/* clean up */
fclose(fp) ;
unlink (FNAME) ;
return 0;

Chapter 2, The run-time library

265

getx

getx
Function
Syntax

Remarks
Return value

Returns the current graphics position's x-coordinate.
#include 
int far getx(void);

getx finds the current graphics position's x-coordinate. The value is
viewport-relative.
getx returns the x-coordinate of the current position.

See also

getmaxx, getmaxy, getviewsettings, gety, moveto

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcodei
char msg[80]i
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
print f ( nPress any key to halt: n) ;
getch () ;
exit(l);
/* terminate with an error code */
/* move to the screen center point */
moveto(getmaxx() / 2, getmaxy() / 2);
/* create a message string */
sprintf(msg, n<-(%d, %d) is the here. n, getx(), gety());
/* display the message */
outtext (msg) ;
/* clean up */
getch () ;

266

Borland C++ Library Reference

getx

closegraph ( ) ;
return 0;

gety
I

Function
Syntax

Remarks
Return value

Returns the current graphics position's y-coordinate.

I

•

#inc1ude 
int far gety(void);

gety returns the current graphics position's y-coordinate. The value is
viewport-relative.
gety returns the y-coordinate of the current position.

See also

getmaxx, getmaxy, getviewsettings, getx, moveto

Example

hncl ude
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
char msg[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf ("Graphics error: %s\n", grapherrormsg (errorcode)) ;
printf (" Press any key to halt:") ;
getch();
exit(l);
/* terminate with an error code */
/* move to the screen center point */
moveto(getmaxx() / 2, getmaxy() / 2);
/* create a message string */
sprintf(msg, "<-(%d, %d) is the here.", getx(), gety());

Chapter 2, The run-time library

267

I

gety

/* display the message */
outtext (msg) i
/* clean up */
getch() ;
closegraph () i
return 0 i

gmtime
Function
Syntax

Remarks

Converts date and time to Greenwich mean time (GMT).
#include 
struct tm *gmtime(const time_t *timer);

gmtime accepts the address of a value returned by time and returns a
pointer to the structure of type tm containing the broken-down time.
gmtime converts directly to GMT.

The global long variable timezone should be set to the difference in
seconds between GMT and local standard time (in PST, timezone is
8x60x60). The global variable daylight should be set to nonzero only if the
standard U.S. daylight saving time conversion should be applied.
The tm structure declaration from the time.h include file is
struct
int
int
int
int
int
int
int
int
int

tm {
tm_seCi
tm_min;
tm_houri
tm_mday;
tm_mon;
tm-year;
tm_wdaYi
tm-yday;
tm_isdsti

/*
/*
/*
/*
/*
/*
/*
/*
/*

Seconds */
Minutes */
Hour (0 - 23) */
Day of month (1 - 31) */
Month (0 - 11) */
Year (calender year minus 1900) */
Weekday (0 - 6; Sunday is 0) */
Day of year (0 -365) */
Nonzero if daylight saving time is in effect. */

}i

These quantities give the time on a 24-hour clock, day of month (1 to 31),
month (0 to 11), weekday (Sunday equals 0), year -1900, day of year (0 to
365), and a flag that is nonzero if daylight saving time is in effect.

268

Borland C++ Library Reference

gmtime

Return value

gmtime returns a pointer to the structure containing the broken-down

time. This structure is a static that is overwritten with each call.
See also

asctime, ctime, ftime, localtime, stime, time, tzset

Example

#include
#include
#include
#include






I

I

•

/* pacific standard & daylight savings time */
char *tzstr = "TZ=PST8PDT";
int main (void)
{

time_t t;
struct tm *gmt, *area;
putenv (tzstr) ;
tzset();
t = time (NULL) ;
area = localtime(&t);
printf("Local time is: %s", asctime(area));
gmt = gmtime(&t);
%s", asctime(gmt));
printf("GMT is:

,

I

return 0;

gotoxy
Function
Syntax

Remarks

Return value

Positions cursor in text window.
#include 
void gotoxy(int x, int y);

gotoxy moves the cursor to the given position in the current text window.
If the coordinates are in any way invalid, the call to gotoxy is ignored. An
example of this is a call to gotoxy(40,30), when (35,25) is the bottom right
position in the window.

None.

See also

wherex, wherey, window

Example

#include 

Chapter 2, The run-time library

;

269

gotoxy

int main(void)
{

clrscr () ;
gotoxy(35, 12);
cprintf ("Hello world") ;
getch () ;
return 0;

graphdefaults
Function
Syntax

Remarks

Resets all graphics settings to their defaults.
#inc1ude 
void far graphdefaults(void);

graphdefaults resets all graphics settings to their defaults:

• sets the viewport to the entire screen.
• moves the current position to (0,0).
• sets the default palette colors, background color, and drawing color.
• sets the default fill style and pattern.
iii

Return value

sets the default text font and justification.

None.

See also

initgraph, setgraphmode

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();

270

Borland C++ Library Reference

graphdefaults

if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */
I

maxx
maxy

= getmaxx();
= getmaxy();

I

•

/* output line with nondefault settings */
setlinestyle(DOTTED_LINE, 0, 3);
line(O, 0, maxx, maxy);
outtextxy (maxx/2, maxy /3, "Before default values are restored.");
getch() ;
/* restore default values for everything */
graphdefaults () ;
/* clear the screen */
cleardevice () ;
/* output line with default settings */
line(O, 0, maxx, maxy);
outtextxy(maxxl2, maxy/3, "After restoring default values.");
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

grapherrormsg
Function
Syntax

Remarks

Returns a pointer to an error message string.
#include 
char * far grapherrormsg(int errorcode);

grapherrormsg returns a pointer to the error message string associated
with errorcode, the value returned by graphresult.

Refer to the entry for errno in Chapter 3 ("Global variables") for a list of
error messages and mnemonics.
Return value

grapherrormsg returns a pointer to an error message string.

Chapter 2, The run-time library

271

I

grapherrormsg

See also

graph result

Example

#include
#include
#include
#include






#define NONSENSE -50
int main(void)
{

/* force an error to occur */
int gdriver = NONSENSE, gmode, errorcode;
/* initialize graphics mode */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
/* if an error occurred, then output descriptive error message */
if (errorcode != grOk) {
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */

/* draw a line */
line(O, 0, getmaxx(), getmaxy());
/* clean up */
getch() ;
closegraph () ;
return 0;

_graphfreemem
Function
Syntax

272

User hook into graphics memory deallocation.
#include 
void far _graphfreemem(void far *ptr, unsigned size);

Borland C++ Library Reference

_graphfreemem

Remarks

Return value

The graphics library calls _graphfreemem to release memory previously·
allocated through _graphgetmem. You can choose to control the graphics
library memory management by simply defining your own version of
_graphfreemem (you must declare it exactly as shown in the declaration).
The default version of this routine merely calls free.
None.

See also

_graphgetmem, setgraphbufsize

Example

#include
#include
#include
#include
#include

I

I







I

int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode, midx, midy;

/* clear the text screen */
clrscr () ;
printf("Press any key to initialize graphics mode:");
getch() ;
clrscr () ;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
print f ( "Graphics error: %s \n", grapherrormsg (errorcode) ) ;
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */

midx = getmaxx() / 2;
midy = getmaxy() / 2;
/* display a message */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, "Press any key to exit graphics mode:");
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

Chapter 2, The run-time library

273

_graphfreemem

1* called by the graphics kernel to allocate memory *1
void far * far _graphgetmem(unsigned size) {
printf ("_graphgetmem called to allocate %d bytes. \n ", size);
printf("hit any key:");
getch() ;
printf (" \n");
1* allocate memory from far heap *1
return farmalloc(size) i
1* called by the graphics kernel to free memory *1
void far _graphfreemem(void far *ptr, unsigned size)
printf ("_graphfreemem called to free %d bytes. \n", size);
printf ("hit any key: ");
getch () i
printf("\n") i
1* free ptr from far heap *1
farfree (ptr)

i

_graphgetmem
Function

User hook into graphics memory allocation.

Syntax

#include 
void far * far _graphgetmem(unsigned size);

Remarks

Routines in the graphics library (not the user program) normally call
_graphgetmem to allocate memory for internal buffers, graphics drivers,

and character sets. You can choose to control the memory management of
the graphics library by defining your own version of _graphgetmem (you
must declare it exactly as shown in the declaration). The default version of
this routine merely calls malloe.
Return value

274

None.

See also

_graphfreemem, initgraph, setgraphbufsize

Example

#include
#include
#include
#include
#include







Borland C++ Library Reference

_graphgetmem

int main(void)
/* request autodetection */
int gdriver = DETECT, gmode, errorcode, midx, midYi
/* clear the text screen */
clrscr () i
printf("Press any key to initialize graphics mode:");
getch () ;
clrscr () ;

I

•

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /} an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode))i
printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */
midx
midy

= getmaxx() / 2;
=

getmaxy() / 2;

/* display a message */
settextjustify(CENTER_TEXT, CENTER_TEXT)i
outtextxy(midx, midy, "Press any key to exit graphics mode: ");
/* clean up */
getch() ;
closegraph ( ) ;
return 0;
/* called by the graphics kernel to allocate memory */
void far * far _graphgetmem(unsigned size) {
printf ("_graphgetmem called to allocate %d bytes. \n", size);
printf ("hit any key:");
getch () ;
printf ("\n");
/* allocate memory from far heap */
return farmalloc(size);

/* called by the graphics kernel to free memory */
void far _graphfreemem(void far *ptr, unsigned size)
printf ("_graphfreemem called to free %d bytes. \n", size);
printf("hit any key:");
getch () ;

Chapter 2, The run-time library

275

I

_graphgetmem

printf ("\n") i

/* free ptr from far heap */
farfree (ptr) i

graphresult
Function
Syntax

Remarks

Returns an error code for the last unsuccessful graphics operation.
#include 
int far graphresult(void);

graphresult returns the error code for the last graphics operation that
reported an error and resets the error level to grOk.

The following table lists the error codes returned by graphresult. The
enumerated type graph_errors defines the errors in this table. graph_errors
is declared in graphics.h.
Error
code

graphics_errors
constant

Corresponding error message string

o

grOk
grNoInitGraph

No error
(BGl) graphics not installed (use

grN otDetected
grFileN otFound
grInvalidDriver
grNoLoadMem
grNoScanMem
grN oFloodMem
grFontNotFound
igrNoFontMem
grInvalidMode

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
Graphics I/O error
Invalid font file
Invalid font number
Invalid device number
Invalid version number

-1

initgraph)

-2
-3
-4

-5
-6

-7
-8
-9
-10

-11
-12
-13
-14
-15
-18

276

grError
grIOerror
grIn validFont
grInvalidFontNum
grInvalidDeviceNum
grInvalidVersion

Borland C++ Library Reference

graphresult

Note that the variable maintained by graphresult is reset to 0 after
graphresult has been called. Therefore, you should store the value of
graphresult into a temporary variable and then test it.
Return value

graph result returns the current graphics error number, an integer in the
range -15 to 0; grapherrormsg returns a pointer to a string associated with
the value returned by graphresult.

See also

detectgraph, drawpoly, fillpoly, floodfill, grapherrormsg, initgraph,
pieslice, registerbgidriver, registerbgifont, setallpalette, setcolor,
setfillstyle, setgraphmode, setlinestyle, setpalette, settextjustify,
settextstyle, setusercharsize, setviewport, setvisualpage

Example

#include
#include
#include
#include

I

•
.






int main (void)
(

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;

/* initialize graphics and local variables *;
initgraph(&gdriver, &gmode, 1111);
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */

print f ( I Graphics error: %s \n ", grapherrormsg (errorcode) ) ;
printf(IIPress any key to halt:");
getch();
exit(l);
/* terminate with an error code */
/* draw a line */
line(O, 0, getmaxx(), getmaxy());
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

Chapter 2, The run-time library

I

277

I

harderr, hardresume, hardretn

harderr, hardresume, hardretn
Function
Syntax

Remarks

Establishes and handles hardware errors.
#include 
void harderr(int (*handler)O);
void hardresume(int axret);
void hardretn(int retn);

The error handler established by harderr can call hard resume to return to
DOS. The return value of the rescode (result code) of hardresume contains
an abort (2), retry 0), or ignore (0) indicator. The abort is accomplished by
invoking DOS interrupt Ox23, the control-break interrupt.
The error handler established by harderr can return directly to the
application program by calling hardretn. The returned value is whatever
value you passed to hardretn.
harderr establishes a hardware error handler for the current program.
This error handler is invoked whenever an interrupt Ox24 occurs. (See
your DOS reference manuals for a discussion of the interrupt.)

The function pointed to by handler is called when such an interrupt occurs.
The handler function is called with the following arguments:
handler(int errval, int ax, int bp, int si);

errval is the error code set in the DI register by DOS. ax, bp, and si are the
values DOS sets for the AX, BP, and SI registers, respectively .
• ax indicates whether a disk error or other device error was encountered.
If ax is nonnegative, a disk error was encountered; otherwise, the error
was a device error. For a disk error, ax ANDed with OxOOFF gives the
failing drive number (0 equals A, 1 equals B, and so on) .
• bp and si together point to the device driver header of the failing driver.
bp contains the segment address, and si the offset.
The function pointed to by handler is not called directly. harderr
establishes a DOS interrupt handler that calls the function.

278

Borland C++ Library Reference

harderr, hardresume, hardretn

The handler can issue DOS calls 1 through OxC; any other DOS call
corrupts DOS. In particular, any of the C standard I/O or UNIXemulation I/O calls cannot be used.
The handler must return 0 for ignore, 1 for retry, and 2 for abort.
Return Value

None.

See also

peek, poke

Example

/* This program will trap disk errors and prompt the user for action. Try running
it with no disk in drive A: to invoke its functions.
*/

#include 
#include 
#include 
#define IGNORE
#define RETRY
#define ABORT
int buf[500);
/* Define the error messages for trapping disk problems. */
static char *err_msg[) = {
"write protect",
"unknown unit",
"drive not ready",
"unknown cornmand" ,
"data error (CRC) ",
"bad request",
"seek error",
"unknown media type",
"sector not found",
"printer out of paper",
"write fault",
"read fault",
"general failure",
"reserved" ,
"reserved" ,
"invalid disk change"
};

error_win(char *msg)
{

int retval;
cputs (msg) ;
/* Prompt for user to press a key to abort, retry, ignore. */
while(l) {
retval= getch ( ) ;

Chapter 2, The run-time library

279

•

harderr, hardresume, hardretn

if (retval

retval
break;

--

'A' ) {

'a' II retval

= ABORT;

if (retval
retval
break;

= RETRY;

'r' II retval

if (retval

--

'i' II retval

'R' ) {

'I' )

{

ret val
break;

= IGNORE;

return (retval) ;
/*

pragma warn -par reduces warnings which occur
due to the non use of the parameters errval,
bp and si to the handler.
*/

#pragma warn -par
int handler(int errval,int aX,int bp,int si)
{

static char msg[80l;
unsigned di;
int drive;
int errorno;
/*

if this is not a disk error then it was
another device having trouble
*/

if (ax < 0)
{

/* report the error */
error_win ("Device error");
/* and return to the program directly requesting abort */
hardretn(ABORT);

/* otherwise it was a disk error */

drive = ax & OxOOFF;
errorno = di & OxOOFF;
/* report which error it was */
sprintf(msg, "Error: %8 on drive %c\r\nA)bort, R)etry, I)gnore: "

280

Borland C++ Library Reference

harderr, hardresume, hardretn

err_msg[errorno), 'A' + drive);
/*

return to the program via dos interrupt Ox23 with abort, retry,
or ignore as input by the user.
*/

hardresume(error_win(msg));
return ABORT;
#pragma warn +par
int main(void)

I

{

/*

install our handler on the hardware problem interrupt
*/

harderr(handler);
clrscr () ;
printf("Make sure there is no disk in drive A:\n");
print f ( "Press any key .... \n" ) ;
getch() ;
printf ("Trying to access drive A: \n");
printf("fopen returned %p\n",fopen("A:temp.dat", Ow"));
return 0;

I

_harderr
Function
Syntax

Establishes a hardware error handler.
#include 
void _harderr(int (far *handler)O);
DOS

Remarks

UNIX

Wi ndows

ANS I C

_harderr establishes a hardware error handler for the current program.
This error handler is invoked whenever an interrupt Ox24 occurs. (See

your DOS reference manuals for a discussion of the interrupt.)
The function pointed to by handler is called when such an interrupt occurs.
The handler function is called with the following arguments:
void far handler (unsigned deverr, unsigned errval, unsigned far *devhdr);

• deverr is the device error code (passed to the handler by DOS in the AX
register) .

• errval is the error code (passed to the handler by DOS in the 01 register).

Chapter 2, The run-time library

281

_harderr

• devhdr a far pointer to the driver header of the device that caused the
error (passed to the handler by DOS in the BP:SI register pair).
The handler should use these arguments instead of referring directly to
the CPU registers.

deverr indicates whether a disk error or other device error was
encountered. If bit 15 of deverr is 0, a disk error was encountered.
Otherwise, the error was a device error. For a disk error, deverr ANDed
with OxOOFF give the failing drive number (0 equals A, 1 equals B, and so
on).
The function pointed to by handler is not called directly. _harderr
establishes a DOS interrupt handler that calls the function.
The handler can issue DOS calls 1 through OxC; any other DOS call
corrupts DOS. In particular, any of the C standard I/O or UNIXemulation I/O calls cannot be used.
The handler does not return a value, and it must exit using _hardretn or
_hard resume.
Return Value

None.

See also

_hardresume, _hardretn

Example

/* This program traps disk errors and prompts the user for action. */
/* Try running it with no disk in drive A to invoke its functions. */
#include
#include
#include
#include






int buf[500];
/* Define the error messages for trapping disk problems. */
static char *err_msg[] =
{

"wri te protect",
"unknown unit",
"drive not ready", "unknown command",
"data error (CRC) ", "bad request",
"unknown media type",
"seek error",
"sector not found", "printer out of paper",
"read fault",
"write fault",
"general failure", "reserved",
"invalid disk change"
"reserved",
};

static void mesg(char *s)
{

282

Borland C++ Library Reference

_harderr

while (*s)
bdos (2, *s++, 0);
static int getkey(void)
return (bdos(7, 0, 0) & Oxff);
error_win(char *msg)
{

int c;

I

1* Prompt user to press a key to abort, retry, ignore, fail. *1
while(l) {
mesg (msg) ;
c = tolower(getkey()) i
mesg("\r\n");
switch (c) {
case 'a':
return (_HARDERR_ABORT);
case 'r':
return (_HARDERR_RETRY) ;
case 'i' :
return (_HARDERR_IGNORE) ;
case 'f':
return (_HARDERR_FAIL) ;

,

:

1* Pragma warn -par reduces warnings which occur due to the nonuse of the
parameter devhdr *1
#pragma warn -par
void far handler(unsigned deverr, unsigned errval,
unsigned far *devhdr)
static char msg[80];
int drive, errorno;

1* If this not disk error then another device having trouble. *1
if (deverr & Ox8000) {
error_win(IIDevice error"); 1* report the error *1
1* return to the program directly requesting abort *1
_hardretn (5) ;
1* 5 = DOS I access denied I error *I
drive = deverr & OxOOFF;
errorno = errval & OxOOFF;

1* otherwise it was disk error *1

1* report which error it was *1

Chapter 2, The run-time library

283

_harderr

sprintf(msg, "Error: %s on drive %c\r\nA)bort, R)etry,
I)gnore, F)ail: ",
err_msg[errornoJ, 'A' + drive);
/* Return to program via dos interrupt Ox23 with abort, retry or ignore as
input by the user */

_hardresume(error_win(msg));
#pragma warn +par
int main (void)
{

int handle;
/* Install our handler on the hardware problem interrupt. */
_harderr(handler) ;
printf("Make sure there is no disk in drive A:\n");
print f ( Press any key .... \n ") ;
getkey() ;
print f ( Trying to access drive A: \n ") ;
printf (" _dos_open returned Ox%x\n
_dos_open ("A:temp.dat" , O_RDONLY, &handle));
return 0;
II

II

II ,

_hardresume
Function
Syntax

Remarks

284

Hard ware error handler.
#include 
void _hardresume(int rescode);

The error handler established by _harderr can call _hardresume to return
to DOS. The return value of the res code (result code) of _hardresume
contains one of the following values:
_HARDERR_ABORT

Abort the program by invoking DOS interrupt
Ox23, the control-break interrupt.

_HARDERR_IGNORE

Ignore the error.

_HARDERR_RETRY

Retry the operation.

_HARDERR_FAIL

Fail the operation.

Bor/and C++ Library Reference

_hardresume

Return Value

The _hardresume function does not return a value, and does not return to
the caller.

See also

_harderr, _hardretn

Example

See the example for _harderr.

_hardretn
Function

Hardware error handler.

Syntax

#include 
void _hardretn(int retn);

Remarks

•

The error handler established by _harderr can return directly to the
application program by calling _hardretn.
If the DOS function that caused the error is less than Ox38, and it is a
function that can indicate an error condition, then _hardretn will return to
the application program with the AL register set to OxFF. The retn
argument is ignored for all DOS functions less than Ox38.
If the DOS function is greater than or equal to Ox38, the retn argument
should be a DOS error code; it is returned to the application program in
the AX register. The carry flag is also set to indicate to the application that
the operation resulted in an error.

Return Value

The _hard resume function does not return a value, and does not return to
the caller.

See also

_harderr, _hardresume

Example

See the example for _harderr.

heapcheck
Function
Syntax

Checks and verifies the heap.
#include 
int heapcheck(void);

Chapter 2, The run-time library

285

heapcheck

Remarks

Return Value

heapcheck walks through the heap and examines each block checking its
pointers, size, and other critical attributes. In the large data models,
heapcheck maps to farheapcheck.

The return value is less than zero for an error and greater than zero for
success. The return values and their meaning is as follows:

_HEAPEMPTY
_HEAPOK
_HEAPCORRUPT
See also

farheapcheck

Example

#include 
#include 

no heap (value 1).
heap is verified (value 2).
heap has been corrupted (value -1).

#define NUM_PTRS 10
#define NUM_BYTES 16
int main(void)
{

char *array[ NUM_PTRS 1;
int i;
for( i = 0; i < NUM_PTRS; itt
array [ i 1 = (char *) malloc( NUM_BYTES );
for( i = 0; i < NUM_PTRS; i t= 2 )
free( array[ i 1 );
if( heapcheck() == _HEAPCORRUPT )
printf ( "Heap is corrupted. \n" );
else
printf ( "Heap is OK. \n" ) i
return 0;

heapcheckfree
Function
Syntax

286

Checks the free blocks on the heap for a constant value.
#include 
int heapcheckfree(unsigned int fillvalue);

Borland C++ Library Reference

heapcheckfree

Return Value

The return value is less then zero for an error and greater than zero for
success. The return values and their meaning is as follows:

HEAPEMPTY
HEAPOK
_HEAPCORRUPT
- BADVALUE
-

no heap (value 1).
heap is accurate (value 2).
heap has been corrupted (value -1).
a value other than the fill value was found (value
-3).

See also

farheapcheckfree

Example

#include 
#include 
#include 

II

#define NUM_PTRS 10
#define NUM_BYTES 16
int main(void)
{

char *array[ NUM_PTRS ];
int i, res;
for( i = 0; i < NUM_PTRS; i++
array [ i ] = (char *) malloc( NUM_BYTES );
for( i = 0; i < NUM_PTRS;
+= 2 )
free( array [ i ] );
if( heapfillfree( 1 ) < 0 ) {
printf( "Heap corrupted.\n" );
return 1;
for( i = 1; i < NUM_PTRS; i += 2 )
memset( array [ i ], 0, NUM_BYTES );
res = heapcheckfree( 1 );
if( res < 0 )
switch( res) {
case _HEAPCORRUPT:
printf( "Heap corrupted. \n" );
return 1;
case _BADVALUE:
printf( "Bad value in free space.\n" );
return 1;
default:
printf ( "Unknown error. \n" );
return 1;
printf( "Test successful.\n" );
return 0;

Chapter 2, The run-time library

287

heapchecknode

heapchecknode
Function
Syntax

Remarks

Return Value

Checks and verifies a single node on the heap.
#include 
int heapchecknode(void *node);

If a node has been freed and heapchecknode is called with a pointer to
the freed block, heapchecknode can return _BADNODE rather than the
expected _FREEENTRY. This is because adjacent free blocks on the heap
are merged, and the block in question no longer exists.
The return value is less than zero for an error and greater than zero for
success. The return values and their meaning is as follows:
_HEAPEMPTY
_HEAPCORRUPT
_BADNODE
_FREEENTRY
_USEDENTRY

See also

farheapchecknode

Example

#include 
#include 

no heap (value 1).
heap has been corrupted (value -1).
node could not be found (value -2).
node is a free block (value 3).
node is a used block (value 4).

#define NUM_PTRS 10
#define NUM_BYTES 16
int main(void)
{

char *array[ NUM_PTRS 1;
int i;
for( i = 0; i < NUM_PTRS; itt
array [ i 1 = (char *) malloc( NUM_BYTES );
for( i = 0; i < NUM_PTRS; i t= 2 )
free( array [ i 1 );
for( i = 0; i < NUM_PTRS; itt) {
printf ( "Node %2d ", i );
switch( heapchecknode( array [ i 1 ) ) {
case _HEAPEMPTY:
printf( "No heap.\n" );
break;
case _HEAPCORRUPT:
printf( "Heap corrupt.\n" );

288

Borland C++ Library Reference

heapchecknode

break;
case _BADNODE:
printf( "Bad node.\n" );
break;
case _FREEENTRY:
printf ( "Free entry. \n" );
break;
case _USEDENTRY:
printf( "Used entry.\n" );
break;
default:
printf ( "Unknown return code. \n" );
break;

•

return 0;

I

I

heapfillfree
Function
Syntax

Return Value

I

Fills the free blocks on the heap with a constant value.
#include 
int heapfillfree(unsigned int fillvalue);

The return value is less than zero for an error and greater than zero for
success. The return values and their meaning is as follows:

_HEAPEMPTY
_HEAPOK
_HEAPCORRUPT
See also

farheapfillfree

Example

#include 
#include 
#include 

no heap (value 1).
heap is accurate (value 2).
heap has been corrupted (value -1).

#define NUM_PTRS 10
#define NUM_BYTES 16
int mairi(void)
{

char *array[ NUM_PTRS 1;
int i, res;

Chapter 2, The run-time library

289

heapfillfree

for( i = 0; i < NUM_PTRS; itt)
array [ i 1 = (char *) rnalloc( NUM_BYTES );
t= 2 )
for( i = 0; i < NUM_PTRS;
free( array [ i 1 );
if( heapfillfree( 1 ) < 0 ) {
printf( "Heap corrupted.\n" );
return 1;
for( i = 1; i < NUM_PTRS; i t= 2 )
rnernset( array [ i l, 0, NUM_BYTES );
res = heapcheckfree( 1 );
if( res < 0 )
switch( res) {
case _HEAPCORRUPT:
printf( "Heap corrupted.\n" );
return 1;
case _BADVALUE:
printf( "Bad value in free space.\n" );
return 1;
default :
printf ( "Unknown error. \n" );
return 1;
printf( "Test successful.\n" );
return 0;

heapwalk
Function
Syntax

heapwalk is used to "walk" through the heap, node bynode.

#include 
int heapwalk(struct heapinfo *hi);
DOS

Remarks

heapwalk assumes the heap is correct. Use heapcheck to verify the heap
,before using heapwalk. _HEAPOK is returned with the last block on the
heap. _HEAPEND will be returned on the next call to heapwalk.
heapwalk receives a pointer to a structure of type heapinfo (declared in
alloc.h). For the first call to heapwalk, set the hLptr field to null. heapwalk
returns with hi.ptr containing the address of the first block. hi.size holds
the size of the block in bytes. hi.in_use is a flag that's set if the block is
currently in use.

290

Borland C++ Library Reference

heapwalk

Return Value

The return values and their meaning is as follows:

_HEAPEMPTY
_HEAPOK
_HEAPEND
See also

farheapwalk

Example

#inc1ude 
#include 

no heap (value 1).
heapinfo block contains valid data (value 2).
end of the heap has been reached (value 5).

#define NUM_PTRS 10
#define NUM_BYTES 16
int main( void)
{

struct heapinfo hi;
char *array[ NUM_PTRS l;
int i;
for( i = 0; i <
array [ i 1 =
for( i = Oi i <
free ( array [

NUM_PTRSi itt
(char *) malloc( NUM_BYTES );
NUM_PTRSi i t= 2 )
i 1 )i

hi.ptr = NULL;
printf ("
Size Status\n");
printf( "
------\n" )i
while( heapwalk( &hi ) == _HEAPOK )
%s\n", hi.size, hi.in_use
printf( "%7u
return 0i

"used"

"free")i

highvideo
Function
Syntax

Remarks

Selects high-intensity characters.
#include 
void highvideo(void);

highvideo selects high-intensity characters by setting the high-intensity bit
of the currently selected foreground color.

Chapter 2, The run-time library

291

highvideo

This function does not affect any characters currently on the screen, but
does affect those displayed by functions (such as cprintf) that perform
direct video, text mode output after highvideo is called.
Return Value

None.

See also

cprintf, cputs, gettextinfo, lowvideo, normvideo, textattr, textcolor

Example

#include 
int main (void)
{

clrscr () ;
lowvideo();
cprintf("Low Intensity text\r\n");
highvideo();
gotoxy(l,2);
cprintf("High Intensity Text\r\n");
return 0;

hypot hypotl
I

Function
Syntax

Calculates hypotenuse of a right triangle.
#include 
double hypot(double x, double y);
long double hypotlOong double X, long double y);
DOS

hypof

•

hypofl

•

Remarks

UNIX

•

Windows

ANSI C

C++ only

•
•

hypot calculates the value z where
Z2=X2 +y2

and

z >=0
This is equivalent to the length of the hypotenuse of a right triangle, if the
lengths of the two sides are X and y.
hyptol is the long double version; it takes long double arguments and
returns a long double result.

292

Borland C++ Library Reference

hypot, hypotl

Return Value

On success, these functions return z, a double (hypot) or a long double)
(hypotl). On er~or (such as an overflow), they set the global variable errno
to
ERANGE

Result out of range
i

and return the value HUGE_VAL (hypot) or _LHUGE_VAL) (hypotl).

I

Error handling for these routines can be modified through the functions
matherr and _matherrl.
Example

I

#include 
#include 

•

int main(void)
{

double result, x

= 3.0, y = 4.0;

result = hypot(x, y)i
printf("The hypotenuse is: %If\n'', result);
return 0;

imag
Function
Syntax

Remarks

Return Value

I

Returns the imaginary part of a complex number.
#include 
double imag(complex x);

The data associated to a complex number consists of two floating-point
(double) numbers. imag returns the one considered to be the imaginary
part.
The imaginary part of the complex number.

See also

complex, conj, real

Example

#include 
int main (void)
{

double x = 3.1, Y = 4.2;
complex z = complex(x,y);
cout « "z = " « Z « "\n";
cout «" has real part = " « real(z) « "\n";

Chapter 2, The run-time library

293

I

imag

cout «" and imaginary real part = " « imag(z) « "\n";
cout « "z has complex conjugate = " « conj (z) « "\n";
return 0;

imagesize
Function
Syntax

Remarks

Return Value

Returns the number of bytes required to store a bit image.
#include 
unsigned far imagesize(int left, int top, int right, int bottom);

imagesize determines the size of the Iflemory area required to store a bit
image. If the size required for the selected image is greater than or equal
to 64K -1 bytes, imagesize returns OxFFFF (-1).
imagesize returns the size of the required memory area in bytes.

See also

getimage, putimage

Example

#include
#include
#include
#include






#define ARROW_SIZE 10
void draw_arrow(int x, int y);
int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
void *arrow;
int x, y, maxx;
unsigned int size;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, ""I;
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf (" Press any key to halt:");
getch() ;

294

Borland C++ Library Reference

imogesize

exit(l) ;

/* terminate with an error code */

maxx = getmaxx();
x 0;
y = getmaxy() / 2;
/* draw the image to be grabbed */
draw_arrow (x, y);
/* calculate the size of the image */
size = imagesize(x, y-ARROW_SIZE, xt(4*ARROW_SIZE), ytARROW_SIZE);
/* allocate memory to hold the image */
arrow = malloc(size);

•

/* grab the image */
get image (x, y-ARROW_SIZE, xt(4*ARROW_SIZE), ytARROW_SIZE, arrow);
/* repeat until a key is pressed */
while (!kbhit()) {
/* erase old image */
put image (x, y-ARROW_SIZE, arrow, XOR_PUT);
x t= ARROW_SIZE;
if (x >= maxx)
x = 0;
/* plot new image */
put image (x, y-ARROW_SIZE, arrow, XOR_PUT);
/* clean up */
free (arrow) ;
closegraph ( ) ;
return 0;
void draw_arrow(int

x,

int y)

{

/* draw an arrow on the screen */
moveto (x, y);
linerel(4*ARROW_SIZE, 0);
linerel(-2*ARROW_SIZE, -l*ARROW_SIZE);
linerel(O, 2*ARROW_SIZE);
linerel(2*ARROW_SIZE, -l*ARROW_SIZE);

initgraph
Function

Initializes the graphics system.

Chapter 2, The run-time library

295

initgraph

Syntax

Remarks

#include 
void far initgraph(int far *graphdriver, int far *graphmode,
char far *pathtodriver);

initgraph initializes the graphics system by loading a graphics driver from
disk (or validating a registered driver), and putting the system into
graphics mode.

To start the graphics system, first call the initgraph function. initgraph
loads the graphics driver and puts the system into graphics mode. You
can tell initgraph to use a particular graphics driver and mode, or to
autodetect the attached video adapter at run time and pick the
corresponding driver.
If you tell initgraph to autodetect, it calls detectgraph to select a graphics
driver and mode. initgraph also resets all graphics settings to their
defaults (current position, palette, color, viewport, and so on) and resets
graphresult to O.

Normally, initgraph loads a graphics driver by allocating memory for the
driver (through _graphgetmem), then loading 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. See UTIL.DOC (included with your distribution disks) for
more information on BGIOBJ.

pathtodriver specifies the directory path where initgraph looks for graphics
drivers. initgraph first looks in the path specified in pathtodriver, then (if
they're not there) in the current directory. Accordingly, if pathtodriver is
null, the driver files (*.BGI) must be in the current directory. This is also
the path settextstyle searches for the stroked character font files (*.CHR).
*graphdriver is an integer that specifies the graphics driver to be used. You
can give it a value using a constant of the graphics_drivers enumeration
type, defined in graphics.h and listed in Table 2.3.

296

Borland C++ Library Reference

initgroph

Table 2.3
Graphics drivers
constants

graphics_ drivers
constant

DETECT
CGA
MCGA
EGA
EGA64
EGAMONO
IBM8514
HERCMONO
ATT400
VGA
PC3270

Numeric value

o (requests autodetection)
1
2

3
4
5
6
7
8
9
10

*graphmode is an integer that specifies the initial graphics mode (unless
*graphdriver equals DETECT; in which case, *graphmode is set by initgraph
to the highest resolution available for the detected driver). You can give

*graphmode a value using a constant of the graphics_modes enumeration
type, defined in graphics.h and listed in Table 2.5.
~

graphdriver and graph mode must be set to valid values from tables 2.3 and
2.5, or you'll get unpredictable results. The exception is graphdriver =
DETECT.
In Table 2.5, the Palette listings CO, C1, C2, and C3 refer to the four
predefined four-color palettes available on CGA (and compatible)
systems. You can select the background color (entry #0) in each of these
palettes, but the other colors are fixed. These palettes are described in
greater detail in Chapter II, "Video functions" in the Programmer's Guide
(in the section titled "Color control," toward the end of the chapter) and
summarized in Table 2.4.

Table 2.4
Color palettes

Color assigned to pixel value
Palette
number

o
1
2

3

2

LIGHTGREEN
LIGHTCYAN
GREEN
CYAN

LIGHTRED
LIGHTMAGENTA
RED
MAGENTA

3

YELLOW
WHITE
BROWN
LIGHTGRAY

After a call to initgraph, *graphdriver is set to the current graphics driver,
and *graphmode is set to the current graphics mode.

Chapter 2, The run-time library

297

•

initgroph

Table 2.5
Graphics modes

Graphics
driver

Column
graphics_modes

Value

xrow

Palette

Pages

CO
C1
C2
C3
2 color

1
1
1
1
1

CGA

CGACO
CGAC1
CGAC2
CGAC3
CGAHI

0
1
2
3
4

320x200
320x200
320x200
320x200
640x200

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
ATT400

HERCMONOHI
ATT400CO
ATT400C1
ATT400C2
ATT400C3
ATT400MED
ATT400HI

0
0
1
2
3
4
5

720x348
320x200
320x200
320x200
320x200
640x200
640x400

2 color
CO
C1
C2
C3
2 color
2 color

2
1
1
1
1
1
1

VGA

VGALO
VGAMED
VGAHI

0
1
2

640x200
640x350
640x480

16 color
16 color
16 color

2
2
1

PC3270

PC3270HI

0

720x350

2 color

1

IBM8514

IBM8514HI
IBM8514LO

1
0

1024x768
640x480

256 color
256 color

* 64K on EGAMONO card
** 256K on EGAMONO card
Return Value

initgraph always sets the internal error code; on success, it sets the code to
O. If an error occurred, *graphdriver is set to -2, -3, -4, or -5, and
graphresult returns the same value as listed here:

grNotDetected
grFileNotFound
grInvalidDriver
grNoLoadMem

298

-2
-3
-4

-5

Cannot detect a graphics card
Cannot find driver file
Invalid driver
Insufficient memory to load driver

Borland C++ Library Reference

inifgraph

See also

closegraph, detectgraph, getdefaultpalette, getdrivername,
getgraphmode, getmoderange, graphdefaults, _graphgetmem,
graphresult, installuserdriver, registerbgidriver, registerbgifont,
restorecrtmode, setgraphbufsize, setgraphmode

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;

•

/* initialize graphics mode */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();

if (errorcode

!=

grOk)

/* an error occurred */

{

printf ("Graphics error: %s\n", grapherrormsg (errorcode) );
print f ( "Press any key to halt:");
getch() ;
exit(l);
/* return with error code */
/* draw a line */
line(O, 0, getmaxx(), getmaxy());
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

inp
Function
Syntax

Reads a byte from a hardware port.
#include 
int inp(unsigned portid);

Chapter 2, The run-time library

299

inp

Remarks

inp is a macro that reads a byte from the input port specified by portid.

If inp is called when conio.h has been included, it will be treated as a
macro that expands to inline code. If you don't include conio.h, or if you
do include conio.h and #undef the macro inp, you get the inp function.
Return Value

inp returns the value read.

See also

inpw, outp, outpw

Example

#include 
#include 
int main(void}
{

int result;
unsigned port = 0;
result = inp(port};
printf("Byte read from port %d = Ox%X\n", port, result};
return 0;

inport
Function
Syntax

Remarks

Return Value

Reads a word from a hardware port.
#include 
int inport(int portid);

inport works just like the 80x86 instruction IN. It reads the low byte of a
word from the input port specified by portid; it reads the high byte from
portid + 1.
inport returns the value read.

See also

inportb, outport, outportb

Example

#include 
#include 
int main(void}
{

int result;
int port = 0;
result = inport(port};

300

Borland C++ Library Reference

inport

printf("Word read from port %d
return 0;

= Ox%X\n", port, result);

inportb
Function
Syntax

Reads a byte from a hardware port.
#include 
unsigned char inportb(int partid);
I

Remarks

inportb is a macro that reads a byte from the input port specified by partido

If inportb is called when dos.h has been included, it will be treated as a
macro that expands to inline code. If you don't include dos.h, or if you do
include dos.h and #undef the macro inportb, you get the inportb function.
Return Value

inportb returns the value read.

See also

inport, outport, outportb

Example

#inc1ude 
#include 
int main(void)
{

unsigned char result;
int port = 0;
result = inportb(port);
printf("Byte read from port %d
return 0;

= Ox%X\n", port, result);

inpw
Function
Syntax

Reads a word from a hardware port.
#include 
unsigned inpw(unsigned pOl'tid);

Chapter 2, The run-time library

301

•

I

I

inpw

Remarks

inpw is a macro that reads a 16-bit word from
the inport port specified by partido It reads the low byte of the word from
partid, and the high byte from partid + 1.

If inpw is called when conio.h has been included, it will be treated as a
macro that expands to inline code. If you don't include conio.h, or if you
do include conio.h and #undef the macro inpw, you get the inpw function.
Return Value

inpw returns the value read.

See also

inp, outp, outpw

Example

#include 
#include 
int main (void)
{

unsigned result;
unsigned port = 0;
result = inpw(port);
printf("Word read from port %d
return 0;

= Ox%X\n", port, result);

insline
Function
Syntax

Remarks

Inserts a blank line in the text window.
#include 
void insline(void);

insline inserts an empty line in the text window at the cursor position
using the current text background color. All lines below the empty one
move down one line, and the bottom line scrolls off the bottom of the
window.
insline is used in text mode.

Return Value

None.

See also

clreol, delline, window

Example

#include 
int main (void)

302

Borland C++ Library Reference

insline

clrscr () ;
cprintf("INSLINE inserts an empty line in the text window\r\n");
cprintf("at the cursor position using the current text\r\n");
cprintf("background color. All lines below the empty one\r\n");
cprintf (" move down one line and the bottom line scrolls\r\n");
cprintf("off the bottom of the window.\r\n");
cprintf("\r\nPress any key to continue: ") ;
gotoxy(l, 3);
getch() ;
insline();
getch() ;
return 0;

I

II

installuserdriver
Function
Syntax

Remarks

Installs a vendor-added device driver to the BGI device driver table.
#include 
int far installuserdriver(char far *name, int huge (*detect)(void»;

installuserdriver allows you to add a vendor-added device driver to the
BGI internal table. The name parameter is the name of the new device
driver file (.BGI), and the detect parameter is a pointer to an optional
autodetect function that can accompany the new driver. This autodetect
function takes no parameters and returns an integer value.

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 BGI device driver (SGA.BGI).
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.

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 this autodetect
function). When you install the driver (by calling installuserdriver), you
pass the address of this function, along with the device driver's file name.
After you install the device driver file name and the SGA autodetect
function, call initgraph and let it go through its normal autodetection

Chapter 2, The run-time library

303

installuserdriver

process. Before initgraph calls its built-in autodetection function
(detectgraph), it first calls the SGA autodetect function. If the SGA
autodetect function doesn't find the SGA hardware, it returns a value of
-11 (grError), and initgraph proceeds with its normal hardware detection
logic (which can include calling any other vendor-supplied autodetection
functions in the order in which they were "installed"). If, however, the
autodetect function determines that an SGA is present, it returns a nonnegative mode number; then initgraph locates and loads SGA.BGI, puts
the hardware into the default graphics mode recommended by the
auto detect function, and finally returns control to your program.
You can install up to ten drivers at one time.
Return Value

The value returned by installuserdriver is the driver number parameter
you would pass to initgraph in order to select the newly installed driver
manually.

See also

initgraph, registerbgidriver

Example

#include
#include
#include
#include






/* function prototypes */
int huge detectEGA(void);
void checkerrors(void);
int main(void)
{

int gdriver, gmode;
/* install a user written device driver */
gdriver = installuserdriver("EGA", detectEGA);
/* must force use of detection routine */
gdriver = DETECT;
/* check for any installation errors */
checkerrors() ;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* check for any initialization errors */
checkerrors();
/* draw a line */
line(O, 0, getmaxx(), getmaxy());
/* clean up */
getch() ;
closegraph () ;

304

Borland C++ Library Reference

installuserdriver

return 0;
/* detects EGA or VGA cards */
int huge detectEGA(void)
{

int driver, mode, sugmode = 0;
detectgraph(&driver, &mode);
if ((driver == EGA) II (driver == VGA))
return sugmode;
/* return suggested video mode number */
else
return grError;
/* return an error code */
I

•

/* check for and report any graphics errors */
void checkerrors(void)
{

int errorcode;
/* read result of last graphics operation */

errorcode = graphresult();
if (errorcode != grOk) {
printf(IIGraphics error: %s\n", grapherrormsg(errorcode));
printf(npress any key to halt:");
getch () ;
exit(l) ;

installuserfont
Function
Syntax

Loads a font file (.CHR) that is not built into the BGI system.
#include 
int far installuserfont(char far *name);
"

DOS

I

UNIX

I •I
Remarks

I

I

Windows

I

ANSI C

C++ only

I

name is a path name to a font file containing a stroked font. Up to twenty

fonts can be installed at one time.
Return Value

installuserfont returns a font ID number that can then be passed to
settextstyle to select the corresponding font. If the internal font table is

full, a value of -11 (grError) is returned.
See also

settextstyle

Chapter 2, The run-time library

305

installuserfont

Example

#include
#include
#include
#include






/* function prototype */
void checkerrors(void);
int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode;
int userfont;
int midx, midy;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

midx = getmaxx()
midy = getmaxy()

2;
2;

/* check for any initialization errors */
checkerrors();
/* install a user-defined font file */
userfont
installuserfont("USER.CHR");
/* check for any installation errors */
checkerrors ( ) ;

/* select the user font */
settextstyle(userfont, HORIZ_DIR, 4);
/* output some text */
outtextxy (midx, midy, "Testing!");

/ * clean up */
getch () ;
closegraph () ;
return 0;
/* check for and report any graphics errors */
void checkerrors(void)
{

int errorcode;
/* read result of last graphics operation */
errorcode = graphresult();
if (errorcode != grOk) {
printf ("Graphics error: %s\n", grapherrormsg (errorcode) ) ;
printf("Press any key to halt:");
getch() ;

306

Borland C++ Library Reference

installuserfont

exit (1) i

int86
Function
Syntax

Remarks

General 8086 software interrupt.
#include 
int int86(int intno, union REGS *inregs, union REGS *olltregs);

int86 executes an 8086 software interrupt specified by the argument intno.
Before executing the software interrupt, it copies register values from
inregs into the registers.

After the software interrupt returns, int86 copies the current register
values to olltregs, copies the status of the carry flag to the x.cflag field in
outregs, and copies the value of the 8086 flags register to the x.flags field in
outregs. If the carry flag is set, it usually indicates that an error has
occurred.
Note that inregs can point to the same structure that outregs points to.
Return Value

int86 returns the value of AX after completion of the software interrupt. If
the carry flag is set (out regs -> x. cflag ! = 0), indicating an error, this
function sets the global variable _doserrno to the error code.

See also

bdos, bdosptr, geninterrupt, int86x, intdos, intdosx, intr

Example

#include 
#include 
#include 
#define VIDEO Ox10
void movetoxy(int x, int y)
{

union REGS regsi
regs.h.ah =2i
regs.h.dh = Yi
regs.h.dl = Xi
regs.h.bh = Oi
int86 (VIDEO, ®s, ®s)i

Chapter 2, The run-time library

/* set cursor postion */

/* video page 0 */

307

•

int86

int main(void)
{

clrscr ();
movetoxy(35, 10);
printf("Hello\n");
return 0;

int86x
Function
Syntax

Remarks

General 8086 software interrupt interface.
#include 
int int86x(int intno, union REGS *inregs, union REGS *outregs,
struct SREGS *segregs);

int86x executes an 8086 software interrupt specified by the argument

intno. Before executing the software interrupt, it copies register values
from in regs into the registers.
In addition, int86x copies the segregs ->ds and segregs ->es values into the
corresponding registers before executing the software interrupt. This
feature allows programs that use far pointers or a large data memory
model tospecify which segment is to be used for the software interrupt.
After the software interrupt returns, int86x copies the current register
values to outregs, the status of the carry flag to the x.cflag field in outregs,
and the value of the 8086 flags register to the x.flags field in outregs. In
addition, int86x restores DS and sets the segregs ->es and segregs ->ds fields
to the values of the corresponding segment registers. If the carry flag is
set, it usually indicates that an error has occurred.
int86x lets you invoke an 8086 software interrupt that takes a value of DS
different from the default data segment, and/or takes an argument in ES.

Note that inregs can point to the same structure that outregs points to.
Return Value

308

int86x returns the value of AX after completion of the software interrupt.
If the carry flag is set (outregs -> x. cflag ! = 0), indicating an error, this
function sets the global variable _doserrno to the error code.

See also

bdos, bdosptr, geninterrupt, intdos, intdosx, int86, intr, segread

Example

#incl ude 

Borland C++ Library Reference

int86x

#include 
#include 
int main(void)
{

char filename[80j;
union REGS inregs, outregs;
struct SREGS segregs;
printf("Enter file name: ");
gets (filename) ;
inregs.h.ah = Ox43;
inregs.h.al = 0;
inregs.x.dx = FP_OFF(filename);
segregs.ds = FP_SEG(filename);
int86x(Ox2l, &inregs, &outregs, &segregs);
printf("File attribute: %X\n", outregs.x.cx);
return 0;

II

intdos
Function
Syntax

Remarks

General DOS interrupt interface.
#include 
int intdos(union REGS *inregs, union REGS *outregs);

intdos executes DOS interrupt Ox21 to invoke a specified DOS function.
The value of in regs -> h.ah specifies the DOS function to be invoked.

After the interrupt Ox21 returns, intdos copies the current register values
to outregs, copies the status of the carry flag to the x.cflag field in outregs,
and copies the value of the 8086 flags register to the x.flags field in outregs.
If the carry flag is set, it indicates that an error has occurred.
Note that in regs can point to the same structure that outregs points to.
Return Value

intdos returns the value of AX after completion of the DOS function call.
If the carry flag is set (outregs -> x.cflag != 0), indicating an error, it sets
the global variable _doserrno to the error code.

See also

bdos, bdosptr, geninterrupt, int86, int86x, intdosx, intr

Example

#include 
#include 

Chapter 2, The run-time library

309

intdos

/* deletes file name; returns 0 on success, nonzero on failure */
int delete_file (char near *filename)
{

union REGS regs;
int ret;
regs.h.ah = Ox4l;
regs.x.dx = (unsigned) filename;
ret = intdos(®s, ®s);

/* delete file */

/* if carry flag is set, there was an error */
return(regs.x.cflag? ret: 0);
int main(void)
{

int err;
err = delete_file("NOTEXIST.$$$");
if (!err)
printf("Able to delete NOTEXIST.$$$\n");
else
printf("Not able to delete NOTEXIST.$$$\n");
return 0;

intdosx
Function
Syntax

Remarks

General DOS interrupt interface.
#include 
int intdosxCunion REGS *inregs, union REGS *outregs,
struct SREGS *segregs);

intdosx executes DOS interrupt Ox21 to invoke a specified DOS function.
The value of inregs -> h.ah specifies the DOS function to be invoked.

In addition, intdosx copies the segregs ->ds and segregs ->es values into the
corresponding registers before invoking the DOS function. This feature
allows programs that use far pointers or a large data memory model to
specify which segment is to be used for the function execution.
After the interrupt Ox21 returns, intdosx copies the current register values
to outregs, copies the status of the carry flag to the x.cflag field in outregs,
and copies the value of the 8086 flags register to the x.flags field in outregs.
In addition, intdosx sets the segregs ->es and segregs ->ds fields to the

310

Borland C++ Library Reference

intdosx

values of the corresponding segment registers and then restores DS. If the
carry flag is set, it indicates that an error occurred.
intdosx lets you invoke a DOS function that takes a value of DS different
from the default data segment and/or takes an argument in ES.

Note that in regs can point tb the same structure that outregs points to.
Return Value

intdosx returns the value of AX after completion of the DOS function call.

If the carry flag is set (outregs -> x.cflag != 0), indicating an error, it sets
the global variable _doserrno to the error code.
See also

bdos, bdosptr, geninterrupt, int86, int86x, intdos, intr, segread

Example

#include 
#include 
/* deletes file name; returns 0 on success, nonzero on failure */
int delete_file(char far *filename)
{

union REGS regs; struct SREGS sregs;
int ret;
regs.h.ah = Ox41;
regs.x.dx = FP_OFF(filename);
sregs.ds = FP_SEG(filename);
ret = intdosx(®s, ®s, &sregs);

/* delete file */

/* if carry flag is set, there was an error */
return(regs.x.cflag ? ret: 0);
int rnain(void)
{

int err;
err = delete_file("NOTEXIST.$$$");
if (!err)
printf("Able to delete NOTEXIST.$$$\n");
else
printf ("Not Able to delete NOTEXIST. $$$\n");
return 0;

intr
Function

Alternate 8086 software interrupt interface.

Syntax

#include 
void intr(int intno, struct REGPACK *preg);

Chapter 2, The run-time library

311

intr

I
• I

II DOS

II
Remarks

UNIX

Wi ndows I ANSI C

•

I

C++ only

II
/I

The intr function is an alternate interface for executing software
interrupts. It generates an 8086 software interrupt specified by the
argument intno.
intr copies register values from the REGPACK structure *preg into the
registers before executing the software interrupt. After the software
interrupt completes, intr copies the current register values into *preg,
including the flags.

The arguments passed to intr are as follows:

intno

Interrupt number to be executed

preg

Address of a structure containing
(a) the input registers before the interrupt call
(b) the value of the registers after the interrupt call

The REGPACI< structure (defined in dos.h) has the following fornlat:
struct REG PACK {
unsigned r_ax, r_bx, r_cx, r_dx;
unsigned r_bp, r_si, r_di, r_ds, r_es, r_flags;
};

Return Value

No value is returned. The REGPACI( structure *preg contains the value of
the registers after the interrupt call.

See also

geninterrupt, int8G, int8Gx, intdos, intdosx

Example

#include 
#include 
#include 
#include 
#define CF 1 /* Carry flag */
int main(void)
{

char directory[80];
struct REGPACK reg;
printf("Enter directory to change to: ");
gets (directory) ;
/* shift 3Bh into AH */
reg.r_ax = Ox3B « 8;
reg.r_dx = FP_OFF(directory);
reg.r_ds = FP_SEG(directory);
intr(Ox21, ®);
if (reg.r_flags & CF)

312

Borland C++ Library Reference

intr

printf("Directory change failed\n");
getcwd(directory, 80);
printf("The current directory is: %s\n", directory);
return 0;

ioctl
Function
Syntax

Remarks

Controls I/O device.
#include 
int ioctl(int handle, int June [, void *argdx, int argcxD;

ioetl is available on UNIX systems, but not with these parameters or
functionality. UNIX version 7 and System III differ from each other in
their use of ioetl. ioetl calls are not portable to UNIX and are rarely
portable across DOS machines.

DOS 3.0 extends ioetl with June values of 8 and 11.

/

This is a direct interface to the DOS call Ox44 (IOCTL).
The exact function depends on the value of June as follows:

o
1
2
3
4
5
6
7
8
11

Get device information.
Set device information (in argdx).
Read argex bytes into the address pointed to by argdx.
Write argex bytes from the address pointed to by argdx.
Same as 2 except handle is treated as a drive number (0 equals
default, 1 equals A, and so on).
Same as 3 except handle is a drive number (0 equals default, 1
equals A, and so on).
Get input status.
Get output status.
Test removability; DOS 3.0 only.
Set sharing conflict retry count; DOS 3.0 only.

ioetl can be used to get information about device channels. Regular files
can also be used, but only June values 0, 6, and 7 are defined for them. All
other calls return an EINVAL error for files.

See the documentation for system call Ox44 in your DOS reference
manuals for detailed information on argument or return values.

Chapter 2, The run-time library

313

ioetl

The arguments argdx and argcx are optional.
ioetl provides a direct interface to DOS device drivers for special
functions. As a result, the exact behavior of this function varies across
different vendors' hardware and in different devices. Also, several
vendors do not follow the interfaces described here. Refer to the vendor
BIOS documentation for exact use of ioetl.
Return Value

For June 0 or I, the return value is the device information (OX of the
IOCTL call).
For June values of 2 through 5, the return value is the number of bytes
actually transferred.
For June values of 6 or 7, the return value is the device status.
In any event, if an error is detected, a value of -1 is returned, and the
global variable errno is set to one of the following:
EINVAL
EBADF
EINVDAT

Example

Invalid argument
Bad file number
Invalid data

#include 
#include 
#include 
int main(void)
{

int stat;
/*use func 8 to determine if the default drive is removable */
stat = ioctl(O, 8, a, 0);
if (!stat)
printf("Drive %c is removable.\n", getdisk() + 'A');
else
printf("Drive %c is not removable.\n", getdisk() + 'A');
return 0;

isalnum
Function
Syntax

314

Character classification macro.
#include 
int isalnum(int c);

Borland C++ Library Reference

isalnum

Remarks

isalnum is a macro that classifies ASCII-coded integer values by table
lookup. It is a predicate returning nonzero for true and 0 for false. It is
defined only when isascii(c) is true or c is EOF.

You can make this macro available as a function by undefining (#undef) it.
Return Value
Example

isalnum returns nonzero if c is a letter (A to Z or a to z) or a digit (0 to 9).
#include 
#include 
int main(void)
{

char c = 'c' i
if (isalnum(c))
printf("%c is alphanumeric\n",c) i
else
printf("%c isn't alphanumeric\n",c)
return 0 i

i

isalpha
Function
Syntax

Remarks

Character classification macro.
#include 
int isalpha(int c);

isalpha is a macro that classifies ASCII-coded integer values by table
lookup. It is a predicate returning nonzero for true and 0 for false. It is
defined only when isascii(c) is true or c is EOF.

You can make this macro available as a function by undefining (#undef) it.
Return Value
Example

isalpha returns nonzero if c is a letter (A to Z or a to z).
#incl ude 
#include 
int main (void)
{

char c = 'c'

Chapter 2, The run-time library

i

315

isalpha

if (isalpha(c))
printf("%c is alphabetic\n",c);
else
printf("%c isn't alphabetic\n",c);
return 0;

isascii
Function
Syntax

Remarks

Character classification macro.
#include 
int isascii(int c);

isascii is a macro that classifies ASCII-coded integer values by table
lookup. It is a predicate returning nonzero for true and 0 for false.
isascii is defined on all integer values.

Return Value
Example

isascii returns nonzero if the low order byte of c is in the range 0 to 127
(OxOO-Ox7F) .
#include 
#include 
int main(void)
{

char c = 'e';
if (isascii (c))
printf("%c is ascii\n",c);
else
printf("%c isn't ascii\n",c);
return 0;

isatty
Function
Syntax

316

Checks for device type.
#include 
int isatty(int handle);

Borland C++ Library Reference

isatty

DOS

Remarks

isatty determines whether handle is associated with anyone of the
following character devices:

c a terminal
c a console
c a printer
c a serial port
Return Value
Example

If the device is a character device, isatty returns a nonzero integer. If it is
not such a device, isatty returns O.
#include 
#include do.h>
int main(void)
{

int handle;
handle = fileno(stdprn);
if (isatty(handle))
printf("Handle %d is a device type\n", handle);
else
printf("Handle %d isn't a device type\n", handle);
return 0;

iscntrl
Function
Syntax

Remarks

Character classification macro.
#include 
int iscntr1(int c);

iscntrl is a macro that classifies ASCII-coded integer values by table
lookup. It is a predicate returning nonzero for true and 0 for false. It is
defined only when isascii(c) is true or cis EOP.

You can make this macro available as a function by undefining (#undef) it.
Return Value

iscntrl returns nonzero if c is a delete character or ordinary control
character (Ox7F or OxOO to OxlF).

Chapter 2, The run-time library

317

iscntrl

Example

#include 
#include 
int rnain(void)
{

char c = 'C';
if (iscntrl(c))
printf("%c is a control character\n",c);
else
printf("%c isn't a control character\n",c);
return 0;

isdigit
Function
Syntax

Remarks

Character classification macro.
#include 
int isdigit(int c);

isdigit is a macro that classifies ASCII-coded integer values by table
lookup. It is a predicate returning nonzero for true and 0 for false. It is
defined only when isascii(c) is true or c is EOF.

You can make this macro available as a function by undefining (#undef) it.
Return Value
Example

isdigit returns nonzero if c is a digit (0 to 9).
#include 
#include 
int rnain(void)
{

char c = 'C';
if (isdigit(c))
printf("%c is a digit\n",c);
else
printf("%c isn't a digit\n",c);
return 0;

318

Borland C++ Library Reference

isgraph

isgraph
Function
Syntax

Remarks

Character classification macro.
#include 
int isgraph(int c);

II

isgraph is a macro that classifies ASCII-coded integer values by table
lookup. It is a predicate returning nonzero for true and 0 for false. It is
defined only when isascii(c) is true or c is EOF.

You can make this macro available as a function by undefining (#undef) it.
Return Value
Example

isgraph returns nonzero if c is a printing character, like isprint, except that
a space character is excluded.
#include 
#include 
int main (void)
{

char c = ' c' ;
if (isgraph(c))
printf("%c is a graphic character\n",c);
else
printf("%c isn't a graphic character\n",c);
return 0;

islower
Function
Syntax

Character classification macro.
#include 
int islower(int c);

Chapter 2, The run-time library

319

islower

Remarks

islower is a macro that classifies ASCII-coded integer values by table
lookup. It is a predicate returning nonzero for true and a for false. It is
defined only when isascii(c) is true or c is EOF.
You can make this macro available as a function by undefining (#undef) it.

Return Value
Example

islower returns nonzero if c is a lowercase letter (a to z).
#include 
#include 
int main(void)
{

char c = 'C';
if (islower(c))
printf (" %c is lower case \n" ,c) ;
else
printf("%c isn't lower case\n",c);
return 0;

isprint
Function
Syntax

Remarks

Character classification macro.
#include 
int isprint(int c);

isprint is a macro that classifies ASCII-coded integer values by table
lookup. It is a predicate returning nonzero for true and a for false. It is
defined only when isascii(c) is true or c is EOF.
You can make this macro available as a function by ulJ.defining (#undef) it.

Return Value
Example

isprint returns nonzero if c is a printing character (Ox20 to Ox7E).
#include 
#include 
int main(void)
{

char c = 'C';
if (isprint(c))
printf("%c is a printable character\n",c);
else

320

Borland C++ Library Reference

isprint

printf("%c isn't a printable character\n",c);
return 0;

ispunct
Function
Syntax

Remarks

Character classification macro.
#include 
int ispunct(int c);

ispunct is a macro that classifies ASCII-coded integer values by table
lookup. It is a predicate returning nonzero for true and 0 for false. It is
defined only when isascii(c) is true or c is EOF.

You can make this macro available as a function by undefining (#undef) it.
Return Value
Example

ispunct returns nonzero if c is a punctuation character (iscntrl or isspace).
#include 
#include 
int main(void)
{

char c = 'e';
if (ispunct(c))
printf("%c is a punctuation character\n",c);
else
printf("%c isn't a punctuation character\n",c);
return 0;

isspace
Function
Syntax

Character classification macro.
#include 
int isspace(int c);

Chapter 2, The run-time library

321

isspace

Remarks

isspace is a macro that classifies ASCII-coded integer values by table
lookup. It is a predicate returning nonzero for true and 0 for false. It is
defined only when isascii(c) is true or c is EOF.

You can make this macro available as a function by undefining (#undef) it.
Return Value
Example

isspace returns nonzero if c is a space, tab, carriage return, new line,
vertical tab, or formfeed (Ox09 to OxOD, Ox20).
#include 
#include 
int main (void)
{

char c = ' C' i
if (isspace(c))
printf("%c is white space\n",c)i
else
printf("%c isn't white space\n",c) i
return 0i

isupper
Function
Syntax

Remarks

Character classification macro.
#include 
int isupper(int c);

isupper is a macro that classifies ASCII-coded integer values by table
lookup. It is a predicate returning nonzero for true and 0 for false. It is
defined only when isascii(c) is true or c is EOF.

You can make this macro available as a function by undefining (#undef) it.
Return Value
Example

isupper returns nonzero if c is an uppercase letter (A to Z).
#incl ude 
#include 
int main(void)
{

char c = 'C'i
if (isupper(c))
printf("%c is upper case\n",c)i

322

Borland C++ Library Reference

isupper

else
printf("%c isn't upper case\n",c);
return 0;

isxdigit
Function
Syntax

Remarks

Character classification macro.
#include 
int isxdigit(int c);

isxdigit is a macro that classifies ASCII-coded integer values by table
lookup. It is a predicate returning nonzero for true and 0 for false. It is
defined only when isascii(c) is true or c is EOF.

You can make this macro available as a function by undefining (#undef) it.
Return Value
Example

isxdigit returns nonzero if c is a hexadecimal digit (0 to 9, A

to F, a to f).

#incl ude 
#include 
int main(void)
{

char c :: ' c' ;
if (isxdigit(c))
printf("%c is hexadecimal\n",c);
else
printf("%c isn't hexadecimal\n",c);
return 0;

itoa
Function
Syntax

Converts an integer to a string.
#include 
char *itoa(int value, char *string, int radix);

Chapter 2, The run-time library

323

itoa

Remarks

itoa converts value to a null-terminated string and stores the result in
string. With itoa, value is an integer.

radix specifies the base to be used in converting value; it must be between 2
and 36, inclusive. If value is negative and radix is 10, the first character of
string is the minus sign (-).
..

Return Value

The space allocated for string must be large enough to hold the returned
string, including the terminating null character (\0). itoa can return up to
17 bytes.
itoa returns a pointer to string.

See also

Itoa, ultoa

Example

#include 
#include 
int main (void)
int number = 12345;
char string[25];
itoa(number, string, 10);
printf("integer = %d string = %s\n", number, string);
return 0;

kbhit
Function
Syntax

Remarks
Return Value

Checks for currently available keystrokes.
#include 
int kbhit(void);

kbhit checks to see if a keystroke is currently available. Any available
keystrokes can be retrieved with getch or getche.

If a keystroke is available, kbhit returns a nonzero value. Otherwise, it
returns O.

See also

getch, getche

Example

#include 
int main(void)

324

Borland C++ Library Reference

kbhit

cprintf("Press any key to continue:");
while (!kbhit()) /* do nothing */ ;
cprintf ("\r\nA key was pressed ... \r\n");
return 0;

keep, _dos_keep
Function
Syntax

Remarks

Exits and ren1ains resident.
#include 
void keep(unsigned char status, unsigned size);
void _dos_keep(unsigned char status, unsigned size);

keep and _dos_l<:eep return to DOS with the exit status in status. The

current program relnains resident, however. The program is set to size
paragraphs in length, and the remainder of the memory of the program is
freed.
keep and _dos_keep can be used when installing TSR programs. keep
and _dos_l<:eep use DOS function Ox31.

Before _dos_keep exits, it calls any registered "exit functions" (posted
with atexit), flushes file buffers, and restores interrupt vectors modified
by the startup code.
Return Value

None.

See also

abort, exit

Example

/* This is an interrupt service routine. You can NOT compile this program with

Test Stack Overflow turned on and get an executable file which will operate
correctly. Due to the nature of this function the formula used to compute the
number of paragraphs may not necessarily work in all cases. Use with care!
Terminate Stay Resident (TSR) programs are complex and no other support for
them is provided. Refer to the MS-DOS technical documentation for more
information. */
#include 
/* The clock tick interrupt */
#define INTR Oxle
/* Screen attribute (blue on grey) */
#define ATTR Ox7900

Chapter 2, The run-time library

325

#ifdef __cplusplus
#define __ CPPARGS
#else
#define __ CPPARGS
#endif

1* Reduce heaplength and stacklength to make a smaller program in memory. *1
extern unsigned _heaplen = 1024;
extern unsigned _stklen = 512;
void interrupt ( *oldhandler) (__CPPARGS) ;
typedef unsigned int (far *s_arrayptr);
void interrupt handler (__CPPARGS)
{

s_arrayptr screen[80];
static int count;

1* For a color screen the video memory is at B800:0000.
For a monochrome system use BOOO:OOO.

*1
screen[O]

= (s_arrayptr) MK_FP(OxB800,0);

1* increase the counter and keep it within 0 to 9 *1
count++;
count %= 10;
1* put the number on the screen *1
screen[O] [79] = count + '0' + ATTR;
1* call the old interrupt handler *1
oldhandler () ;
int main(void)
{

1* Get the address of the current clock tick interrupt *1
oldhandler = getvect(INTR);
1* install the new interrupt handler *1
setvect(INTR, handler);
1* -psp is the starting address of the program in memory. The top of the stack
is the end of the program. Using _S5 and _SP together we can get the end of
the stack. You may want to allow a bit of safety space to insure that
enough room is being allocated ie:
(_5S + ((_SP + safety space)/16) - -psp)

*1
keep(O, (_SS + (_SP/16) - -psp));
return 0;

326

Borland C++ Library Reference

Exannple 2

1* NOTE: This is an interrupt service routine. You CANNOT compile this program
with Test Stack Overflow turned on and get an executable file which will
operate correctly. Due to the nature of this function the formula used to
compute the number of paragraphs may not necessarily work in all cases. Use
with care! Terminate Stay Resident (TSR) programs are complex and no other
support for them is provided. Refer to the MS-DOS technical documentation for
more information. *1

#include 
1* The clock tick interrupt *1
#define INTR Ox1C
1* Screen attribute (blue on grey) *1
#define ATTR Ox7900
#ifdef __ cplusplus
#define __ CPPARGS
#else
#define __CPPARGS
#endif

1* Reduce heaplength and stacklength to make a smaller program in memory *1
extern unsigned _heaplen 1024;
extern unsigned _stklen
512;
void interrupt ( *oldhandler) (__CPPARGS) ;
typedef unsigned int (far *s_arrayptr);
void interrupt handler (__CPPARGS)
{

s_arrayptr screen[80];
static int count;
1* For a color screen the video memory is at B800:0000.
For a monochrome system use BOOO:OOO *1
screen[O] = (s_arrayptr) MK_FP(OxB800,O);

1* Increase the counter and keep it within 0 to 9. *1
count++;
count %= 10;

1* Put the number on the screen. *1
screen[O] [79] = count + '0' + ATTRi

1* Call the old interrupt handler. *1
oldhandler() ;
int main(void)

1* Get the address of the current clock tick interrupt. *1
oldhandler

= _dos_getvect(INTR);

1* install the new interrupt handler *1

\

Chapter 2, The run-time library

327

_dos_setvect(INTR , handler);
/* -psp is the starting address of the program in memory. The top of the stack is

the end of the program. Using _SS and _SP together we can get the end of the
stack. You may want to allow a bit of safety space to insure that enough room
is being allocated ie:
(_SS + ((_SP + safety space)/16) - _psp) */
_dos_keep (0
return 0·;

I

(_SS + (_SP /16) - _psp));

labs
Function
Syntax

Remarks
Return Value

Gives long absolute value.
#include 
long int labsOong int x);

labs computes the absolute value of the parameter x.
labs returns the absolute value of x.

See also

abs, cabs, tabs

Example

#inc1ude 
#include 
int main(void)
{

long result;
long x = -12345678L;
result= labs (x) ;
• printf ("number: %ld abs value: %ld\n", x, result);
return 0;

Idexp Idexpl
I

Function
Syntax

328

Calculates x x 2exP.
#include 
double ldexp(double x, int exp);
long double IdexplOong double x, int exp);

Borland C++ Library Reference

Jdexp, JdexpJ

DOS

/dexp
/dexp/

Remarks

Return Value

UNIX

•
•

Windows

ANSI C

•

•

•

C++ only

•

Idexp calculates the double value x x 2cxP.
lexpl is the long double version; it takes a long double argument for x and
returns' a long double result.
On success, Idexp (or Idexpl) returns the value it calculated, x x 2cxP •
Error handling for these routines can be modified through the functions
math err and matherrl.

See also

exp, frexp, modf

Example

#include 
#include 
int main(void)
double value, x

= 2;

/* ldexp raises 2 by a power of 3 then mUltiplies the result by 2 */
value = ldexp(x,3);
printf("The ldexp value is: %If\n", value);
return 0;

Idiv
Function
Syntax

Remarks

Divides two longs, returning quotient and remainder.
#include 
ldiv_t ldiv(long int monel', long int denom);

Idiv divides two longs and returns both the quotient and the remainder as
an ldiv_t type. maner and denom are the numerator and denominator,
respectively. The ldiv_t type is a structure of longs defined (with typedef)
in stdlib.h as follows:
typedef struct {
long int quot;
long int rem;

Chapter 2, The run-time library

/* quotient */
/* remainder */

329

Idiv

} ldiv_t;

Return Value

Idiv returns a structure whose elements are quat (the quotient) and rem

(the remainder).
See also

div

Example

#include 
#include 
int main (void)
{

ldiv_t lx;
lx = ldiv(lOOOOOL, 30000L);
printf("lOOOOO div 30000 = %ld remainder %ld\n", lx.quot, lx.rem);
return 0;

Ifind
Function
Syntax

Performs a linear search.
#include 
void *lfind(const void *key, const void *base, size_t *num, size_t width,
int (*femp)(const void*, const void *»;
DOS

Remarks

Ifind makes a linear search for the value of key in an array of sequential
records. It uses a user-defined comparison routine 
#include 
int compare(int *x, int *y)
{

return ( *x - *y );

330

Borland C++ Library Reference

Ifind

int main(void)
{

int array[5]
{35, 87, 46, 99, 12};
size_t nelem = 5;
int key = 99;
int *result;
result = (int *) lfind(&key, array, &nelem,
sizeof (int) ,
(int (*) (const void *, const void *)) compare) ;
if (result)
printf ("Number %d found\n", key) ;
else
printf ("Number %d not found\n", key) ;
return 0;

line
Function
Syntax

Remarks

Return Value

Draws a line between two specified points.
#include 
void far line(int xl, int yl, int x2, int y2);

line draws a line in the current color, using the current line style and
thickness between the two points specified, (xl,yl) and (x2,y2), without
updating the current position (CP).

None.

See also

getlinesettings, linerel, lineto, setcolor, setlinestyle, setwritemode

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int xmax, ymax;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

Chapter 2, The run-time library

331

line

/* read result of initialization */
errorcode = graphresult();

if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf ("Press any key to halt:") ;
getch() ;
exit(l) ;
setcolor(getmaxcolor() );
xmax = getmaxx();
ymax = getmaxy();
/* draw a diagonal line */
line(O, 0, xmax, ymax);
/* clean up */
getch () ;
closegraph ( ) ;
return 0;

Iinerel
Function
Syntax

Remarks
Return Value

Draws a line a relative distance from the current position (CP).
#include 
void far linerel(int dx, int dy);

linerel draws a line from the CP to a point that is a relative distance (dx,dy)
from the CPo The CP is advanced by (dx,dy).

None.

See also

getlinesettings, line, lineto, setcolor, setlinestyle, setwritemode

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;

332

Borland C++ Library Reference

linerel

char msg[80];

1* initialize graphics and local variables *1
initgraph(&gdriver, &gmode, "");
1* read result of initialization *1
errorcode = graphresult();
if (errorcode != grOk) {
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit (1) ;
1* move the CP to location (20,30) *1
moveto(20,30);
1* create and output a message at (20,30) *1
sprintf(msg, " (%d, %d)", getx(), gety());
outtextxy(20,30, msg);

I

•

1* draw line to a point a relative distance away from current CP *1
linerel (100, 100);

1* create and output a message at CP *1
sprintf(msg, " (%d, %d)", getx(), gety());
outtext (msg) ;
1* clean up *1
getch () ;
closegraph ( ) ;
return 0;

lineto
Function
Syntax

Remarks
Return Value
See also

Draws a line from the current position (CP) to (x,y).
#include 
void far lineto(int x, int y);

Iineto draws a line from the CP to (x,y), then moves the CP to (x,y).

None.
getlinesettings, line, Iinerel, setcolor, setlinestyle, setvisualpage,
setwritemode

Chapter 2, The run-time library

333

lineto

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
char msg [801 ;
/* initialize graphics and local variables */
initgraph(&gdriver, &~mode, no);
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) {
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf (" Press any key to halt:");
getch();
exi t (1) ;

/* move the CP to location (20,30) */
moveto(20, 30);
/* create and output a message at (20,30) */
sprintf(msg, " (%d, %d)", getx(), gety());
outtextxy(20,30, msg);
/* draw a line to (100,100) */
lineto (100, 100);
/* create and ou'tput a message at CP */
sprintf (msg, " (%d, %d)", getx (), gety () ) ;
outtext (msg) ;

/* clean up */
getch();
closegraph() ;
return 0;

localeconv
Function
Syntax

334

Returns a pointer to the current locale structure.
#include 
struct !cony *localeconv(void);

Borland C++ Library Reference

localeconv

UNIX

Remarks
Return Value

Wi ndows

This function sets up country-specific monetary and other numeric
formats. However, Borland C++ currently only supports locale C.
Returns a pointer to the current locale structure. See locale.h for details.

See also

setlocale

Example

#include 
#include 
int main(void)
{

struct lconv 11;
struct lconv *conv

= &11;

•

/* read the locality conversion structure */
conv = localeconv();
/* display the structure */
printf("Decimal Point
printf("Thousands Separator
printf("Grouping
printf("International Currency symbol
printf("$ thousands separator
printf("$ grouping
printf("Positive sign
printf ( "Negative sign
printf("International fraction digits
printf("Fraction digits
printf("Positive $ symbol precedes
printf("Positive sign space separation
printf("Negative $ symbol precedes
printf("Negative sign space separation
printf("Positive sign position
printf("Negative sign position
return 0;

%s\n" , conv->decimal-point) ;
%s\nll , conv->thousands_sep) ;
%s\n" , conv->grouping) ;
%s\n" , conv->int_curr_symbol) ;
%s\n" , conv->mon_thousands_sep);
%s\n" , conv->mon_grouping) ;
%s\n", conv->positive_sign);
%s\n", conv->negative_sign);
%d\n", conv->int_frac_digits);
%d\n", conv->frac_digits);
%d\n", conv->p_cs-precedes);
%d\n", conv->p_sep_by_space);
%d\n", conv->n_cs-precedes);
%d\n", conv->n_sep_by_space);
%d\n", conv->p_sign-posn);
%d\n", conv->n_sign-posn);

localtime
Function
Syntax

Converts date and time to a structure.
#include 
struct tm *localtimeCconst time_t *timer);

Chapter 2, The run-time library

335

locoltime

Remarks

localtime accepts the address of a value returned by time and returns a
pointer to the structure of type tm containing the broken-down time. It
corrects for the time zone and possible daylight saving time.
.

The global long variable timezone should be set to the difference in
seconds between GMT and local standard time (in PST, timezone is
8x60x60). The global variable daylight should be set to nonzero only if the
standard U.s. daylight saving time conversion should be applied.
The tm structure declaration from the time.h include file follows:
struct
int
int
int
int
int
int
int
int
int

tm {
tm_sec;
tm_min;
tm_hour;
tffi_mday;
tm_mon;
tm-year;
tm_wday;
tm-yday;
tm_isdst;

};

These quantities give the time on a 24-hour clock, day of month (1 to 31),
month (0 to 11), weekday (Sunday equals 0), year -1900, day of year (0 to
365), and a flag that is nonzero if daylight saving time is in effect.
Return Value

localtime returns a pointer to the structure containing the broken-down
time. This structure is astatic that is overwritten with each call.

See also

asctime, ctime, ftime, gmtime, stime, time, tzset

Example

#inc1 ude 
#include 
#include 
int main(void)
{

time_t timer;
struct tm *tblock;
/* gets time of day */
timer = time(NULL);
/* converts date/time to a structure */
tblock = localtime(&timer);
printf("Local time is: %s", asctime(tblock));

336

Borland C++ Library Reference

locoltime

return 0;

lock
Function
Syntax

Remarks

Sets file-sharing locks.
#include 
int lock(int handle, long offset, long length);

lock provides an interface to the DOS 3.x file-sharing mechanism.
SHARE.EXE must be loaded before using lock.
lock can be placed on arbitrary, nonoverlapping regions of any file. A
program attempting to read or write into a locked region will retry the
operation three times. If all three retries fail, the call fails with an error.

Return Value

lock returns 0 on success. On error, lock returns -1 and sets the global
variable errno to

EACCES

Locking violation

See also

open, sopen, unlock

Example

#include
#include
#include
#include
#include
#include








int main(void)
{

int handle, status;
long length;
/* must have DOS SHARE.EXE loaded for file locking to function */
handle = sopen(" c :\\autoexec.bat", O_RDONLY,SH_DENYNO,S_IREAD);
if (handle < 0) {
printf("sopen failed\n");
exit(l);

length = filelength(handle);
status = lock(handle,OL,length/2);
if (status == 0)

Chapter 2, The run-time library

337

lock

printf("lock succeeded\n");
else
printf("lock failed\n");
status = unlock(handle,OL,length/2);
if (status == 0)
printf("unlock succeeded\n");
else
printf("unlock failed\n");
close(handle);
return 0;

locking
Function
Syntax

Remarks

Sets or resets file-sharing locks.
#include 
#include 
int locking(int handle, int cmd, long length);

locking provides an interface to the file-sharing mechanism of DOS 3.0 or
later. SHARE.EXE must be loaded before using locking. The file to be
locked or unlocked is the open file specified by handle. The region to be
locked or unlocked starts at the current file position, and is length bytes
long.

Locks can be placed on arbitrary, nonoverlapping regions of any file. A
program attempting to read or write into a locked region will retry the
operation three times. If all three retries fail, the call fails
with an error.
The cmd specifies the action to be taken (the values are defined in sys \
locking.h):
LK_LOCK

Lock the region. If the lock is unsuccessful, try once a
second for 10 seconds before giving up.
Same as LK_LOCK.
Lock the region. If the lock if unsuccessful, give up
immedia tel y.

LK_NBRLCK

338

Same as LK_NBLCK.

Borland C++ Library Reference

locking

LK_UNLCK
Return Value

Unlock the region, which must have been previously
locked.

On successful operations, locking returns O. Otherwise, it returns -1, and
the global variable errno is set to one of the following:
EBADF
Bad file number
EACCESS
File already locked or unlocked
EDEADLOCK File cannot be locked after 10 retries (cmd is
LK LOCK or LK RLCK)
EINVAL
Invalid cmd, or SHARE.EXE not loaded

See also
Example

_fsopen,ope~sopen

#include
#include
#include
#include
#include
#include








int main (void)
{

int handle, status;
long length;
/* must have DOS SHARE.EXE loaded for file locking to function */
handle = sopen("c:\\autoexec.bat", O_RDONLY,SH_DENYNO);
if (handle < 0) {
printf("sopen failed\n");
exit(l);

length = filelength(handle);
status = locking(handle,LK_LOCK,length/2);
if (status == 0)
printf("lock succeeded\n");
else
perror("lock failed");
status = locking(handle,LK_UNLCK,length/2);
if (status == 0)
printf("unlock succeeded\n");
else
perror("unlock failed");
close (handle) ;
return 0;

Chapter 2, The run-time library

339

log, log I

log,logl
Function
Syntax

Calculates the natural logarithm of x.

Real versions:

Complex version:

#include 
double log(double x);
long double loglOong double x);

#include 
complex log (complex x);

DOS

logl

•
•
•

Rea/log
. Complex log

Remarks

UNIX

Wi ndows

ANSI C

c++

only

•

•
•

•

•

•

log calculates the natural logarithm of x.
logl is the long double version; it takes a long double argument and

returns a long double result.
The complex natural logarithm is defined by
log(z)
Return Value

= log(abs(z» + i arg(z)

On success, log and logl return the value calculated, In(x).
If the argument x passed to these functions is real and less than 0, the
global variable errno is set to
EDaM

Domain error

If x is 0, the functions return the value negative HUGE_VAL (log) or
negative _LHUGE_VAL (logl), and set errno to ERANGE.
Error handling for these routines can be modified through the functions
matherr and _matherrl.
See also

complex, exp, log10, sqrt

Example

#include 
#include 
int main(void)
{

double result, x = 8.6872;
result = log (x) ;
printf("The natural log of %If is %If\n", x, result);
return 0;

340

Borland C++ Library Reference

log10,logl01

laglO,laglOI
Function
Syntax

Calculates log lO(X).

Real versions:
Complex version:
#include 
#include 
double log10(double x);
complex log10(complex x);
long double logl0l0ong double x);

.

DOS

log 101
Rea/logl0

D

.

Wi ndows

D

~

I

Complex log 10

Remarks

UNIX

ANSI C

C++ only

•

I

II

log10 calculates the base 10 logarithm of x.
log1 01 is the long double version; it takes a long double argument and

returns a long double result.
The complex common logarithm is defined by
log10(z) = log(z) / log(10)
Return Value

On success, log10 (or log1 01) returns the value calculated, loglQ(x).
If the argument x passed to these functions is real and less than 0, the
global variable errno is set to
EDaM

Domain error

If x is 0, these functions return the value negative HUGE_VAL (log10) or
_LHUGE_VAL (log101).

Error handling for these routines can be modified through the functions
math err and _matherrl.
See also

complex, exp, log

Example

#inc1ude 
#include 
int main(void)
{

double result, x = 800.6872;
result = loglO(x);
printf("The common log of %If is %If\n'', x, result);
return 0;

Chapter 2, The run-time library

341

longjmp

longjmp
Function
Syntax

Remarks

Performs nonlocal goto.
#include 
void longjmp(jmp_buf jmpb, int retval);

A call to longjrnp restores the task state captured by the last call to setjrnp
with the argument jmpb. It then returns in such a way that setjrnp appears
to have returned with the value retval.
A task state is
• all segment registers (C5, 05, E5, 55)
.. register variables (51, 01)
• stack pointer (5P)
II frame base pointer (BP)
III flags
A task state is complete enough that setjrnp and longjmp can be used to
implement coroutines.
setjrnp must be called before longjrnp. The routine that called setjrnp and
set up jmpb must still be active and cannot have returned before the
longjrnp is called. If this happens, the results are unpredictable.
longjrnp cannot pass the value 0; if 0 is passed in retval, longjrnp will
substitute 1.

..

You can't use setjrnp and longjrnp for implementing coroutines if your
program is overlaid. Normally, setjrnp and longjrnp save and restore all
the registers needed for coroutines, but the overlay manager needs to
keep track of stack contents and assumes there is only one stack. When
you implement coroutines there are usually either two stacks or two
partitions of one stack, and the overlay manager will not track them
properly.
You can have background tasks which run with their own stacks or
sections of stack, but you must ensure that the background tasks do not
invoke any overlaid code, and you must not use the overlay versions of
setjrnp o~ longjrnp to switch to and from background.

Return Value
See also,

342

None.
ctrlbrk, setjrnp, signal

Borland C++ Library Reference

longjmp

Example

#include 
#include 
#include 
void subroutine (jmp_buf) ;
int main(void)
{

int value;
jmp_buf jumper;
value = setjmp(jumper);
if (value != 0) {
printf ("Longjmp with value %d\n", value);
exit (value) ;
printf ("About to call subroutine ... \n");
subroutine(jumper);
return 0;

II

void subroutine(jmp_buf jumper) {
longjmp(jumper,l) ;

Program output
About to call subroutine
Longjmp with value 1

lowvideo
Function
Syntax

Selects low-intensity characters.
#include 
void lowvideo(void);
II

DOS

UNIX

II

Remarks

Windows I

I

ANSI C I C++ only

II

I

JI

lowvideo selects low-intensity characters by clearing the high-intensity bit
of the currently selected foreground color.

This function does not affect any characters currently on the screen, only
those displayed by functions that perform text mode, direct console
output after this function is called.
Return Value

None.

Chapter 2, The run-time library

343

lowvideo

See also

highvideo, normvideo, textattr, textcolor

Example

#include 
int main(void)
{

clrscr () ;
highvideo() ;
cprintf("High Intesity Text\r\n");
lowvideo();
gotoxy (1 , 2) ;
cprintf("Low Intensity Text\r\n");
return 0;

Irotl
Function

Rotates an unsigned long integer value to the left.

Syntax

#include 
unsigned long _lrotl(unsigned long val, int count);

Remarks
Return Value

_Irotl rotates the given val to the left COllnt bits; val is an unsigned long.
_Irati returns the value of val left-rotated count bits.

See also

_Irotr, _rotl, _rotr

Example

#include 
#include 
/* function prototypes */

int lrotl_example(void);
int lrotr_example(void);
/* lrotl example */
int lrotl_example(void)
{

unsigned long result;
unsigned long value = 100;
result = _lrotl(value,l);
printf("The value %lu rotated left"
" one bit is: %lu\n", value, result);
return 0;

344

Borland C++ Library Reference

Jrotl

/* lrotr example */
int lrotr_example(void)
{

unsigned long result;
unsigned long value = 100;
result = _lrotr(value,l);
printf("The value %lu rotated right"
" one bit is: %lu\n", value, result);
return 0;
int main(void)
{

lrotl_example() ;
lrotr_example() ;
return 0;

Irotr
Function
Syntax

Remarks
Return Value

Rotates an unsigned long integer value to the right.
#include 
unsigned long _lrotrCunsigned long val, int count);

_Irotr rotates the given val to the right count bits; val is an. unsigned long.
_Irotr returns the value of val right-rotated count bits.

See also

_Irotl, _rotl, _rotr

Example

#include 
#include 
int main(void)
{

unsigned long result;
unsigned long value = 100;
result = _lrotr(value,l);
printf("The value %lu rotated right one bit is: %lu\n", value, result);
return 0;

Chapter 2, The run-time library

345

Isearch

Isearch
Function
Syntax

Remarks

Performs a linear search.
#include 
void *lsearch(const void *key, void *base,.size_t *num, size_t width,
int (*fcmp)(const void *, const void *»;

Isearch searches a table for information. Because this is a linear search, the
table entries do not need to be sorted before a call to Isearch. If the item
that key points to is not in the table, Isearch appends that item to the table.
III

base points to the base (Oth element) of the search table.

mnum points to an integer containing the number of entries in the table .

.. width contains the number of bytes in each entry .
.. key points to the item to be searched for (the search key).
The argument fcmp points to a user-written comparison routine, which
compares two items and returns a value based on the comparison.
To search the table, Isearch makes repeated calls to the routine whose
address is passed in fcmp.
On each call to the comparison routine, Isearch passes two arguments:
key, a pointer to the item being searched for, and elem, a pointer to the
element of base being compared.

fcmp is free to interpret the search key and the table entries in any way.
Return Value

Isearch returns the address of the first entry in the table that matches the
search key.

If the search key is not identical to *elem, fcmp returns a nonzero integer. If
the search key is identical to *elem, fcmp returns O.
See also

bsearch, Ifind, qsort

Example

#include 
#include 
#include 

/* for strcmp declaration */

/* initialize number of colors */
char *colors[lO] = { "Red", "Blue", "Green" };
int ncolors = 3;
int colorscmp(char **argl, char **arg2) {

346

Borland C++ Library Reference

Isearch

return(strcmp(*argl, *arg2));
int addelem(char *key) {
int oldn = ncolors;
lsearch(key, colors, (size_t *) &ncolors, sizeof(char *), (int(*)
(const void *, const void *)) colorscmp);
return(ncolors == oldn);
int main(void)
{

int i;
char *key = "Purple";
if (addelem(key))
printf("%s already in colors table\n", key);
else {
strcpy(colors[ncolors-l] ,key);
printf("%s added to colors table\n", key);
printf("The colors:\n");
for (i = 0; i < ncolors; itt)
printf ("%s\n", colors [i]);
return 0;

Iseek
Function
Syntax

Remarks

Moves file pointer.
#include 
long lseek(int handle, long offset, int fromwhere);

Iseek sets the file pointer associated with handle to a new position offset
bytes beyond the file location given by fromwhere. It is a good idea to set
fromwhere using one of three symbolic constants (defined in io.h) instead
of a specific number. The constants are
from where

SEEK_SET
SEEK_CUR
SEEK_END

Chapter 2, The run-time library

File location

(0)
(1)

(2)

File beginning
Current file pointer position
End-of-file

347

Iseek

Return Value

Iseek returns the offset of the pointer's new position measured in bytes
from the file beginning. Iseek returns -1 L on error, and the global variable
errno is set to one of the following:

EBADF
EINVAL

Bad file number
Invalid argument

On devices incapable of seeking (such as terminals and printers), the
return value is undefined.
See also

filelength, fseek, ftell, getc, open, sopen, ungetc, _write, write

Example

#include
#include
#include
#include
#include





do.h>

int main(void)
{

int handle;
char msg[] = "This is a test";
char Chi
/* create a file */
handle = open("TEST.$$$", O_CREAT I O_RDWR, S_IREAD I S_IWRITE);
/* write some data to the file */
write(handle, msg, strlen(msg));
/* seek to the begining of the file */
lseek(handle, OL, SEEK_SET);
/* reads chars from the file until EOF */
do {
read(handle, &ch, 1);
printf("%c", ch);

while (!eof(handle))i
close (handle) ;
return 0i

Itoa
Function
Syntax

348

Converts a long to a string.
#include 

Borland C++ Library Reference

Itoa

char *ltoa(long value, char *string, int radix);

Remarks

Itoa converts value to a null-terminated string and stores the result in
string. value is a long integer.

radix specifies the base to be used in converting value; it must be between 2
and 36, inclusive. If value is negative and radix is 10, the first character of
string is the minus sign (-).
~

Return Value

The space allocated for string must be large enough to hold the returned
string, including the terminating null character (\0). Itoa can return up to
33 bytes.
Itoa returns a pointer to string.

See also

itoa, u Itoa

Example

#include 
#include 
int main(void)
{

char string[25];
long value = 123456789L;
ltoa(value,string,10) ;
printf("number = %ld string
return 0;

= %s\n",

value, string);

_mokepoth
Function
Syntax

Remarks

Builds a path from component parts.
#include 
void _makepath(char *path, const char *drive, const char *dir,
const char *name, const char *ext);

_makepath makes a path name from its components. The new path name

is
X:\DIR\SUBDIR\NAME.EXT

Chapter 2, The run-time library

349

where

drive
dir
name
ext

x:
\DIR\SUBDIR\
NAME

.EXT

If drive is empty or NULL, no drive is inserted in the path name. If it is
missing a trailing colon (:), a colon is inserted in the path name.
If dir is empty or NULL, no directory is inserted in the path name. If it is
missing a trailing slash (\ or I), a backslash is inserted in the path name.
If name is empty or NULL, no filename is inserted in the path name.
If ext is empty or NULL, no extension is inserted in the path name. If it is
missing a leading period (.), a period is inserted in the path name.
_makepath assumes there is enough space in path for the constructed path

name. The maximum constructed length is _MAX_PATH. _MAX_PATH
is defined in stdlib.h. _makepath and _splitpath are invertible; if you split
a given path with _splitpath, then merge the resultant components with
_makepath, you end up with path.
Return Value

None.

See also

_fulJpath, _splitpath

Example

#include
#include
#include
#include






int main (void)
{

char
char
char
char
char

s[_MAX_PATHJ;
drive [_MAX_DRIVEJ ;
dir[_MAX_DIR1;
file[_MAX_FNAME1;
ext [_MAX_EXT 1;

getcwd(s,_MAX_PATH) ;
1* get current working directory *1
i f (s [s t rl en (s) -lJ ! = ' \ \ ' )
strcat(s,"\\");
1* append a trailing \ character *1
_splitpath(s,drive,dir,file,ext); 1* split the string to separate elems *1
strcpy(file, "DATA");
strcpy (ext, " . TXT") ;
_makepath(s,drive,dir,file,ext); 1* merge everything into one string *1
puts (s) ;
I * display result ing string * I
return 0;

350

Borland C++ Library Reference

malloe

malloe
Function
Syntax

Remarks

Allocates main memory.
#include  or #include
void *malloc(size_t size);

malloc allocates a block of size bytes from the memory heap. It allows a
program to allocate memory explicitly as it's needed, and in the exact
amounts needed.

The heap is used for dynamic allocation of variable-sized blocks of
memory. Many data structures, such as trees and lists, naturally employ
heap memory allocation.
All the space between the end of the data segment and the top of the
program stack is available for use in the small data models, except for a
small margin immediately before the top of the stack. This margin is
intended to allow the application some room to make the stack larger, in
addition to a small amount needed by DOS.
In the large data models, all the space beyond the program stack to the
end of available memory is available for the heap.
Return Value

On success, malloc returns a pointer to the newly allocated block of
memory. If not enough space exists for the new block, it returns null. The
contents of the block are left unchanged. If the argument size == 0, malloc
returns null.

See also

allocmem, calloc, coreleft, farcalloc, farmalloc, free, realloc

Example

#include
#include
#include
#include






int main(void)
{

char *str;
/* allocate memory for string */
if ((str = (char *) malloc(lO)) == NULL)
printf("Not enough memory to allocate buffer\n");

Chapter 2, The run-time library

351

•

malloc

exit(l);

/* terminate program if out of memory */

/* copy "Hello" into string */
strcpy (str, "Hello");
/* display string */
printf("String is %s\n", str);
/* free memory */
free (str) ;
return 0;

matherr, _matherrl
Function
Syntax

Remarks

User-modifiable math error handler.
#include 
int matherr(struct exception *e);
int _matherrl(struct _exceptionl *e);

matherr is called when an error is generated by the math library.
_matherrl is the long double version; it is called when an error is

generated by the long double math functions.
matherr and _matherrl each serve as a user hook (a function that can be
customized by the user) that you can replace by writing your own math
error handling routine - see the following example of a user-defined
math err implementation.

math err and _matherrl are useful for trapping domain and range errors
caused by the math functions. They do not trap floating-point exceptions,
such as division by zero. See signal for trapping such errors.

You can define your own matherr or _matherrl routine to be a custom
error handler (such as one that catches and resolves certain types of
errors); this customized function overrides the default version in the C
library. The customized matherr or _matherrl should return a if it fails to
resolve the error, or nonzero if the error is resolved. When matherr or
_matherrl return nonzero, no error message is printed and the global
variable errno is not changed.
Here are the exception and _exceptionl structures (defined in math.h):

352

Borland C++ Library Reference

matherr, _matherrl

struct exception {
int typei
char *Functioni
double argl, arg2, retvali
}i

struct _exceptionl {
int typei
char *Function;
long double argl, arg2, retvali
};

The members of the exception and _exceptionl structures are shown in
the following table:
Member

What it is (or represents)

type

The type of mathematical error that occurred; an enum type
defined in the typedef _mexcep (see definition after this list).

name

A pointer to a null-terminated string holding the name of the math
library function that resulted in an error.

argl,
arg2

The arguments (passed to the function name points to) that
caused the error; if only one argument was passed to the function,
it is stored in argl.

retval

The default return value for matherr (or _matherrl); you can
modify this value.

I

The typedef _mexcep, also defined in math.h, enumerates the following
symbolic constants representing possible mathematical errors:
Symbolic
constant

Mathematical error

DOMAIN

Argument was not in domain of function, such as log(-1).

SING

Argument would result in a singularity, such as pow(O, -2).

OVERFLOW

Argument would produce a function result greater than
DBL_MAX (or LDBL_MAX), such as exp(1000).

UNDERFLOW

Argument would produce a function result less than
DBL_MIN (or LDBL_MIN), such as exp(-1000).

TLOSS

Argument would produce function result with total loss of
significant digits, such as sin(10e70).

The macros DBL_MAX, DBL_MIN, LDBL_MAX, and LDBL_MIN are
defined in float.h.
The source code to the default matherr and _matherrl is on the Borland
C++ distribution disks.

Chapter 2, The run-time library

353

•

motherr, _motherrl '

The UNIX-style matherr and _matherrl default behavior (printing a
message and terminating) is not ANSI compatible. If you desire a UNIXstyle version of these routines, use MA THERR.C and MA THERRL.C
provided on the Borland C++ distribution disks.
Return Value

The default return value for matherr and _matherrl is 1 if the error is
UNDERFLOW or TLOSS, a otherwise. matherr and _matherrl can also
modify e -> retval, which propagates back to the original caller.
When matherr and _matherrl return a (indicating that they were not able
to resolve the error), the global variable errno is set to a and an error
message is printed.
When matherr and _matherrl return nonzero (indicating that they were
able to resolve the error), the global variable errno is not set and no
messages are printed.

Example

#include 
#include 
#include 
int matherr(struct exception *a)
{

if (a->type == DOMAIN)
if (!strcmp(a->name," sqrt"))
a->retval = sqrt(-(a->arg1));
return 1;
return 0;
int main (void)
{

double x = -2.0, y;
Y = sqrt (x) ;
printf("Matherr corrected value: %If\n",y);
return 0;

max
Function
Syntax

354

Returns the larger of two values.
#inc1ude 
(type) max(a, b);

Borland C++ Library Reference

max

Remarks
Return Value

Thi's macro compares two values and returns the larger of the two. Both
arguments and the macro declaration must be of the same type.
max returns the larger of two values.

See also

min

Example

#include 
#include 
int main(void)
int x

=

5, y

=

6, z;

z = max (x, y);

printf("The larger number is %d\n", z);
return 0;

Program output
The larger number is

mblen
Function
Syntax

Remarks

Determines the length of a multibyte character.
#include 
int mblen(const char *s, size_t n);

If s is not NULL, mblen determines the multibyte character pointed to by
s. The maximum number of bytes examined is specified by n.
The behavior of mblen is affected by the setting of LC_CTYPE category of
the current locale.

Return Value

If s is null, mblen returns a nonzero value if multibyte characters have
state-dependent encodings. Otherwise, mblen returns zero.
If s is not null, mblen returns the following:
zero

Chapter 2, The run-time library

if s points to the null character;

355

mblen

-1
if the next n bytes do not comprise a valid multibyte character;
the number of bytes that comprise a valid multibyte charter.
See also

mbtowc, mbstowc, setlocale

mbstowcs
Function
Syntax

Remarks

Converts a multibyte string to a wchar_t array.
#include 
size_t mbstowcs(wchar_t *pwcs, const char *s, size_t n);

The function converts the multibyte string s into the array pointed to by
pwcs. No more than n values are stored in the array. If an invalid
multibyte sequence is encountered, mbstowcs returns (size_t)-1.
The pwcs array will not be terminated with a zero value if mbstowcs
returns n.

Return Value

See also

If an invalid multibyte sequence is encountered, mbstowcs returns
(size_t) -1. Otherwise, the function returns the number of array elements
modified, not including the terminating code, if any.
mblen, mbstowc, setlocale

mbtowc
Function
Syntax

Converts a multibyte character to wchar_t code.
#include 
int mbtowc(wchar_t *pwc, const char *s, size_t n);
UNIX

Remarks

356

Wi ndows

If s is not null, mbtowc determines the number of bytes that comprise the
multibyte character pointed to by s. mbtowc then determines the value of
the type wchar_t that corresponds to that multibyte character. If there is a
successful match between wchar_t and the multibyte character, and pwc is
not null, the wchar_t value is stored in the array pointed to by pwc. At
most n characters are examined.

Borland C++ Library Reference

mbtowc

Return Value

When s points to an invalid multibyte character, -1 is returned. When s
points to the NULL character, zero is returned. Otherwise, mbtowc
returns the number of bytes that cOlnprise the converted multibyte
character.
The return value will never exceed MB_CUR_MAX or the value of n.

See also

mblen, mbstowcs, setlocale

memccpy, _fmemccpy
Function
Syntax

Copies a block of 11 bytes.
#inc1ude 
Near version: void *memccpy(void *dest, const void *src, int c, size_t n);
Far version: void far * far _fmemccpy(void far *dest, const void far *src,
int c, size_t n)
DOS

Near version
Far version

Remarl{s

UNIX

Windows

ANSI C

•

C++ only

•
•

I

I

•

memccpy is available on UNIX System V systems.
memccpy copies a block of n bytes from src to dest. The copying stops as
soon as either of the following occurs:

c The character c is first copied into dest.
en bytes have been copied into dest.
Return Value

memccpy returns a pointer to the byte in dest immediately following c, if c
was copied; otherwise, memccpy returns null.

See also

memcpy, memmove, memset

Example

#include 
#include 
int main(void)
char *src
ptr

=

= (char

"This is the source string", dest[50], *ptr;
*) memccpy(dest, src, 'c', strlen(src));

if (ptr) {
*ptr = '\0';
printf("The character was found: %s\n", dest);

Chapter 2, The run-time library

357

memccpy, _fmemccpy

else
printf("The character wasn't found\n");
return 0;

memchr, _fmemchr
Function
Syntax

Searches n bytes for character c.
#include 
Near version: void *memchr(const void *s, int c, size_t n);
Far version: void far * far _fmemchr(const void far *s, int c, size_t n);
DOS

Near version

•
•

For version

Remarks

UNIX

Windows

•

•
•

ANSI C

C++ only

•

memchr is available on UNIX System V systems.
memchr searches the first n bytes of the block pointed to by s for
character c.

Return Value
Example

On success, memchr returns a pointer to the first occurrence of c in s;
otherwise, it returns null.
#include 
#include 
int main(void)
{

char str[171, *ptr;
strcpy (str, "This is a string");
ptr = (char *) memchr(str, 'r', strlen(str));
if (ptr)
printf("The character 'r' is at"
" position: %d\n", ptr - str);
else
printf("The character was not found\n");
return 0;

memcmp, _fmemcmp
Function

358

Compares two blocks for a length of exactly n bytes.

Borland C++ Library Reference

memcmp, _fmemcmp

Syntax

#inc1ude 
Near version: int memcmp(const void *sl, const void *s2, size_t n);
Far version: int far _fmemcmp(const void far *sl, const void far *s2,
size_t n)
DOS

Near version

•
•

Far version

Remarks

UNIX

Windows

ANSI C

•
•

•

•

C++ only

memcmp is available on UNIX System V systems.
memcmp compares the first n bytes of the blocks sl and s2 as unsigned
chars.

Return Value

Because it compares bytes as unsigned chars, memcmp returns a value
< 0 if sl is less than s2
0 if sl is the same as s2
> 0 if sl is greater than s2

•

=

For example,
memcmp ( "\xFF", "\x7F", l)

returns a value greater than o.
See also

memicmp

Example

#include 
#include 
int main(void)
"aaa";
char *bufl
char *buf2
"bbb";
char *buf3
"ccc";
int stat;
stat = memcmp(buf2,
if (stat> 0)
printf ("buffer 2
else
printf("buffer 2
stat = memcmp(buf2,
if (stat> 0)
printf(nbuffer 2
else
printf(nbuffer 2
return 0;

Chapter 2, The run-time library

bufl, strlen(buf2));
is greater than buffer 1\n") ;
is less than buffer l\nn);
buf3, strlen(buf2));
is greater than buffer 3\n");
is less than buffer 3\nn);

359

memcpy, _fmemcpy

memcpy, _fmemcpy
Function
Syntax

Copies a block of n bytes.
#include 
Near version: void *memcpy(void *dest, canst void *src, size_t 11);
Far version: void far *far _fmemcpy(void far *dest, canst void far *src,
size_t n);
DOS

Near version

•
•

For version

Remarks

UNIX

Windows

•

•
•

ANSI C

C++ only

I

memcpy is available on UNIX System V systems.
memcpy copies a block of n bytes from src to dest. If src and dest overlap,
the behavior of memcpy is undefined.

Return Value

memcpy returns dest.

See also

memccpy, memmove, memset, movedata, movmem

Example

#include 
#include 
int main(void)
{

char src[] = "******************************";
char dest[] = "abcdefghijlkmnopqrstuvwxyz0123456709";
char *ptr;
printf("destination before memcpy: %s\n", dest);
ptr = (char *) memcpy(dest, src, strlen(src));
if (ptr)
printf("destination after memcpy: %s\n", dest);
else
printf("memcpy failed\n");
return 0;

memicmp, _fmemicmp
Function
Syntax

360

Compares n bytes of two character arrays, ignoring case.
#include 
Near version: int memicmp(const void *sl, canst void *s2, size_t n);

Borland C++ Library Reference

memicmp, _fmemicmp

Far version: int far _fmemicmp(const void far *s1, const void far *s2,
size_t 11)
DOS

Near version

•
•

Far version

Remarks

UNIX

Windows

•

ANSI C

C++ only

•
•

memicmp is available on UNIX System V systems.
memicmp compares the first 11 bytes of the blocks s1 and s2, ignoring
character case (upper or lower).

Return Value

memicmp returns a value

< 0 if s1 is less than s2
0 if s1 is the same as s2
> 0 if s1 is greater than s2

=

See also

memcmp

Example

#include 
#include 

•

int main(void)
{

char *bufl = "ABCDE123";
char *buf2 = "abcde456";
int stat;
stat = memicmp(bufl, buf2, 5);
printf("The strings to position 5 are ");
if (stat)
printf ("not ");
printf("the same\n");
return 0;

memmove
Function
Syntax

Remarks

Copies a block of 11 bytes.
#include 
void *memmove(void *dest, const void *src, size_t 11);

memmove is available on UNIX System V systems.

Chapter 2, The run-time library

361

memmove

memmove copies a block of n bytes from src to dest. Even when the source
and destination blocks overlap, bytes in the overlapping locations are
copied correctly.
Return Value

memmove returns dest.

See also

memccpy, memcpy, movmem

Example

#include 
#include 
int main(void)
{

char *dest = "abcdefghijklmnopqrstuvwxyz0123456789";
char *src = "******************************";
printf("destination prior to memmove: %s\n", dest);
memmove(dest, src, 26);
printf("destination after memmove:
%s\n", dest) i
return 0i

memset _fmemset
I

Function
Syntax

Sets n bytes of a block of memory to byte c.
#include 
Near version: void *memset(void *s, int c, size_t n);
Far version: void far * far _fmemset (void far *s, int c, size_t n)
DOS

Near version

•

Far version

•

Remarks

UNIX

Windows

ANSI C

•
•

•

•

C++ only

memset is available on UNIX System V systems
memset sets the first n bytes of the array s to the character c.

Return Value

memset returns s.

See also

memccpy, memcpy, setmem

Example

#include 
#include 
#include 
int main(void)
{

char buffer!] = "Hello world\n"i
printf("Buffer before memset: %s\n", buffer) i

362

Borland C++ Library Reference

memset, _fmemset

memset(buffer, '*', strlen(buffer) - 1);
printf("Buffer after memset: %s\n", buffer);
return 0;

min
Function
Syntax

Returns the smaller of two values.
#include 
(type) min(a, b);

I

Remarks

•

min compares two values and returns the smaller of the two. Both

arguments and the macro declaration must be of the same type.
Return Value

min returns the smaller of two values.

See also

max

Example

#include 
#include 
int main ()
{

int x = 5, y = 6;
printf ("The smaller number is %d\n", min (x,y));
return 0;

Program output
The smaller number is 5

mkdir
Function
Syntax

Creates a directory.
#include 
int mkdir(const char *path);
DOS

UNIX

I

Windows

•

I

•

•

Chapter 2, The run-time library

ANSI C

I C++

1

only

I
JI

363

mkdir

Remarks

mkdir is available on UNIX System V systems, though it then takes an
additional parameter.
mkdir creates a new directory from the given path name path.

Return Value

mkdir returns the value

a if the new directory was created.

A return value of -1 indicates an error, and the global variable errno is set
to one of the following values:
EACCES
ENOENT

Permission denied
No such file or directory

See also

chdir, getcurdir, getcwd, rmdir

Example

#include
#include
#include
#include






int main(void)
{

int status;
clrscr ();
status = mkdir("asdfjklm");
(! status)
(printf ("Directory created\n"))
(printf ("Unable to create directory\n"));
getch() ;
system( "dir");
getch () ;
status = rmdir("asdfjklm");
if (status == 0)
printf ("Directory deleted\n");
else
perror("Unable to delete directory");
return 0;

Function
Syntax

364

Makes a far pointer.
#include 
void far * MK_FP
#include 
int main(void)
int gd, gm, i;
unsigned int far *screen;
detectgraph(&gd, &gm);
if (gd == HERCMONO)
screen = MK_FP(OxBOOO, 0);
else
screen = MK_FP(OxBBOO, 0);
for (i = 0; i < 26; itt)
screen[ij = Ox0700 + ('a' + i);
return 0;

mktemp
Function
Syntax

Makes a unique file name.
#include 
char *mktemp(char *template);
ett

Remarks

only

mktemp replaces the string pointed to by template with a unique file name
and returns template.

template should be a null-terminated string with six trailing Xs. These XS
are replaced with a unique collection of letters plus a period, so that there
are two letters, a period, and three suffix letters in the new file name.
Starting with AA.AAA, the new file name is assigned by looking up the
name on the disk and avoiding pre-existing names of the same format.

Chapter 2, The run-time library

365

mktemp

Return Value
Example

If template is well-formed, mktemp returns the address of the template
string. Otherwise, it returns null.
#include 
#include 
int main (void)
{

1* fname defines template for temporary file *1
char *fname = "TXXXXXX", *ptr;
ptr = mktemp(fname);
printf("%s\n",ptr) ;
return 0;

mktime
Function
Syntax

Remarks

Converts time to calendar format.
#include 
time_t mktime(struct tm *t);

Converts the time in the structure pointed to by t into a calendar time
with the same format used by the time function. The original values of the
fields tm_sec, tm_min, tm_hour, tm_mday, and tm_mon are not restricted to
the ranges described in the tm structure. If the fields are not in their
proper ranges, they are adjusted. Values for fields tm_wday and tm-JIday
are computed after the other fields have been adjusted. If the calender
time cannot be represented, mktime returns -1.
The allowable range of calender times is Jan 11970 00:00:00 to Jan 19 2038
03:14:07.

Return Value

See Remarks.

See also

localtime, strftime, time

Example

#include 
#include 
char *wday [l

=

"Sunday", "Monday", "Tuesday", "Wednesday", Thursday", "Friday",
"Saturday", "Unknown"};

int main (void)

366

Borland C++ Library Reference

mktime

struct tm time_check;
int year, month, day;
/* input year, month, and day to find the weekday for */
printf ("Year: ");
scanf ("%d", &year);
printf ("Month: ");
scanf("%d", &month);
printf("Day:
");
scanf (" %d", &day);
/* load the time_check structure with the data */
time_check.tm-year = year - 1900;
time_check.tm_mon = month - 1;
time_check.tm_mday = day;
time_check.tm_hour = 0;
time_check.tm_min = 0;
time_check.tm_sec = 1;
time_check.tm_isdst = -1;

I

•

/* call mktime to fill in the structure's weekday field */
if (mktime(&time_check) == -1)
time_check.tm_wday = 7;
/* print out the day of the week */
printf("That day is a %s\n", wday [time_check. tm_wday] );
return 0;

modf, modfl
Function
Syntax

Splits a double or long double into integer and fractional parts.
#include 
double modf(double X, double *ipart);
long double modfl(long double X, long double *ipart);
DOS

modf
modfl

Remarks

UNIX

•
•

•

Windows

ANSI C

•

•

C++ only

•

modf breaks the double X into two parts: the integer and the fraction.
modf stores the integer in ipart and returns the fraction.
modfl is the long double version; it takes long double arguments and

returns a long double result.
Return Value

modf and modfl return the fractional part of x.

Chapter 2, The run-time library

367

modf, modfl

See also

fmod, Idexp

Example

#include 
#include 
int main (void)
{

double fraction, integer, number = 100000.567;
fraction = modf(number, &integer);
printf("The whole and fractional parts of %If are %If and %If\n", number,
integer, fraction);
return 0;

movedata
Function
Syntax

Remarks

Copies n bytes.
#include 
void movedata(unsigned srcseg, unsigned srcoff, unsigned dstseg,
unsigned dstoff, size_t n);

movedata copies n bytes from the source address (srcseg:srcoff) to the
destination address (dstseg:dstoff).
movedata is a means of moving blocks of data that is independent of
memory model.

Return Value

None.

See also

FP_OFF, memcpy, MK_FP, movmem, segread

Example

#incl ude 
#define MONO_BASE OxBOOO
char buf[80*25*2];
/* Saves the contents of the monochrome screen in buffer. */
void save_rnono_screen(char near *buffer)
{

movedata(MONO_BASE, 0, _DS, (unsigned) buffer, 80*25*2);
int main (void)
{

368

Borland C++ Library Reference

movedata

save_mono_screen(buf);
return(O) ;

movmem
Function
Syntax

Remarks

Return Value

Moves a block of length bytes.
#include 
void movmem(void *src, void *dest, unsigned length);

movmem moves a block of length bytes from src to dest. Even if the source
and destination blocks overlap, the move direction is chosen so that the
data is always moved correctly.

None.

See also

memcpy, memmove, movedata

Example

#include
#include
#include
#include






int main(void)
{

char *source = "Borland International";
char *destination;
int length;
length = strlen(source);
destination = malloc(length + 1);
movrnem(source,destination,length);
printf("%s\n",destination) ;
return 0;

moverel
Function
Syntax

Moves the current position (CP) a relative distance.
#include 
void far moverel(int dx, int dy);

Chapter 2, The run-time library

369

•

moverel

Remarks
Return Value

moverel moves the current position (CP) dx pixels in the x direction and
dy pixels in the y direction.

None.

See also

moveto

Example

#include
#include
#include
#include






int main(void}
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
char msg [80] ;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, ""};
/* read result of initialization */
errorcode = graphresult(};
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode});
printf("Press any key to halt:"};
getch(};
/* terminate with an error code */
exi t (1) ;
/* move the CP to location (20,30) */
moveto(20,30} ;
/* plot a pixel at the CP */
putpixel(getx(}, gety(}, getmaxcolor()};

/* create and output a message at (20,30) */
sprintf(msg, " (%d, %d)", getx(}, gety(}};
outtextxy(20,30, msg};
/* move to a point a relative distance away from the current CP */
moverel(100, 100};
/* plot a pixel at the CP */
putpixel(getx(}, gety(}, getmaxcolor()};
/* create and output a message at CP */
sprintf(msg, " (%d, %d)", getx(}, gety(}};
outtext (msg) ;

370

Borland C++ Library Reference

moverel

/* clean up */
getch() ;
closegraph ( ) ;
return 0;

movetext
Function
Syntax

Remarks

Copies text onscreen from one rectangle to another.
#inc1ude 
int movetextCint left, int top, int right, int bottom, int destleft, int desttop);

movetext copies the contents of the onscreen rectangle defined by left, top, •

right, and bottom to a new rectangle of the same dimensions. The new
rectangle's upper left corner is position Cdestleft, desttop).
All coordinates are absolute screen coordinates. Rectangles that overlap
are moved corre~t1y.
movetext is a text mode function performing direct video output.
Return Value

movetext returns nonzero if the operation succeeded. If the operation
failed Cfor example, if you gave coordinates outside the range of the
current screen mode), movetext returns o.

See also

gettext, puttext

Example

hncl ude 
#include 
int main (void)
{

char *str = "This is a test string";
clrscr () ;
cputs (str) ;
getch () ;
movetext(l, 1, strlen(str), 2, 10, 10);
getch () ;
return 0;

Chapter 2, The run-time library

371

moveto

moveto
Function
Syntax

Remarks
Return Value

Moves the current position (CP) to (x,y).
#include 
void far moveto(int x, int y);

moveto moves the current position (CP) to viewport position (x,y).

None.

See also

moverel

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
char msg [801 ;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf ("Graphics error: %s\n", grapherrormsg (errorcode) ) ;
printf (" Press any key to halt:") ;
getch () ;
exit(l);
/* terminate with an error code */
/* move the CP to location (20,30) */
moveto(20,30);
/* plot a pixel at the CP */
putpixel(getx(), gety(), getmaxcolor());
/* create and output a message at (20,30) */
sprintf(msg, " (%d, %d) ", getx(), gety());
outtextxy(20,30, msg);

/* move to (100,100) */
moveto(100,100);

372

Borland C++ Library Reference

moveto

/* plot a pixel at the CP */
putpixel(getx(), gety(), getmaxcolor());

/ * 'create and output a message at CP * /
sprintf(msg," (%d, %d)", getx(), gety());
outtext (msg) ;
/* clean up */
getch () ;
closegraph ( ) ;
return 0;

norm
Function
Syntax

Returns the square of the absolute value.
#include 
double norm(complex x);
ANSI C

Remarks
Return Value

C++ only

norm can overflow if either the real or imaginary part is sufficiently large.
norm(x)

returns the magnitude real (x) * real (x) + imag (x) * imag (x).

See also

arg, complex, polar

Example

#include 
int main(void)
double x = 3.1, Y = 4.2;
complex z = complex(x,y);
cout « liZ = " « z « "\n";
cout «" has real part = " « real(z) « "\n";
cout«
and imaginary real part
"« imag(z) « "\n";
cout« liZ has complex conjugate = " «conj(z) « "\n";
double mag = sqrt(norm(z));
double ang = arg(z);
cout « "The polar form of z is:\n";
cout«
magnitude ="« mag« "\n"; c
cout «
angle (in radians) = " « ang « "\n";
cout « "Reconstructing z from its polar form gives:\n";
cout «
z = " « polar(mag,ang) « "\n";
return 0;

Chapter 2, The run-time library

373

normvideo

normvideo
Function
Syntax

Remarks

Selects normal-intensity characters.
#include 
void normvideo(void);

normvideo selects normal characters by returning the text attribute

(foreground and background) to the value it had when the program
started.
This function does not affect any characters currently on the screen, only
those displayed by functions (such as cprintf) performing direct console
output functions after normvideo is called.
Return Value

None.

See also

highvideo, lowvideo, textattr, textcolor

Example

#include 
int main(void)
{

clrscr () ;
lowvideo() ;
cprintf("LOW
Intensity Text\r\n");
highvideo() ;
cprintf("HIGH Intensity Text\r\n");
normvideo();
cprintf("NORMAL Intensity Text\r\n");
return 0;

nosound
Function
Syntax

Remarks

374

Turns PC speaker off.
#include 
void nosound(void);

Turns the speaker off after it has been turned on by a call to sound.

Borland C++ Library Reference

nosound

Return Value

None.

See also

delay, sound

Example

/* Emits a 7-Hz tone for 10 seconds. Your PC may not be able to emit a 7-Hz
tone. * /

#include 
int main(void)
{

sound(7) ;
delay(10000) ;
nosound () ;

Function
Syntax

Opens a file for reading or writing.
#include 
int _open(const char *filename, int oflags);
#include 
#include 
#include 
unsigned _dos_open(const char *filename, unsigned oflags, int *handlep);

•

_open and _dos_open open the file specified by filename, then prepares it
Remarks

for reading or writing, as determined by the value of oflags. The file is
always opened in binary mode. The file handle is stored at the location
pointed to by handlep.

oflags must include one of the following values:
O_RDONLY

Open for reading.

O_WRONLY

Open for writing.

O_RDWR

Open for reading and writing.

On DOS 3.0 or later, the following additional values can be included in
oflags (using an OR operation):

Chapter 2, The run-time library

375

These symbolic
constants are
defined in fcntl.h
and share.h.

o_NOINHERIT

The file is not passed to child programs.

SH_COMPAT

Allow other opens with SH_COMP AT. The call will fail
if the file has already been opened in any other shared
mode.

SH_DENYRW

Only the current handle may have access to the file.

SH_DENYWR

Allow only reads from any other open to the file.

SH_DENYRD

Allow only writes from any other open to the file.

SH_DENYNO

Allow other shared opens to the file, but not other
SH_COMPATopens.

Only one of the SH_DENYxx values can be included in a single
_dos_open or _open under DOS 3.0 or later. These file-sharing attributes

are in addition to any locking performed on the files.
The maximum number of simultaneously open files is defined by
HANDLE_MAX.
Return Value

On successful completion, _open returns a nonnegative integer (the file
handle). On successful completion, _dos_open returns 0, and stores the
file handle at the location pointed to by handlep. The file pointer, which
marks the current position in the file, is set to the beginning of the file.
On error, _open returns -1 and _dos_open returns the DOS error code.
For both functions, the global variable errno is set to one of the following:
ENOENT
EMFILE
EACCES
EINVACC

Path or file not found
Too many open files
Permission denied
Invalid access code

See also

open, _read, sopen

Example

#include
#include
#include
#include



·
do.h>

int main(void) /* Example for _open. */
{

int handle;
char msg[] = "Hello world\n";
if ((handle = _open ("TEST. $$$"
perror("Error:") ;
return 1;

376

I

O_RDWR))

==

-1) {

Borland C++ Library Reference

_write (handle, msg, strlen(msg));
_close (handle) ;
return 0;
#include
#include
#include
#include






int main (void)

/* Example for _dos_open. */

{

int handle;
unsigned nbytes;
char msg[] = "Hello world\n";
if (_dos_open("TEST.$$$", O_ROWR, &handle)
perror("Unable to open TEST.$$$");
return 1;

!=

0) {

if (_dos_write (handle, msg, strlen(msg) ,&nbytes)
perror("Unable to write to TEST.$$$");
printf("%u bytes written to TEST.$$$\n",nbytes);
_dos_close(handle);
return 0;

!=

0)

•

open
Function
Syntax

Remarks

Opens a file for reading or writing.
#include 
#include
int open(const char *path, int access [, unsigned mode]);

open opens the file specified by path, then prepares it for reading and/or

writing as determined by the value of access.
To create a file in a particular mode, you can either assign to the global
variable Jmode or call open with the O_CREAT and O_TRUNC options
ORed with the translation mode desired. For example, the call
open("xmp",O_CREATIO_TRUNClo_BINARY,S_IREAO)

Chapter 2, The run-time library

377

open

will create a binary-mode, read-only file named XMP, truncating its
length to 0 bytes if it already existed.
For open, access is constructed by bitwise ~Ring flags from the following
two lists. Only one flag from the first list can be used (and one must be
used); the remaining flags can be used in any logical combination.
List 1: Read/write flags
These symbolic
constants are
defined in fcnt/.h.

O_RDONLY
0_WRONL Y
O_RDWR

Open for reading only.
Open for writing only.
Open for reading and writing.

List 2: Other access flags

O_NDELAY

o_APPEND
0_CREAT

O_TRUNC
O_EXCL

o_BINARY
O_TEXT

Not used; for UNIX compatibility.
If set, the file pointer will be set to the end of the file prior
to each write.
If the file exists, this flag has no effect. If the file does not
exist, the file is created, and the bits of mode are used to
set the file attribute bits as in chmod.
If the file exists, its length is truncated to o. The file
attributes remain unchanged.
Used only with O_CREAT. If the file already exists, an
error is returned.
Can be given to explicitly open the file in binary mode.
Can be given to explicitly open the file in text mode.

If neither O_BINARY nor O_TEXT is given, the file is opened in the
translation mode set by the global variable _fmode.
If the O_CREAT flag is used in constructing access, you need to supply the
mode argument to open from the following symbolic constants defined in
sys \stat.h.

Return Value

Value of mode

Access permission

S_IWRITE

Permission to write

S_IREAD
S_IREAD I S_IWRITE

Permission to read
Permission to read and write

On successful completion, open returns a nonnegative integer (the file
handle). The file pointer, which marks the current position in the file, is set
to the beginning of the file. On error, open returns -1 and the global
variable errno is set to one of the following:
ENOENT
EMFILE

378

No such file or directory
Too many open files

Borland C++ Library Reference

open

EACCES
EINVACC

Permission denied
Invalid access code

See also

chmod, chsize, close, _creat, creat, creatnew, creattemp, dup, dup2,
fdopen, file length, fopen, freopen, getftime, Iseek, lock, _open, read,
sopen, _write, write

Example

#include
#include
#include
#include






int main(void)
{

int handle;
char msg[] = "Hello world";
if ((handle = open("TEST.$$$", O_CREAT 10_TEXT)) ==
perror("Error:");
return 1;

-1)

{

}

write(handle, msg, strlen(msg));
close (handle) ;
return 0;

~.D.,I.;

EJ

opendir
Function
Syntax

Remarks

Opens a directory stream for reading.
#include 
DIR *opendir(char *dirname);

opendir is available on POSIX-compliant UNIX systems.

The opendir function opens a directory stream for reading. The name of
the directory to read is dirname. The stream is set to read the first entry in
the directory.
A directory stream is represented by the OIR structure, defined in
dirent.h. This structure contains no user-accessible fields. More than one
directory stream may be opened and read simultaneously. Directory
entries can be created or deleted while a directory stream is being read.

Chapter 2, The run-time library

379

opendir

Use the readdir function to read successive entries from a directory
stream. Use the closedir function to remove a directory stream when it is
no longer needed.
Return Value

If successful, opendir returns a pointer to a directory stream that can be
used in calls to readdir, rewinddir, and closedir. If the directory cannot be
opened, opendir returns NULL and sets the global variable errno to

ENOENT
ENOMEM

The directory does not exist.
Not enough memory to allocate a DIR object.

See also

closedir, readdir, rewinddir

Example

/* Using opendir, readdir, closedir */
#include 
#include 
#include 
void scandir(char *dirnarne)
{

DIR *dir;
struct dirent *ent;
printf("First pass on '%s':\n",dirnarne);
if ((dir = opendir(dirnarne)) == NULL)
perror("Unable to open directory");
exit (1) ;
while ((ent =.readdir(dir)) != NULL)
printf ( "%s \n" , ent ->d_narne) ;
printf("Second pass on '%s' :\n",dirnarne);
rewinddir(dir) ;
while ((ent = readdir(dir)) != NULL)
printf ("%s\n", ent->d_narne);
if (closedir(dir) != 0)
perror ("Unable to close directory");
void rnain(int argc,char *argv[])
{

if (argc != 2) {
printf("usage: opendir dirnarne\n");
exit(l) ;
scandir(argv[l]);
exi t (0) ;

380

Borland C++ Library Reference

outp

outp
Function

Outputs a byte to a hardware port.

Syntax

#include 
int outp(unsigned portid, int value);

Remarks

outp is a macro that writes the low byte of value to the output port
specified by portid.

If Qutp is called when conio.h has been included, it will be treated as a
macro that expands to inline code. If you don't include conio.h, or if you
do include conio.h and #undef the macro outp, you'll get the Qutp
function.
Return Value

outp returns

value.

See also

inp, inpw, outpw

Example

#include 
o#include 

II

int main(void)
{

unsigned port = 0;
int value;
value = outp(port, 'e');
printf("Value %c sent to port number %d\n", value, port);
return 0;

outport outportb
I

Function
Syntax

Outputs a word or byte to a hardware port.
#include 
void outport(int portid, int value);
void outportb(int portid, unsigned char value);

Chapter 2, The run-time library

381

out port , outportb

Remarks

outport works just like the 80x86 instruction out. It writes the low byte of

the word given by value' to the output port specified by portid and writes
the high byte of the word to portid +1.
outportb is a macro that writes the byte given by value to the output port
specified by portid.

If outportb is called when dos.h has been included, it will be treated as a
macro that expands to inline code. If you don't include dos.h, or if you do
include dos.h and #undef the macro outportb, you'll get the outportb
function.
Return Value

None.

See also

inport, inportb

Example

#include 
#include 
int main(void)
{

int value = 64, port = 0;
unsigned char c_value = 'C';
outportb(port, value);
printf(JlValue %d sent to port number %d\n", value, port);
outportb(port, c_value);
printf("Character %c sent to port number %d\n", c_value, port);
return 0;

outpw
Function
Syntax

382

Outputs a word to a hardware port.
#include 
unsigned outpwCunsigned portid, unsigned value);

Borland C++ Library Reference

outpw

Remarks

outpw is a macro that writes the 16-bit word given by value to the output
port specified by portid. It writes the low byte of value to portid, and the
high byte of the word to portid +1, using a single 16-bit OUT instruction.
If outpw is called when conio.h has been included, it will be treated as a
macro that expands to inline code. If you don't include conio.h, or if you
do include conio.h and #undef the macro outpw, you'll get the outpw
function.

Return Value

outpw returns value.

See also

inp, inpw, outp

Example

#include 
#include 
int main(void)
{

unsigned value, port = 0;
value = outpw(port, 64);
printf("Value %d sent to port number %d\n", value, port);
return 0;

outtext
Function
Syntax

Displays a string in the viewport.
#include 
void far outtext(char far *textstring);
I

DOS

I

UNIX

" • I
Remarks

I
I

Windows

ANSI C

I C++ only
I

outtext displays a text string in the viewport, using the current
. justification settings and the current font, direction, and size.
outtext outputs textstring at the current position (CP). If the horizontal text
justification is LEFT_TEXT and the text direction is HORIZ_DIR, the CP's
x-coordinate is advanced by textwidth(textstring). Otherwise, the CP
remains unchanged.
To maintain code compatibility when using several fonts, use textwidth
and textheight to determine the dimensions of the string.

..

If a string is printed with the default font using outtext, any part of the
string that extends outside the current viewport is truncated.

Chapter 2, The run-time library

383

ouHext

outtext is for use in graphics mode; it will not work in text mode.
Return Value

None.

See also

gettextsettings, outtextxy, settextjustify, textheight, textwidth

Example

#incl ude
#include
#include
#include






int main (void)
{

1* request autodetection *1
int gdriver = DETECT, gmode, errorcode;
int midx, midy;

1* initialize graphics and local variables *1
initgraph(&gdriver, &gmode, "");

1* read result of initialization *1
errorcode =. graphresult();
if (errorcode != grOk) { 1* an error occurred *1
printf("Graphics error: %s\n", graphe~rormsg(errorcode));
print f ( "Press any key to halt:");
getch();
exit(l);
1* terminate with an error code *1
midx
midy

= getmaxx()
= getmaxy()

I 2;
I 2;

1* move the CP to the center of the screen *1
moveto(midx, midy);
1* output text starting at the CP *1
outtext("This ");
outtext ( "is ");
outtext ("a ");
outtext("test.");
1* clean up *1
getch () ;
closegraph ( ) ;
return 0;

outtextxy
Function

384

Displays a string at a specified location.

Borland C++ Library Reference

outtextxy

Syntax

Remarks

#include 
void far outtextxy(int x, int y, char far *textstring);

outtextxy displays a text string in the viewport at the given position (x, y),
using the current justification settings and the current font, direction, and
size.

To maintain code compatibility when using several fonts, use textwidth
and textheight to determine the dimensions of the string.

_

If a string is printed with the default font using outtext or outtextxy, any
part of the string that extends outside the current viewport is truncated.
outtext is for use in graphics mode; it will not work in text mode.

Return Value

None.

See also

gettextsettings, outtext, textheight, textwidth

Example

hnc1 ude
#include
#include
#include






•

int main(void)
{

/* request autodetection */

int gdriver = DETECT, gmode, errorcode;
int midx, midy;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Gr~phics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */

midx
midy

= getmaxx() / 2;
= getmaxy() / 2;

/* output text at center of the screen; CP doesn't get changed */
outtextxy (midx, midy, "This is a test.");

Chapter 2, The run-time library

. 385

outtextxy

/* clean up * /
getch () ;
closegraph ( ) ;
return 0;

_OvrlnitEms
Function
Syntax

Remarks

Initializes expanded memory swapping for the overlay manager.
#include 
int cdecl far _OvrInitEms(unsigned emsHandle, unsigned firstPage,
unsigned pages);

_OvrlnitEms checks for the presence of expanded memory by looking for

an EMS driver and allocating memory from it. If emsHandle is zero, the
overlay manager allocates EMS pages and uses them for swapping. If
emsHandle is not zero, then it should be a valid EMS handle; the overlay
manager will use it for swapping. In that case, you can specify firstPage,
where the swapping can start inside that area.
In both cases, a nonzero pages parameter gives the limit of the usable
pages by the overlay manager.
Return Value

_OvrlnitEms returns 0 if the overlay manager is able to use expanded

memory for swapping.
See also

_OvrlnitExt, _ovrbuffer (global variable)

Example

#incl ude 
int main(void)
{

/* ask overlay manager to check for expanded memory and allow it to use 16
pages (256K) available only in medium, large, and huge memory models */

_OvrlnitEms (0, 0, 16);
return 0;

_Ovrl nitExt
Function

386

Initializes extended memory swapping for the overlay manager.

Borland C++ Library Reference

_OvrlnitExt

Syntax

Remarks

#include 
int cdecl far _OvrInitExt(unsigned long startAddress,
unsigned long length);

_OvrlnitExt checks for the presence of extended memory, using the known

methods to detect the presence of other programs using extended memory, and allocates memory from it. If startAddress is zero, the overlay
manager determines the start address and uses, at most, the size of the
overlays. If startAddress is not zero, then the overlay manager uses the
extended memory above that address.
In both cases, a nonzero length parameter gives the limit of the usable
extended memory by the overlay manager.
Return Value

_OvrlnitExt returns 0 if the overlay manager is able to use extended
memory for swapping.

See also

_OvrlnitEms, _ovrbuffer (global variable)

Example

#incl ude 

int main(void)
{

/* use the extended memory from the linear address Ox200000L (2MB), as much as
necessary */

_OvrlnitExt (Ox200000L, 0);
return 0;

parsfnm
Function
Syntax

Remarks

Parses file name.
#include 
char *parsfnm(const char *emdline, struct fcb *feb, int opt);

parsfnm parses a string pointed to by emdline for a file name. The string is
normally a command line. The file name is placed in a file control block
(FCB) as a drive, file name, and extension. The FCB is pointed to by feb.

Chapter 2, The run-time library

387

parsfnm

The opt parameter is the value documented for AL in the DOS parse
system call. See your DOS reference manuals under system call Ox29 for a
description of the parsing operations performed on the file name.
Return Value

Example

On success, parsfnm returns a pointer to the next byte after the end of the
file name. If there is any error in parsing the file name, parsfnm returns
null.
#include
#include
#include
#incl ude






int main(void)
{

char line[801i
struct fcb blk;
/* get file name */
printf("Enter drive and file name (no path - ie. a:file.dat)\n")i
gets(line) ;
/* put file name in fcb */
if (parsfnm(line, &blk, 1) == NULL)
printf("Error ig parsfm call\n");
else
printf("Drive #%d Name: %l1s\n", blk.fcb_drive, blk.fcb_name)i
return 0;

peek'
Function
Syntax

Remarks

Returns the word at memory location specified by segment:offset.
#include 
int peek(unsigned segment, unsigned offset);

peek returns the word at the memory location segment:offset.

If peek is called when dos.h has been included, it is treated as a macro
that expands to inlinecode. If you don't include dos.h, or if you do
include it and #undef peek, you'll get the function rather than the macro.
Return Value

388

peek returns the word of data stored at the memory location segment:offset.

Borland C++ Library Reference

peek

See also

harderr, peekb, poke

Example

#include 
#include 
#include 
int main(void)
{

int value = 0;
printf("The current status of your keyboard is:\n");
value = peek(Ox0040, Ox0017);
if (value & 1)
printf("Right shift on\n");
else
printf("Right shift off\n");
if (value & 2)
printf("Left shift on\n");
else
printf("Left shift off\n");
if (value & 4)
printf("Control key on\n");
else
printf("Control key off\n");
if (value & 8)
printf("Alt key on\n");
else
printf("Alt key off\n");
if (value & 16)
printf("Scroll lock on\n");
else
printf("Scroll lock off\n");
if (value & 32)
printf ("Num lock on\n");
else
printf("Num lock off\n");
if (value & 64)
printf("Caps lock on\n");
else
printf("Caps lock off\n");
return 0;

•

peekb
Function
Syntax

Returns the byte of memory specified by segment:offset.
#include 

Chapter 2, The run-time library

389

peekb

char peekb(unsigned segment, unsigned offset);

Remarks

peekb returns the byte at the memory location addressed by segment:offset.

If peekb is called when dos.h has been included, it is treated as a macro
that expands to inline code. If you don't include dos.h, or if you do
include it and #undef peekb, you'll get the function rather than the macro.
Return Value

peekb returns the byte of information stored at the memory location

segment:offset.
See also

peek, pokeb

Example

#incl ude 
#include 
#incl ude 
int main(void)
{

int value = 0;
printf("The current status of your keyboard is:\n");
value = peekb(Ox0040, Ox0017);
if (value & 1)
printf("Right shift on\n");
else
printf("Right shift off\n");
if (value & 2)
printf("Left shift on\n");
else
printf("Left shift off\n");
if (value & 4)
printf("Control key on\n");
else
printf("Control key off\n");
if (value & 8)
printf("Alt key on\n");
else
printf("Alt key off\n");
if (value & 16)
printf("Scroll lock on\n");
else
printf("Scroll lock off\n");
if (value & 32)
printf ("Num lock on \n") ;
else
printf ("Num lock off\n");

390

Borland C++ Library Reference

peekb

if (value & 64)
printf("Caps lock on\n");
else
printf("Caps lock off\n");
return 0;

perror
Function
Syntax

Remarks

Prints a system error message.
#include 
void perror(const char *s);

perror prints to the stderr stream (normally the console) the system error
message for the last library routine that produced the error.

First the argument s is printed, then a colon, then the message corresponding to the current value of the global variable errno, and finally a
newline. The convention is to pass the file name of the program as the
argument string.

•

The array of error message strings is accessed through the global variable

sys_errlist. The global variable errno can be used as an index into the array
to find the string corresponding to the error number. None of the strings
includes a newline character.
The global variable sys_nerr contains the number of entries in the array.
Refer to errno, sys_errlist, and sys_nerr in Chapter 3, "Global variables," for
more information.
Return Value

None.

See also

clearerr, eof, _strerror, strerror

Example

#include 
int main (void)
{

FILE *fp;
fp = fopen("perror.dat", "r");
if (! fp)
perror("Unable to open file for reading");

Chapter 2, The run-time library

391

pieslice

return 0;

pieslice
Function
Syntax

Remarks

Draws and fills in pie slice.
#include 
void far pieslice(int x, int y, int stangle, int endangle, int radius);

pies lice draws and fills a pie slice centered at (x,y) with a radius given by

radius. The slice travels from stangle to endangle. The slice is outlined in the
current drawing color and then filled using the current fill pattern and fill
color.
The angles for pies lice are given in degrees. They are measured counterclockwise, with 0 degrees at 3 o'clock, 90 degrees at 12 o'clock, and so on.
...

Return Value

If you are using a eGA or monochrome adapter, the examples in this book
of how to use graphics functions may not produce the expected results. If
your system runs on a eGA or monochrome adapter, use the value 1 (one)
instead of the symbolic color constant, and consult the second example
under arc on how to use the pieslice function.

None.

See also

fillellipse, fillyatterns (enumerated type), graphresult, sector, setfillstyle

Example

#include
#include
#include
#include






int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
int stangle = 45, endangle = 135, radius

=

100;

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, 1111);
/* read result of initialization */
errorcode = gravhresult();

392

Borland C++ Library Reference

pieslice

if (errorcode

!=

grOk)

/* an error occurred */

{

printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */
midx
midy

=

getmaxx() / 2;

= getmaxy() / 2;

/* set fill style and draw a pie slice */
setfillstyle(EMPTY_FILL, getmaxcolor());
pieslice(midx, midy, stangle, endangle, radius);

/* clean up * /
getch() ;
closegraph ( ) ;
return 0;

poke
Function
Syntax

Remarks

•

Stores an integer value at a memory location given by segment:offset.
#include 
void poke(unsigned segment, unsigned offset, int value);

poke stores the integer value at the memory location segment:offset.
If this routine is called when dos.h has been included, it will be treated as
a macro that expands to inline code. If you don't include dos.h, or if you
do include it and #undef poke, you'll get the function rather than the
macro.

Return Value

None.

See also

harderr, peek, pokeb

Example

#incl ude 
#include 
int main(void)
{

clrscr () ;
cprintf ("Make sure the scroll lock key is off and press any key\r\n");

Chapter 2, The run-time library

393

poke

getch () ;

poke(OxOOOO,Ox0417,16) ;
cprintf("The scroll lock is now on\r\n");
return 0;

pokeb
Function
Syntax

Remarks

Stores a byte value at memory location segment:offset.
#include 
void pokeb(unsigned segment, unsigned offset, char value);

pokeb stores the byte

value at the memory location segment:offset.

If this routine is called when dos.h has been included, it will be treated as
a macro that expands to inline code. If you don't include dos.h, or if you
do include it and #undef pokeb, you'll get the function rather than the
macro.
Return Value

None.

See also

peekb, poke

Example

#include 
#include 
int main (void)
{

clrscr () ;
cprintf ("Make sure the scroll lock key is off and press any key\r\n");
getch () ;

pokeb(OxOOOO,Ox0417,16) ;
cprintf("The scroll lock is now on\r\n");
return 0;

polar
Function
Syntax

394

Returns a complex number with a given magnitude and angle.
#include 
complex polar(double mag, double angle);

Borland C++ Library Reference

polar

Remarks
Return Value

polar (mag, angle) is the same as complex (mag*cos (angle), mag*sin (angle) ).

The complex number with the given magnitude (absolute value) and
angle (argument).

See also

arg, complex, norm

Example

#include 
int main ()
{

double x = 3.1, y = 4.2;
complex z = complex(x,y);
cout « "z = " « z « "\n";
cout « " has real part = " « real(z) « "\n";
cout «" and imaginary real part = " « imag(z) « "\n";
cout « "z has complex conjugate = " « conj (z) « "\n";
double mag = sqrt(norm(z));
double ang = arg(z);
cout « "The polar form of z is:\n";
cout « " magnitude = " « mag « "\n";
angle (in radians) = " « ang « "\n";
cout «"
cout « "Reconstructing z from its polar form gives:\n";
cout «"
z = " « polar(mag,ang) « "\n";
return 0;

•

poly, polyl
Function
Syntax

Generates a polynomial from arguments.
#include 
double poly(double x, int degree, double coeffs[]);
long double polylOong double x, int degree, long double coeffs[]);
DDS

poly
polyl

Remarks

UNIX

•
•

•

Windows

ANSI C

C++ only

•
•

poly generates a polynomial in x, of degree degree, with coefficients
coeffs[oJ, coeffs[1J, ... , coeffs[degreel. For example, if n = 4, the generated
polynomial is

Chapter 2, The run-time library

395

poly, polyl

coejfs[4]x4 + coeffs[3]x3 + coeffs[2]x2 + coeffs[l]x + coeffs[O]
polyl is the long double version; it takes long double arguments and
returns a long double result.
Return Value
Example

poly and polyl return the value of the polynomial as evaluated for the
given x.
#include 
#include 
1* polynomial:
int main(void)

x**3 - 2x**2 + 5x - 1 *1

{

double result, array[] = { -1.0,5.0, -2.0, 1.0 };
result = poly(2.0, 3, array);
printf("The polynomial: x**3 - 2.0x**2 + 5x - 1"
" at 2.0 is %If\n", result);
return 0;

POW ,

powl
Function
Syntax

Calculates x to the power of y.

Real versions:
#include 
double pow(double x, double y);
long double powl(long double x,
long double y)
DOS

powl

Rea/pow
Comp/expow

Remarks

•
•
•

UNIX

Wi ndows

ANSI C

Complex version:
#include 
complex pow(complex x, complex y);
complex pow(complex x, double y);
complex pow (double x, complex y);

C++ only

•
•

•

•

•

•

pow calculates xY•
powl is the long double version; it takes long double arguments and

returns a long double result.
The complex pow is defined by .

pow(base, expon)
Return Value

396

=

exp(expon log(base»

On success, pow and powl _
return the value calculated, xY•

Borland C++ Library Reference

pow, powl

Sometimes the arguments passed to these functions produce results that
overflow or are incalculable. When the correct value would overflow, the
functions return the value HUGE_VAL (pow) or _LHUGE_VAL (powl).
Results of excessively large magnitude can cause the global variable errno
to be set to
ERANGE

Result out of range

If the argument x passed to pow or powl is real and less than 0, and y is
not a whole number, the global variable errno is set to
EDaM

Domain error

If the arguments x and y passed to pow or powl are both 0, they return 1.

Error handling for these functions can be modified through the functions
matherr and _matherrl.
See also

complex, exp, pow10, sqrt

Example

#include 
#include 
int main(void)
{

double x = 2.0, y = 3.0;
printf("%lf raised to %If is %If\n", x, y, pow(x, y));
return 0;

powlO, powlOI
Function
Syntax

Calculates 10 to the power of p.
#include 
double powlO(int p);
long double powlOl(int p);
DOS

powl0

•

powl01

•

Remarks
Return Value

UNIX

•

Wi ndows

ANSI C

c++

only

I

•

pow10 computes lOP.

On success, pow10 returns the value calculated, lOP.
The result is actually calculated to long double accuracy. All arguments
are valid, though some can cause an underflow or overflow.

Chapter 2, The run-time library

397

powlO, powlOI

powl is the long double version; it returns a long double result.
See also

exp, pow

Example

#inc1ude 
#include 
int main(void)
{

double p ,= 3.0;
printf("Ten raised to %If is %If\n", p, powlO(p));
return 0;

printf
Function
Syntax

Remarks

The format string

Writes formatted output to stdout.
#include 
int printf(const char *formatL argument, ... J);

printf accepts a series of arguments, applies to each a format specifier
contained in the format string given by format, and outputs the formatted
data to stdout. There must be the same number of format specifiers as
arguments.

The format string, present in each of the ... printf function calls, controls
how each function will convert, format, and print its arguments. There

must be enough arguments for the format; if there are not, the results will be
unpredictable and likely disastrous. Excess argull1ents (more than required
by the format) are merely ignored.
The format string is a character string that contains two types of objectsplain characters and conversion specifications:
• Plain characters are simply copied verbatim to the output stream.
Conversion specifications fetch arguments from the argument list and
apply formatting to them.

II

Format specifiers
... printf format specifiers have the following form:
% [flags] [width] [.prec] [FINlhllIL] type

398

Borland C++ Library Reference

printf

Each conversion specification begins with the percent character (%). After
the % come the following, in this order:
an optional sequence of flag characters, [flags]
an optional width specifier, [width]
fl an optional precision specifier, [. prec]
II an optional input-size modifier, [F INih III L]
II the conversion-type character, [type]
fJ

III

Optional format
string components

These are the general aspects of output formatting controlled by the
optional characters, specifiers, and modifiers in the format string:
Character
or specifier

What it controls or specifies

flags

Output justification, numeric signs, decimal points, trailing
zeros, octal and hex prefixes

width

Minimum number of characters to print, padding with blanks
or zeros

precision

Maximum number of characters to print; for integers,
minimum number of digits to print

size

Override default size of argument:

•

N = near pointer
F = far pointer
h = short int
I = long
L = long double
... printf
conversion-type
characters

The following table lists the ... printf conversion-type characters, the type
of input argument accepted by each, and in what format the output
appears.
The information in this table of type characters is based on the assumption
that no flag characters, width specifiers, precision specifiers, or input-size
modifiers were included in the format specifier. To see how the addition
of the optional characters and specifiers affects the ... printf output, refer to
the tables following this one.

Chapter 2, The run-time library

399

printf

Type
character

Input argument

Format of output

integer
integer
integer
integer

signed decimal int.
signed decimal int.
unsigned octal int.
unsigned decimal into

X

integer
integer

unsigned hexadecimal int (with a, b, c, d, e, f).
unsigned hexadecimal int (with A, B, C, 0, E, F).

f

floating-point

signed value of the form [- Jdddd.dddd.

e

floating-point

signed value of the form [-Jd.dddd or e [+/-Jddd.

g

floating-point

signed value in either e or f form, based on given value and

Numerics

d
i

o
u

x

precision.
Trailing zeros and the decimal point are printed only if necessary.
E

floating-point

Same as e, but with E for exponent.

G

floating-point

Same as g, but with E for exponent if e format used.

c

character

Single character.

s

string pointer

Prints characters until a null-terminator is pressed or precision is
reached.

%

none

The % character is printed.

n

pointer to int

Stores (in the location pointed to by the input argument) a count
of the characters written so far.

p

pointer

Prints the input argument as a pointer; format depends on which
memory model was used. It will be either XXXX:YYYY or YYYY
(offset only).

Characters

Pointers

Conventions

400

Certain conventions accompany some of these specifications, as summarized in the following table:

Borland C++ Library Reference

printf

Characters

e or E

Conventions

The argument is converted to match the style [-]
d.ddd ... e[+/-]ddd, where
• one digit precedes the decimal point.
the number of digits after the decimal point is equal to the
precision.
II the exponent always contains at least two digits.
III

The argument is converted to decimal notation in the style
[-] ddd.ddd ... , where the number of digits after the decimal point
is equal to the precision (if a nonzero precision was given).
gorG

The argument is printed in style e, E or f, with the precision
specifying the number of significant digits. Trailing zeros are
removed from the result, and a decimal point appears only if
necessary.
The argument' is printed in style e or f (with some restraints) if g
is the conversion character, and in style E if the character is G.
Style e is used only if the exponent that results from the conversion is either greater than the precision or less than -4.

xorX

For x conversions, the letters a, b, c, d, e, and f appear in the
output; for X conversions, the letters A, 8, C, 0, E, and F appear.

Infinite floating-point numbers are printed as +INF and -INF. An IEEE
Not-a-Number is printed as +NAN or -NAN.
Flag characters

••

The flag characters are minus (-), plus (+), sharp (#), and blank O. They can
appear in any order and combination.
Flag

What it specifies

Left-justifies the result, pads on the right with blanks. If not given,
right-justifies result, pads on left with zeros or blanks.

-..
Alternate forms

+

Signed conversion results always begin with a plus (+) or minus (-)
sign.
.

blank

If value is nonnegative, the output begins with a blank instead of a
plus; negative values still begin with a minus.

#

Specifies that arg is to be converted using an "alternate form." See
the following table.

Plus (+) takes precedence over blank 0 if both are given.
If the # flag is used with a conversion character, it has the following effect
on the argument (arg) being converted:

Chapter 2, The run-time library

401

printf

Width specifiers

Conversion
character

How # affects arg

c,s,d,i,u

No effect.

o

a is prepended to a nonzero arg.

xorX

Ox (or OX) is prepended to argo

e, E, orf

The result always contains a decimal point even if no digits
follow the point. Normally, a decimal point appears in these
results only if a digit follows it.

gorG

Same as e and E, with the addition that trailing zeros are not
removed.

The width specifier sets the minimum field width for an output value.
Width is specified in one of two ways: directly, through a decimal digit
string, or indirectly, through an asterisk (*). If you use an asterisk for the
width specifier, the next argument in the call (which must be an int)
specifies the minimum output field width.
In no case does a nonexistent or small field width cause truncation of a
field. If the result of a conversion is wider than the field width, the field is
simply expanded to contain the conversion result.
Width
specifier

Precision specifiers

How output width is affected

n

At least n characters are printed. If the output value has less
than n characters, the output is padded with blanks (rightpadded if - flag given, left-padded otherwise).

On

At least n characters are printed. If the output value has less
than n characters, it is filled on the left with zeros.

*

The argument list supplies the width specifier, which must
precede the actual argument being formatted.

A precision specification always begins with a period (.) to separate it
from any preceding width specifier. Then, like width, precision isspecified either directly through a decimal digit string, or indirectly through an
asterisk (*). If you use an asterisk for the precision specifier, the next
argument in the call (treated as an int) specifies the precision.
If you use asterisks for the width or the precision, or for both~ the width
argument must immediately follow the specifiers, followed by the
precision argument, then the argument for the data to be converted.

402

Borland C++ Library Reference

printf

Precision
specifier

(none given)

How output precision is affected

Precision set to default:
default = 1 for d, i, 0, U, x, X types
default = 6 for e, E, f types
default = all significant digits for g, G types
default = print to first null character for s types; no effect on
c types

~

.0

For d, i, 0, U, x types, precision set to default; for e, E, f types, no
decimal point is printed.

.n

11 characters or 11 decimal places are printed. If the output value
has more than 11 characters, the output might be truncated or
rounded. (Whether this happens depends on the type
character.)

*

The argument list supplies the precision specifier, which must
precede the actual argument being formatted.

If an explicit precision of zero is specified, and the format specifier for the
field is one of the integer formats (that is, d, i, 0, U, x), and the value to be
printed is 0, no numeric characters will be output for that field (that is, the
field will be blank).
Conversion
character

d

o
u
x
X
e

Input-size modifier

How precision specification (.n) affects conversion
.11 specifies that at least 11 digits are
printed. If the input argument has less
than 11 digits, the output value is leftpadded with zeros. If the input argument
has more than 11 digits, the output value
is not truncated.

E
f

.11 specifies that 11 characters are printed
after the decimal point, and the last digit
printed is rounded.

9
G

.11 specifies that at most 11 significant
digits are printed.

c

.11

s

.11 specifies that no more than 11 characters
are printed.

has no effect on the output.

The input-size modifier character (F, N, h, 1, or L) gives the size of the
subsequent input argument:

F = far pointer
N = near pointer

Chapter 2, The run-time library

403

printf

h = short int
1= long
L = long double

The input-size modifiers (F, N, h, 1, and L) affect how the ... printf functions
interpret the data type of the corresponding input argument argo F and N
apply only to input args that are pointers (%p, %s, and %n). h, L, and L
apply to input args that are numeric (integers and floating-point).
Both F and N reinterpret the input argo Normally, the arg for a %p, %s, or
%n conversion is a pointer of the default size for the memory model. F
says "interpret arg as a far pointer." N says "interpret arg as a near
pointer." .
h, 1, and L override the default size of the numeric data input arguments: 1
and L apply to integer (d, i, 0, lI, x, X) and floating-point (e, E, I, g, and G)
types, while h applies to integer types only. Neither h nor 1affect character
(c, s) or pointer (p, n) types.
Input-size
modifier

How arg is interpreted

F

arg is read as a far pointer.

N

arg is read as a near pointer. N cannot be used with any
conversion in huge model.

arg is interpreted as a short int for d, i, 0,

h

tI,

x, or X.

arg is interpreted as a long int for d, i, 0, li, x, or X; arg is
interpreted as a double for e, E, i, g, or C.

arg is interpreted as a long double for e, E, i, g, or C.

L

Return Value

printf returns the number of bytes output. In the event of error, printf
returns EOF.

See also

cprintf, ecvt, fprintf, fread, fscanf, putc, puts, putw, scanf, sprintf, vprintf,
vsprintf

Example

#include 
#include 
#define I 555
#define R 5.5
int main(void)
{

int i,j,k,l;
char buf [7] ;
char *prefix
char tp [20];

404

=

buf;

Borland C++ Library Reference

printf

printf("prefix 6d
60
8x
10.2e
"10.2f\n");
strcpy(prefix, "%");
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j ++)
for (k = 0; k < 2; k++)
for (1 = 0; 1 < 2; 1++)
if (i==O) strcat(prefix,"-");
if (j==O) strcat(prefix,"+");
if (k==O) strcat(prefix,"#");
if (1==0) strcat(prefix,"O");
printf ("%5s I" ,prefix);
strcpy(tp,prefix);
strcat(tp,"6d I");
printf(tp,I) ;
strcpy (tp, "") ;
strcpy(tp,prefix) ;
strcat (tp, "60 I");
printf(tp,I) ;
strcpy (tp, ')") ;
strcpy(tp,prefix) ;
strcat (tp, "8x I");
printf (tp, I);
strcpy(tp, "");
strcpy(tp,prefix) ;
strcat(tp,"10.2e I");
printf (tp,R);
strcpy(tp,prefix) ;
strcat(tp,"10.2f I");
printf (tp,R);
printf(" \n");
strcpy(prefix, "%");

•

return 0;

Chapter 2, The run-time library

405

printf

Program output
prefix
%-+#0
%-+#
%-+0
%-+
%-#0

6d
1+555
1+555
1+555
1+555
1555
%-# 1555
%-0 1555
%- 1555
%+#0 1+00555
%+# I +555
%+0 1+00555
%+ I +555
%#0 1000555
%# I 555
%0 1000555
% I 555

60
01053
01053
1053
1053
01053
01053
1053
1053
001053
01053
001053
1053
001053
01053
001053
1053

8x
IOx22b
IOx22b
122b
122b
IOx22b
Ox22b
22b
22b
OxOO022b
Ox22b
0000022b
22b
OxOO022b
Ox22b
0000022b
22b

10.2e
1+5.50e+00
1+5.50e+00
1+5.50e+00
1+5.50e+00
15.50e+00
15.50e+00
15.50e+00
15.50e+00
1+05.50e+00
I +5.50e+00
1+05.50e+00
I +5.50e+00
1005.50e+00
I 5.50e+00
1005.50e+00
I 5.50e+00

10.2f
1+5.50
1+5.50
1+5.50
1+5.50
15.50
15.50
15.50
15.50
1+000005.50
+5.50
I
1+000005.50
+5.50
I
10000005.50
5.50
I
10000005.50
5.50
I

putc
Function
Syntax

Remarks
Return Value

Outputs a character to a stream.
#include 
int putc(int c, FILE *stream);

putc is a macro that outputs the character c to the stream given by stream.

On success, putc returns the character printed, c. On error, putc returns
EOF.

See also

fprintf, fputc, fputch, fputchar, fputs, fwrite, geic, getchar, printf, putch,
putchar, putw, vprintf

Example

#include 
int main(void)
{

char msg[] = "Hello world\n";
int i = 0;
while (msg[i])
putc(msg[i++], stdout);
return 0;

406

Borland C++ Library Reference

putch

putch
Function
Syntax

Remarks

Outputs character to screen.
#include 
int putch(int c);

puteh outputs the character c to the current text window. It is a text mode
function performing direct video output to the console. puteh does not
translate linefeed characters (\n) into carriage-return/linefeed pairs.

The string is written either directly to screen memory or by way of a BIOS
call, depending on the value of the global variable directvideo.
Return Value

On success, puteh returns the character printed, c. On error, it returns
EOF.

See also

eprintf, eputs, geteh, getehe, pute, putehar

Example

#include 
#include 

II

int main (void)
{

char ch = 0;
,printf ( "Input a string:");
while ((ch!= '\r')) {
ch = getch();
putch (ch) ;
return 0;

putchor
Function
Syntax

Remarks

Outputs character on stdout.
#include 
int putchar(int c);

putehar(c) is a macro defined to be pute(c,

Chapter 2, The run-time library

stdout).

407

putcher

Return Value

On success, putchar returns the character c. On error, putchar returns
EOF.

See also

fputchar, getc, getchar, printf, putc, putch, puts, putw, vprintf

Example

#include 
/* define some box drawing characters */
#define LEFT_TOP OxDA
#define RIGHT_TOP OxBF
#define HORIZ
OxC4
#define VERT
OxB3
#define LEFT_BOT OxCO
#define RIGHT_BOT OxD9

int main(void)
{

char i, j;
/* draw the top of the box */
put char (LEFT_TOP) ;
for (i=O; i<10; itt)
putchar(HORIZ);
put char (RIGHT_TOP) ;
put char ( , \n' ) ;
/* draw the middle */
for (i=O; i<4; itt) {
put char (VERT) ;
for (j=O; j<10; jtt)
putchar(' ');
put char (VERT) ;
putchar ( '\n' ) ;
/* draw the bottom */
put char (LEFT_BOT) ;
for (i=O; i<10; itt)
put char (HORIZ) ;
putchar(RIGHT_BOT);
putchar(' \n');
return 0;

putenv
Function
Syntax

408

Adds string to current environment.
#include 

Borland C++ Library Reference

putenv

int putenv(const char *name);

Remarks

putenv accepts the string name and adds it to the environment of the
current process. For example,
putenv("PATH=C:\\BC");
putenv can also be used to modify or delete an existing name. You can set

a variable to an empty value by specifying an empty string.
putenv can be used only to modify the current program's environment.
Once the program ends, the old environment is restored.

Note that the string given to putenv must be static or global. Unpredictable results will occur if a local or dynamic string given to putenv is
used after the string memory is released.
Return Value

On success, putenv returns 0; on failure, -1.

See also

getenv

Example

hncl ude
#include
#include
#include
#include







int main (void)
{

char *path, *ptr;
int i = 0;
/* Get the current path environment. */
ptr = getenv("PATH");
/* set up new path */
path = (char *) malloc(strlen(ptr)t15);
strcpy(path, "PATH=");
strcat(path,ptr) ;
strcat (path," ;c: \ \temp");
/* replace the current path and display current environment */
putenv (path) ;
while (environ[iJ)
print f ( "%s \n" , environ [i ++ J ) ;
return 0;

Chapter 2, The run-time library

409

putimage

putimage
Function
Syntax

Remarks

Outputs a bit image to screen.
#include 
void far putimage(int left, int top, void far *bitmap, int op);

putimage puts the bit image previously saved with getimage back onto
the screen, with the upper left corner of the image placed at (left,top).
bitmap points to the area in memory where the source image is stored.

The op parameter to putimage specifies a combination operator that
controls how the color for each destination pixel onscreen is computed,
based on the pixel already on screen and the corresponding source pixel in
memory.
The enumeration putimagc_ops, as defined in graphics.h, gives names to
these operators.
Name

Value

COPY_PUT
XOR_PUT
OR_PUT
AND_PUT
NOT_PUT

Description

0
1

Copy
Exclusive or
Inclusive or
And
Copy the inverse of the source

2
3
4

In other words, COPY_PUT copies the source bitmap image onto the
screen, XOR_PUT XORs the source image with that already onscreen,
OR_PUT ORs the source image with that onscreen, and so on.
Return Value

None.

See also

getimage, imagesize, putpixel, setvisualpage

Example

#include
#include
#include
#include






#define ARROW_SIZE 10
void draw_arrow(int

X,

int Y)

i

int main ()
{

/* request autodetection */

410

Borland C++ Library Reference

int gdriver = DETECT, gmode, errorcode;
void *arrow;
int x, y, maxx;
unsigned int size;

1* initialize graphics and local variables *1
initgraph(&gdriver, &gmode, ""I;
errorcode = graphresult();
if (errorcode != grOk)
1* an error occurred *1
{

printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(l);
1* terminate with an error code *1
maxx = getmaxx();
x = 0;
y = getmaxy() I 2;
draw_arrow (x, y);

1* calculate the size of the image and allocate space for it *1
size = imagesize (x, y-ARROW_SIZE, Xt (4 *ARROW_SIZE), ytARROvCSIZE);
arrow = malloc(size);
1* grab the image *1
getimage(x, y-ARROW_SIZE, xt(4*ARROW_SIZE), ytARROW_SIZE, arrow);
1* repeat until a key is pressed *1
while (!kbhit()) {
1* erase old image *1
put image (x, y-ARROW_SIZE, arrow, XOR_PUT);
x t= ARROW_SIZE;
if (x >= maxx)
x = 0;

1* plot new image *1
put image (x, y-ARROW_SIZE, arrow, XOR_PUT);
free (arrow) ;
closegraph ( ) ;
return 0;
void draw_arrow(int x, int y)
moveto (x, y);
linerel(4*ARROW_SIZE, 0);
linerel(-2*ARROW_SIZE, -l*ARROW_SIZE);
linerel(O, 2*ARROW_SIZE);
linerel(2*ARROW_SIZE, -l*ARROW_SIZE);

Chapter 2, The run-time library

411

putpixel

putpixel
Function
Syntax

Remarks
Return Value

Plots a pixel at a specified point.
#inc1ude 
void far putpixel(int x, int y, int color);

putpixel plots a point in the color defined by color at (x,y).

None.

See also

getpixel, putimage

Example

#include
#include
#include
#include
#include







#define PIXEL_COUNT 1000
#define DELAY_TIME 100 /* in milliseconds */
int main ()
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int i, x, y, color, maxx, maxy, maxcolor, seed;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
print f ( "Press any key to halt:") ;
getch() ;
exit(l);
/* terminate with an error code */

maxx = getmaxx() + 1;
maxy = getmaxy() + 1;
maxcolor = getmaxcolor() + 1;
while

412

(! kbhit

() )

Borland C++ Library Reference

putpixel

/* seed the random number generator */
seed = random(32767);
srand (seed) ;
for (i=O; i
int puts(const char *5);

puts copies the null-terminated string 5 to the standard output stream
stdout and appends a newline character.

On successful completion, puts returns a nonnegative value. Otherwise, it
returns a value of EOF.
cputs, fputs, gets, printf, putchar

Chapter 2, The run-time library

413

puttext

puttext
Function
Syntax

Remarks

Copies text from memory to the text mode screen.
#include 
int puttext(int left, int top, int right, int bottom, void *source);

puttext writes the contents of the memory area pointed to by source out to
the onscreen rectangle defined by left, top, right, and bottom.

All coordinates are absolute screen coordinates, not window-relative. The
upper left corner is (1,1).
puttext places the contents of a memory area into the defined rectangle
sequentially from left to right and top to bottom.
puttext is a text mode function performing direct video output.
Return Value

puttext returns a nonzero value if the operation succeeds; it returns 0 if it
fails (for example, if you gave coordinates outside the range of the current
screen mode).

See also

gettext, movetext, window

Function

Puts an integer on a stream.

putw

Syntax

#include 
int putw(int w, FILE *stream);
DOS

414

Remarks

putw outputs the integer w to the given stream. putw neither expects nor
causes special alignment in the file.

Return Value

On success, putw returns the integer w. On error, putw returns EOF.
Because EOF is a legitimate integer, use ferror to detect errors with putw.

See also

getw, printf

Example

#incl ude 
#include 

Borland C++ Library Reference

putw

#define FNAME "test. $$$"
int main(void)
{

FILE *fp;
int word;
/* place the word in a file */
fp = fopen (FNAME, "wb");
if (fp == NULL) {
printf ("Error opening file %s\n", FNAME);
exit(l);
word = 94;
putw (word, fp) ;
if (ferror(fp))
printf("Error writing to file\n");
else
printf("Successful write\n");
fclose (fp) ;
/* reopen the file */
fp = fopen(FNAME, "rb");
if (fp == NULL) {
printf ("Error opening file %s\n", FNAME);
exit(l);
/* extract the word */
word = getw(fp);
if (ferror(fp))
printf("Error reading file\n");
else
printf("Successful read: word = %d\n", word);
/* clean up */
fclose (fp) ;
unlink (FNAME) ;
return 0;

qsort
Function
Syntax

Sorts using the quicksort algorithm.
#include 
void qsort(void *base, size_t nelem, size_t width,
int (*fcmp)(const void *, const void *»;

Chapter 2, The run-time library

415

Remarks

qsort is an implementation of the "median of three" variant of the
quicksort algorithm. qsort sorts the entries in a table by repeatedly calling
the user-defined comparison function pointed to by temp.

• base points to the base (Oth element) of the table to be sorted.
• nelem is the number of entries in the table.
• width is the size of each entry in the table, in bytes.

*temp, the comparison function, accepts two arguments, eleml and elem2,
each a pointer to an entry in the table. The comparison function compares
each of the pointed-to items (*eleml and *elem2), and returns an integer
based on the result of the comparison.
*eleml < *elem2 temp returns an integer < 0
*eleml == *elem2 temp returns 0
*eleml > *elem2 temp returns an integer> 0
In the comparison, the less-than symbol «) means the left element should
appear before the right element in the final, sorted sequence. Similarly, the
greater-than (» symbol means the left element should appear after the
right element in the final, sorted sequence.
Return Value

None.

See also

bsearch, Isearch

Example

#inc1ude 
#include 
#include 
int sort_function ( const void *a, const void *b);
char list[5][4]

= {

"cat", "car", "cab", "cap", "can" };

int main(void)
int x;
qsort( (void *)list, 5, sizeof(list[O]), sort_function);
for (x = 0; x < 5; x++)
printf("%s\n",list[x]);
return 0;
int sort_function(const void *a, const void *b)
{

return( strcmp((char *)a, (char *)b) );

416

BOrland C++ Library Reference

raise

raise
Function
Syntax

Remarks

Sends a software signal to the executing program.
#include 
int raise(int sig);

raise sends a signal of type sig to the program. If the program has
installed a signal handler for the signal type specified by sig, that handler
will be executed. If no handler has been installed, the default action for
that signal type will be taken.

The signal types currently defined in signal.h are noted here:
Signal

Meaning

SIGABRT
SIGFPE
SIGILL
SIGINT
SIGSEGV
SIGTERM

Abnormal termination (*)
Bad floating-point operation
Illegal instruction (#)
Control break interrupt
Invalid access to storage (#)
Request for program termination (*)

Signal types marked with a (*) aren't generated by DOS or Borland C++
during normal operation. However, they can be generated with raise.
Signals marked by (#) can't be generated asynchronously on 8088 or 8086
processors but can be generated on some other processors (see signal for
details).
Return Value

raise returns 0 if successful, nonzero otherwise.

See also

abort, signal

Example

#include 
int main ()
{

int a, b;
a = 10;
b = 0;

if

(b == 0)

raise (SIGFPE) ;
a = a I b;

Chapter 2, The run-time library

1* preempt divide by zero error *1

417

I

._

return 0;

rand
Function
Syntax

Remarks

Random number generator.
#include 
int rand(void);

rand uses a multiplicative congruential random number generator with

period 232 to return successive pseudorandom numbers in the range from
a to RAND_MAX. The symbolic constant RAND_MAX is defined in
stdlib.h; its value is 215 - 1.
Return Value

rand returns the generated pseudorandom number.

See also

random, randomize, srand

Example

#include 
#include 
int main(void)
{

int i;
printf("Ten random numbers from 0 to 99\n\n");
for(i=O; idO; itt)
printf("%d\n", rand() % 100);
return 0;

randbrd
Function
Syntax

418

Reads random block.
#include 
int randbrd(struct fcb *feb, int rent);

Borland C++ Library Reference

randbrd

Remarks

rent number of records using the open file control block
(FeB) pointed to by feb. The records are read into memory at the current
disk transfer address (DT A). They are read frolll the disk record indicated
in the random record field of the FeB. This is accomplished by calling
DOS system call Ox27.
randbrd reads

The actual number of records read can be determined by examining the
random record field of the FeB. The random record field is advanced by
the number of records actually read.
Return Value

The following values are returned, depending on the result of the randbrd
operation:

o
1
2
3

All records are read.
End-of-file is reached and the last record read is complete.
Reading records would have wrapped around address OxFFFF (as
many records as possible are read).
End-of-file is reached with the last record incomplete.

See also

getdta, randbwr, setdta

Example

#include
#include
#include
#include






int main(void)
{

char far *save_dta;
char line[80] / buffer[256];
struct fcb blk;
int i, result;

II

/* get user input file name for dta */
printf(IIEnter drive and file name (no path - i.e. a:file.dat)\n");
gets (line) ;
/* put file name in fcb */
if (!parsfnm(line, &blk, 1))
print f ( I Error in call to parsfnm \n ") ;
exit(l) ;
printf("Drive #%d File: %s\n\n"/ blk.fcb_drive, blk.fcb_name);
/* open file with DOS fcb open file */
bdosptr(OxOF, &blk, 0);
/* save old dta and set new one */
save_dta = getdta();
setdta(buffer) ;

Chapter 2, The run-time library

419

randbrd

/* set up information for the new dta */
blk.fcb_recsize = 128;
blk.fcb_random = OL;
result = randbrd(&blk, 1);
/* check results from randbrd */

if

(! result)
printf("Read OK\n\n");
else {
perror("Error during read");
exi t (1) ;

/* read in data from the new dta */
printf("The first 128 characters are:\n");
for (i=O; i<128; itt)
putchar(buffer[i]) ;
/* restore previous dta */
setdta(save_dta) ;
return 0;

randbwr
Function
Syntax

Remarks

Writes random block.
#include 
int randbwr(struct fcb *fcb, int rcnt);

randbwr writes rcnt number of records to disk using the open file control
block (FCB) pointed to by fcb. This is accomplished using DOS system call
Ox28. If rcnt is 0, the file is truncated to the length indicated by the random
record field.

The actual number of records written can be determined by examining the
random record field of the FCB. The random record field is advanced by
the number of records actually written.
Return Value

The following values are returned, depending upon the result of the
randbwr operation:

o
1

420

All records are written.
There is not enough disk space to write the records (no records are
written).

Borland C++ Library Reference

randbwr

2

Writing records would have wrapped around address OxFFFF (as
many records as possible are written).

See also

randbrd

Example

#include
#include
#include
#include






int main(void)
{

char far *save_dta;
char line[80];
char buffer[256] = "RANDBWR test!";
struct fcb blk;
int result;
/* get new file name from user */
printf("Enter a file name to create (no path - ie. a:file.dat\n");
gets(line);
/* parse the new file name to the dta */
parsfnm(line,&blk,l) ;
printf("Drive #%d File: %s\n", blk.fcb_drive, blk.fcb_name);

/* request DOS services to create file */
if (bdosptr(Ox16, &blk, 0) == -1) {
perror ( Error creat ing file ") ;
exit(l) ;
II

•

/* save old dta and set new dta */
save_dta = getdta();
setdta (buffer) ;
/* write new records */
blk.fcb_recsize = 256;
blk.fcb_random = OL;
result = randbwr(&blk, 1);

if (! result)
printf("Write OK\n");
else {
perror("Disk error");
exit(l) ;
/* request DOS services to close the file */
if (bdosptr(Ox10, &blk, 0) == -1)
perror("Error closing file");
exit (1);

Chapter 2, The run-time library

421

randbwr

/* reset the old dta */
setdta(save_dta);
return 0;

random
Function
Syntax

Remarks

Return Value

Random number generator.
#include 
int random(int num);

random returns a random number between 0 and (num-1). random(num)
is a macro defined in stdlib.h. Both num and the random number returned
are integers.
random returns a number between 0 and (num-l).

See also

rand, randomize, srand

Example

#incl ude 
#include 
#include 
int main ()

/* prints a random number in the range 0 to 99 */

{

randomize() ;
printf("Random number in the 0-99 range: %d\n", random (100));
return 0;

randomize
Function
Syntax

422

Initializes random number generator.
#include 
#include 
void randomize(void);

Borland C++ Library Reference

randomize

Remarks

Return Value

randomize initializes the random number generator with a random value.
Because randomize is implemented as a macro that calls the time function
proto typed in time.h, we recommend that you also include time.h when
you use this routine.

None.

See also

rand, random, srand

Example

#include 
#include 
#include 
int main(void)
{

int i;
randomize() ;
printf("Ten random numbers from 0 to 99\n\n");
for(i=O; idO; itt)
printf("%d\n", rand() % 100);
return 0;

Function
Syntax

•

Reads from file.
#include 
int _read(int handle, void *buf, unsigned len);
#include 
unsigned _dos_read(int handle, void far *buf, unsigned *nread);

Remarks

_read attempts to read len bytes from the file associated with handle into

the buffer pointed to by buf.
When a file is opened in text mode, _read does not remove carriage
returns.
_dos_read uses DOS function Ox3F to read len bytes from the file

associated with handle into the buffer pointed to by the far pointer buf. The

Chapter 2, The run-time library

423

actual number of bytes read is stored at the location pointed to by nread;
when an error occurs, or the end-of-file is encountered, this number may
be less than len.
_dos_read does not remove carriage returns because all its files are binary

files.

handle is a file handle obtained from a _dos_creat, _dos_creatnew, or
_dos_open call.
For _read, handle is a file handle obtained from a creat, open, dup, or dup2
call.
On disk files, _dos_read and _read begin reading at the current file
pointer. When the reading is complete, they increment the file pointer by
the number of bytes read. On devices, the bytes are read directly from the
device.
The maximum number of bytes that _dos_read or _read can read is
65,534, because 65,535 (OxFFFF) is the same as -1, the error return
indicator.
Return Value

On successful completion, _dos_read returns O. Otherwise, the function
returns the DOS error code and sets the global variable errno.
'
On successful completion, _read returns a positive integer indicating the
number of bytes placed in the buffer. On end-of-file, _read returns zero.
On error, it returns -1, and the global variable errno .
. The global variable errno is set to one of the following:
EACCES
EBADF

Permission denied
Bad file number

See also

_open, read, _write

Example

#include
#incl ude
#include
#include
#include
#include


do. h>





int main(void)

/* Example for _read. */

{

void *buf;
int handle, bytes;
buf = malloc(lO);

424

Borland C++ Library Reference

/* Looks for a file in the current directory named TEST.$$$ and attempts to

read 10 bytes from it. To use this example you should create the file
TEST.$$$ */
if ({handle = open{"TEST.$$$", O_RDONLY )) == -1) {
printf ("Error Opening File\n") ;
exit{l) ;
if ({bytes = _read{handle, buf, 10))
printf ("Read Failed. \n") ;
exit{l);

-1) {

else printf ("Read: %d bytes read. \n", bytes);
return 0;_
#include 
#include 
#include 
int main{void)

/* Example for _dos_read. */

{

int handle;
unsigned bytes;
char buf [10];
/* Looks for a file in the current directory named TEST.$$$ and

attempts to read 10 bytes from it. To use this example you
should create the file TEST.$$$ */
if (_dos_open{"TEST.$$$", O_RDONLY, &handle) != 0) {
perror{"Unable to open TEST.$$$");
return 1;

•

if (_dos_read {handle, buf, 10, &bytes) != 0)
perror{"Unable to read from TEST.$$$");
return 1;
else printf ("_dosjead: %d bytes read. \n", bytes);
return 0;

read
Function
Syntax

Reads from file.
#include 
int read(int handle, void *buf, unsigned len);

Chapter 2, The run-time library

425

read

Remarks

read attempts to read len bytes from the file associated with handle into the
buffer pointed to by but.

For a file opened in text mode, read removes carriage returns and reports
end-of-file when it reaches a Ctrl-Z.
For _dos_read, handle is a file handle obtained from a creat, open, dup, or
dup2 call.
On disk files, read begins reading at the current file pointer. When the
reading is complete, it increments the file pointer by the number of bytes
read. On devices, the bytes are read directly from the device.
The maximum number of bytes that read can read is 65,534, because
65,535 (OxFFFF) is the same as -1, the error return indicator.
Return Value

On successful completion, read returns an integer indicating the number
of bytes placed in the buffer. If the file was opened in text mode, read does
not count carriage returns or Ctrl-Z characters in the number of bytes read.
On end-of-file, read returns o. On error, read returns -1 and sets the global
variable errno to one of the following:
EACCES
EBADF

Permission denied
Bad file number

See also

open, _read, write

Example

#include
#include
#include
#include
#include
#include








int main (void)
{

void *bufj
int handle, bytesj
buf = malloc(10)j
/* Looks for a file in the current directory named TEST.$$$ and attempts to
read 10 bytes from it. To use this example you should create the file
TEST.$$$ */
if ((handle = open(ITEST.$$$", O_RDONLY I O_BINARY,
S_IWRITE I S_IREAD)) == -1) {
printf("Error Opening File\n")j

426

Borland C++ Library Reference

read

exit(l) ;
if ((bytes = read(handle, buf, 10))
printf("Read Failed.\n");
exit (1);

== -1) {

else {
printf ("Read: %d bytes read. \n", bytes);
return 0;

readdir
Function
Syntax

Remarks

Reads the current entry from a directory stream.
#include 
struct dirent readdir(DIR *dirp);

readdir is available on POSIX-compliant UNIX systerns.

The readdir function reads the current directory entry in the directory
stream pointed to by dirp. The directory stream is advanced to the next
entry.
The readdir function returns a pointer to a dirent structure that is
overwritten by each call to the function on the same directory stream. The
structure is not overwritten by a readdir call on a different directory
stream.
The dirent structure corresponds to a single directory entry. It is defined
in dirent.h, and contains (in addition to other non-accessible members) the
following member:
char d_name[];

where d_name is an array of characters containing the null terminated file
name for the current directory entry. The size of the array is
indeterminate; use strlen to determine the length of the filename.
All valid directory entries are returned, including subdirectories, "." and
" .." entries, system files, hidden files, and volume labels. Unused or
deleted directory entries are skipped.

Chapter 2, The run-time library

427

readdir

A directory entry can be created or deleted while a directory stream is
being read, but readdir mayor may not return the affected directory
entry. Rewinding the directory with rewinddir or reopening it with
opendir will ensure that readdir will reflect the current state of the
directory.
Return Value

If successful, readdir returns a pointer to the current directory entry for
the'directory stream. If the end of the directory has been reached, or dirp
does not refer to an open directory stream, readdir returns NULL.

See also

closedir, opendir, rewinddir

Example

See the example for opendir.

Function

Returns the real part of a complex number or converts a BCD number
back to float, double or long double.

real

Syntax

As defined in complex:

As defined in bcd:

#inc1ude 
double real(complex x);

#inc1ude 
double real(bcd x);

I
• I

DOS

Remarks

UNIX

I
I

Wi ndows

ANSI C

I c++ only I
I·
I

The data associated to a complex number consists of two floating-point
numbers. real returns the one considered to be the real part.
You can also use real to convert a binary coded decimal number back to a
float, double, or long double.

Return Value

See also
Example 1

The real part of part of the complex number.
bcd, complex, imag
#inc1ude 
int main(void)
{

double x = 3.1, y = 4.2;
complex z = complex(x,y);
cout « "z = " « z « "\n";
cout «" has real part = " « real(z) « "\n";
cout «" and imaginary real part = " « imag(z) « "\n";
cout « "z has complex conjugate = " « conj (z) « "\n";
return 0;

428

Borland C++ Library Reference

real

Example 2

#include 
#include 
int main(void)
{

bcd x = 3.1;
cout « "The bcd number x = " « x « "\n";
cout « "Its binary equivalent is " « real(x) « "\n";
return 0;

realloc
Function
Syntax

Remarks

Reallocates main memory.
#include 
void *realloc(void *block, size_t size);

realloc attempts to shrink or expand the previously allocated block to size
bytes. The block argument points to a memory block previously obtained
by calling malloc, calloc, or realloc. If block is a null pointer, realloc works
just like malloc.
realloc adjusts the size of the allocated block to size, copying the contents
to a new location if necessary.

Return Value

realloc returns the address of the reallocated block, which can be different
than the address of the original block. If the block cannot be reallocated or
size == 0, realloc returns null.

See also

calloc, farrealloc, free, malloc

Example

#include 
#include 
#include 
int main (void)
{

char *str;
/* allocate memory for string */
str = (char *) malloc(10);
/* copy "Hello" into string */
strcpy (str "Hello");
I

Chapter 2, The run-time library

429

realloc

printf("String is %s\n Address is %p\n", str, str);
str = (char *) realloc(str, 20);
printf("String is %s\n New address is %p\n", str, str);
/* free memory */
free (str) ;
return 0;

rectangle
Function
Syntax

Remarks

Draws a rectangle.
#include 
void far rectangle(int left, int top, int right, int bottom);

rectangle draws a rectangle in the current line style, thickness, and
drawing color.

(left/top) is the upper left corner of the rectangle, and (right/bottom) is its
lower right corner.
Return Value

None.

See also

bar, bar3d, setcolor, setlinestyle

Example

#inc1ude
#include
#include
#include






int main(void)
{

/* request autodetection*/
int gdriver = DETECT, gmode, errorcode;
int left, top, right, bottom;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, ""I;
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;

430

Borland C++ Library Reference

rectangle

exit(l) ;

/* terminate with an error code */

left = getmaxx() / 2 - 50;
top = getmaxy() / 2 - 50;
right = getmaxx() / 2 + 50;
bottom = getmaxy() / 2 + 50;
/* draw a rectangle */
rectangle(left,top,right,bottorn) ;

/* clean up */
getch () ;
closegraph ( ) ;
return 0;

registerbgidriver
Function
Syntax

Remarks

Registers a user-loaded or linked-in graphics driver code with the
graphics system.
#include 
int registerbgidriver(void (*driver)(void));

registerbgidriver enables a user to load a driver file and "register" the
driver. Once its memory location has been passed to registerbgidriver,
initgraph uses the registered driver. 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.

Calling registerbgidriver informs the graphics system that the driver
pointed to by driver was included at link time. This routine checks the
linked-in code for the specified driver; if the code is valid, it registers the
code in internal tables. Linked-in drivers are discussed in detail in
UTIL.DOC, included with your distribution disks.
By using the name of a linked-in driver in a call to registerbgidriver, you
also tell the compiler (and linker) to link in the object file with that public
name.
Return Value

registerbgidriver returns a negative graphics error code if the specified
driver or font is invalid. Otherwise, registerbgidriver returns the driver
number.

Chapter 2, The run-time library

431

registerbgidriver

If you register a user-supplied driver, you must pass the result of
registerbgidriver to initgraph as the drive number to be used.
See also

graph result, initgraph, installuserdriver, registerbgifont

Example

#include
#include
#include
#include






int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;

/ * registE:r a driver t.hat was added into GRAPHICS. LIB * /
errorcode = registerbgidriver(EGAVGA_driver);
/* report any registration errors */
if (errorcode < 0) {
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf ("Press any key to halt:");
getch();
exit(l);
/* terminate with an error code */
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf (" Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */
/* draw a line */
line(O, 0, getmaxx(), getmaxy());
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

registerbgifont
Functiori

432

Registers linked-in stroked font code.

Borland C++ Library Reference

registerbgifont

Syntax

Remarks

#include 
int registerbgifont(void (*font)(void»;

Calling registerbgifont informs the graphics system that the font pointed
to by font was included at link time. This routine checks the linked-in code
for the specified font; if the code is valid, it registers the code in internal
tables. Linked-in fonts are discussed in detail under BGIOBJ in UTIL.DOC
included with your distribution disks.
By using the name of a linked-in font in a call to registerbgifont, you also
tell the compiler (and linker) to link in the object file with that public
name.

If you register a user-supplied font, you must pass the result of
registerbgifont to settextstyle as the font number to be used.
Return Value

registerbgifont returns a negative graphics error code if the specified font
is invalid. Otherwise, registerbgifont returns the font number of the
registered font.

See also

graph result, initgraph, installuserdriver, registerbgidriver, settextstyle

Example

#include
#include
#include
#include






int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcodei
int midx, midy;

/* register a font file that was added into GRAPHICS.LIB */
errorcode = registerbgifont(triplex_font) i
/* report any registration errors */
if (errorcode < 0) {
printf("Graphics error: %s\n", grapherrormsg(errorcode))i
printf (" Press any key to halt: ") i
getch () i
exit(l) i
/* terminate with an error code */
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, 1111) i

Chapter 2, The run-time library

433

registerbgifont

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */

midx
midy

= getmaxx() / 2;
= getmaxy() / 2;

/* select the registered font */
settextstyle(TRIPLEX_FONT, HORIZ_DIR, 4);
/* output some text */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, "The TRIPLEX FONT");
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

remove
Function
Syntax

Removes a file.
#include 
int remove(const char *filename);

I UNIX
• I •

DOS

Remarks

..
Return Value

434

•

ANSI C I C++ only

•

I

remove deletes the file specified by filename. It is a macro that simply
translates its call to a call to unlink. If your file is open, be sure to close it
before removing it.

The string pointed to by *filename may include a full DOS path.
On successful completion, remove returns o. On error, it returns -1, and
the global variable errno is set to one of the following:
ENOENT
EACCES

See also

Windows

No such file or directory
Permission denied

unlink

Borland C++ Library Reference

remove

Example

#include 
int main (void)
{

char file[BO];
/* prompt for file name to delete */
printf("File to delete: ");
gets (file) ;
/* delete the file */
if (remove(file) == 0)
printf(IIRemoved %s.\n",file);
else
perror("remove") ;
return 0;

rename
Function
Syntax

Remarks

Renames a file.
#include 
int rename(const char *oldname, const char *newname);

rename changes the name of a file from oldname to newname. If a drive
specifier is given in newname, the specifier must be the same as that given
in oldname.

Directories in oldname and newname need not be the same, so rename can
be used to move a file from one directory to another. Wildcards are not
allowed.
Return Value

On successfully renaming the file, rename returns O. In the event of error,
-1 is returned, and the global variable errno is set to one of the following:
ENOENT
EACCES
ENOTSAM

Example

No such file or directory
Permission denied
Not same device

#include 
int main (void)
char oldname[BO], newname[80];

Chapter 2, The run-time library

435

rename

/* prompt for file to rename and new name */
printf("File to rename: "I;
gets(oldname);
printf("New name: ");
gets (newname);
/* rename the file */
if (rename (oldname, newname) == 0)
printf("Renamed %s to %s.\n", oldname, newname);
else
perror("rename") ;
return 0;

restorecrtmode
Function

Restores the screen mode to its pre-initgraph setting.

Syntax . #include 
void far restorecrtmode( void);

Remarks

restorecrtmode restores the original video mode detected by initgraph.
This function can be used in conjunction with setgraphmode to switch
back and forth between text and graphics modes. textmode should not be
used for this purpose; use it only when the screen is in text mode, to
change to a different text mode.

Return Value

None.

See also

getgraphmode, initgraph, setgraphmode

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int x, y;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

436

Borland C++ Library Reference

restorecrtmode

/* read result of initialization */
errorcode = graphresult();
if (errorcode ! = grOk) { / * an error occurred * /
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(l);
/* terminate with an error code */

x
y

getmaxx()
getmaxy()

2;
2;

/* output a message */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "Press any key to exit graphics:");
getch () ;
/* restore system to text mode */
restorecrtmode() ;
printf("We're now in text mode.\n");
printf("Press any key to return to graphics mode:");
getch () ;
/* return to graphics mode */
setgraphmode(getgraplli~ode())

;

/* output a message */

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy (x, y, "We're back in graphics mode.");
outtextxy (x, y+textheight ("W'), "Press any key to halt:");

a

/* clean up * /
getch();
closegraph() ;
return 0;

rewind
Function
Syntax

Repositions a file pointer to the beginning of a stream.
#include 
void rewind(FILE *stream);

Chapter 2, The run-time library

437

rewind

Remarks

rewind(stream) is equivalent to fseek(stream, OL, SEEK_SET), except that
rewind clears the end-of-file and error indicators, while fseek only clears

the end-of-file indicator.
After rewind, the next operation on an update file can be either input or
output.
Return Value

None.

See also

fopen, fseek, ftell

Example

See fseek

Example

#inc1 ude 
#include 
int main(void)
{

FILE *fp;
char *fname = "TXXXXXX", *newname, first;
newname = mktemp(fname);
fp = fopen(newname," w+");
fprintf(fp, "abcdefghijklmnopqrstuvwxyz");
rewind (fp) ;
fscanf(fp,"%c",&first) ;
printf(IIThe first character is: %c\n",first);
fc10se (fp);
remove (newname) ;
return 0;

rewinddir
Function
Syntax

Remarks

Resets a directory stream to the first entry.
#include 
void rewinddir(DIR *dirp);

rewinddir is available on POSIX-compliant UNIX systems.

The rewinddir function repositions the directory stream dirp at the first
entry in the directory. It also ensures that the directory stream accurately
reflects any directory entries that may have been created or deleted since
the last opendir or rewinddir on that directory stream.

438

Borland C++ Library Reference

rewinddir

Return Value

None.

See also

closedir, opendir, readdir

Example

See the example for opendir.

Function

Removes a DOS file directory.

rmdir

Syntax

Remarks

#include 
int rmdir(const char *path);

rmdir deletes the directory whose path is given by path. The directory
named by path

must be empty.
II must not be the current working directory.
I'l must not be the root directory.
II

Return Value

rmdir returns 0 if the directory is successfully deleted. A return value of -1
indicates an error, and the global variable errno is set to one of the
following:

EACCES
ENOENT

Permission denied
Path or file function not found

See also

chdir, getcurdir, getcwd, mkdir

Example

#include
#include
#include
#include

II






#define DIRNAME "testdir. $$$

II

int main(void)
{

int stat;
stat = mkdir(DIRNAME);
if (! stat)
printf("Directory created\n");
else {
print f (liUnable to create directory\n ",) ;

Chapter 2, The run-time library

439

rmdir

exit(l);
getch() ;
system(Tldir/p") ;
getch () ;
stat = rmdir(DIRNAME);
if (!stat)
printf(TI\nDirectory deleted\n");
else (
perror("\nUnable to delete directory\n");
exi t (1) ;
return 0;

rmtmp
Function
Syntax

Removes temporary files.
#include 
int rmtmp(void);

Remarks

The rmtmp function closes and deletes all open temporary file streams,
which were previously created with tmpfile. The current directory must
the same as when the files were created, or the files will not be deleted.

Return Value

rmtmp returns the total number of temporary files it closed and deleted.

See also

tmpfil

Example

#include 
#include 
void main ()
FILE *stream;
int i;
/* Create temporary files */
for (i = 1; i <= 10; itt) {
if ((stream = tmpfile()) == NULL).
perror("Could not open temporary file\n");
else
printf ("Temporary file %d created\n ", i);

440

Borland C++ Library Reference

rmtmp

/* Remove temporary files */
if (stream != NULL)
printf("%d temporary files deleted\n", rmtmp());

Function
Syntax

Remarks
Return Value

Bit-rotates an unsigned integer value to the left.
#include 
unsigned _rotl(unsigned value, int count);

_rot! rotates the given value to the left count bits. The value rotated is an
unsigned integer.
_rot! returns the value of value left-rotated count bits.

See also

_Irotl, _Irotr, _rotr

Example

#include 
#include 
/* rotl example */
int rotl_example(void)

I

{
I

unsigned value, result;

II

value = 32767;
result = _rotl(value, 1);
printf("The value %u rotated left"
" one bit is: %u\n", value, result);
return 0;

I

/* rotr example */
int rotr_example(void)
{

unsigned value, result;
value = 32767;
result = _rotr(value, 1);
printf("The value %u rotated right"
" one bit is: %u\n", value, result);
return 0;

Chapter 2, The run-time library

441

int main(void)
{

rotl_example() ;
rotr_example() ;
return 0;

rotr
Function
Syntax

Bit-rotates an unsigned integer value to the right.
#inc1ude 
unsigned _rotr(unsigned value, int count);
UNIX

Remarks
Return Value

Windows

_rotr rotates the given value to the right count bits. The value rotated is an
unsigned integer.
_rotr returns the value of value right-rotated count bits.

See also

_Irotl, _Irotr, _rotl

Example

#include 
#include 
int main (void)
{

unsigned value, result;
value = 32767;
result = _rotr(value, 1);
printf("The value %u rotated right one bit is: %u\n", value, result);
return 0;

sbrk
Function
Syntax

442

Changes data segment space allocation.
#inc1ude 
void *sbrk(int incr);

Borland C++ Library Reference

sbrk

Remarks

sbrk adds incr bytes to the break value and changes the allocated space
accordingly. incr can be negative, in which case the amount of allocated
space is decreased.
sbrk will fail without making any change in the allocated space if such a
change would result in more space being allocated than is allowable.

Return value

Upon successful completion, sbrk returns the old break value. On failure,
sbrk returns a value of -1, and the global variable errno is set to
ENOMEM

Not enough core

See also

brk

Example

#include 
#include 
int main(void)
{

printf("Changing allocation with sbrk()\n");
printf("Before sbrk() call: %lu bytes free\n", (unsigned long) coreleft());
sbrk(lOOO) ;
printf("After sbrk() call: %lu bytes free\n", (unsigned long) coreleft());
return 0;

scanf
Function
Syntax

Remarks

Scans and formats input from the stdin stream.
#include 
int scanf(const char *formatL address, ... J);

seanf scans a series of input fields, one character at a time, reading from

the stdin stream. Then each field is formatted according to a format
specifier passed to seanf in the format string pointed to by format. Finally,
seanf stores the formatted input at an address passed to it as an argument
following format. There must be the same number of format specifiers and
addresses as there are input fields.
The format string

The format string present in seanf and the related functions eseanf,
fseanf, sseanf, vseanf, vfseanf, and vsseanf controls how each function
scans, converts, and stores its input fields. There must be enough address

Chapter 2, The run-time library

443

I

scant

arguments for the given format specifiers; if not, the results are unpredictable and likely disastrous. Excess address arguments (more than required
by the format) are merely ignored.
..

scanf often leads to unexpected results if you diverge from an expected
pattern. You need to remember to teach scanf how to synchronize at the
end of a line. The combination of gets or fgets followed by sscanf is safe

and easy, and therefore preferred.
The format string is a character string that contains three types of objects:
whitespace characters, non-whitespace characters, and format specifiers.
The whitespace characters are blank, tab (\t) or newline (\n). If a ... scanf
function encounters a whitespace character in the format string, it will
read, but not store, all consecutive whitespace characters up to the next
non-whitespace character in the input.
II The non-whitespace characters are all other ASCII characters except the
percent" sign (%). If a ... scanf function encounters a non-whitespace
character in the format string, it will read, but not store, a matching
non-whitespace character.
iii The format specifiers direct the ... scanf functions to read and convert
characters from the input field into specific types of values, then store
them in the locations given by the address arguments.
II

Trailing whitespace is left unread (including a newline), unless explicitly
matched in the format string.
Format specifiers
... scanf format specifiers have the following form:
% [*J [width] [FIN] [hllIL] type_character

Each format specifier begins with the percent character (%). After the %
come the following, in this order:
•
•
•
•

an optional assignment-suppression character, [*]
an optional width specifier, [width]
an optional pointer size modifier, [F IN]
an optional argument-type modifier, [h III L]

• the type character
Optional format
string components

444

These are the general aspects of input formatting controlled by the
optional characters and specifiers in the ... scanf format string:

Borland C++ Library Reference

scant

Character
or specifier

What it controls or specifies

*

Suppresses assignment of the next input field.

width

Maximum number of characters to read; fewer characters
might be read if the ... scanf function encounters a
whitespace or unconvertible character.

size

Overrides default size of address argument:
N = near pointer
F = far poin ter

argument
type

Overrides default type of address argument:
lz = short int
I = long int (if the type character specifies an integer
conversion)
I = double (if the type character specifies a floating-point
conversion)
L = long double (valid only with floating-point
conversions)

... scanftype
characters

The following table lists the ... scanf type characters, the type of input
expected by each, and in what format the input will be stored.
The information in this table is based on the assumption that no optional
characters, specifiers, or modifiers (*, width, or size) were included in the
format specifier. To see how the addition of the optional elements affects
the ... scanf input, refer to the tables following this one.

Chapter 2, The run-time library

445

scant

Type
character

Expected input

Type of argument

Decimal integer
Decimal integer

Pointer to int (int *arg)
Pointer to long (long *arg)

Octal integer
Octal integer

Pointer to int (int *arg)
Pointer to long (long *arg)

Decimal, octal, or
hexadecimal integer
Decimal, octal, or
hexadecimal integer

Pointer to int (int *arg)

Unsigned decimal
integer
Unsigned decimal
integer

Pointer to unsigned int
(unsigned int *arg)
Pointer to unsigned long
(unsigned long *arg)

X

Hexadecimal integer
Hexadecimal integer

Pointer to int (int *arg)
Pointer to int (int *arg)

e, E

Floating point

Pointer to float (float *arg)

Floating point

Pointer to float (float *arg)

Floating point

Pointer to float (float *arg)

s

Character string

Pointer to array of characters (char arg[J)

c

Character

Pointer to character (char *arg) if a field width W is given along
with the c-type character (such as %5c).

Numerics

d

D
a

o

u

u
x

g,G

Pointer to long (long *arg)

Characters

Pointer to array of W characters (char arg[WD
% character

%

No conversion done; % is stored.

Pointers

n
p

Pointer to int (int *arg). The number of characters read
successfully up to %n is stored in this int.
Hexadecimal form
YYYY:ZZZZ or
ZZZZ
Input fields

Pointer to an object (jar* or near*)
%p conversions default to the
pointer size native to the memory model.

Anyone of the following is an input field:
• all characters up to (but not including) the next whitespace character
• all characters up to the first one that cannot be converted under the
current format specifier (such as an 8 or 9 under octal format)

446

Borland C++ Library Reference

scant

• up to n characters, where n is the specified field width
Conventions

Certain conventions accompany some of these format specifiers, as
summarized here.
%c conversion

This specification reads the next character, including a whitespace character. To skip one whitespace character and read the next non-whitespace
character, use % 1s.
%Wc conversion (W

=width specification)

The address argument is a pointer to an array of characters; the array
consists of Welements (char arg[W]).
%s conversion

The address argument is a pointer to an array of characters (char arg[]).
The array size must be at least (n+ 1) bytes, where n equals the length of
slring s (in characters). A space or new line terminates the input field. A
null-terminator is automatically appended to the string and stored as the
last element in the array.
%[search_set] conversion

The set of characters surrounded by square brackets can be substituted for
the s-type character. The address argument is a pointer to an array of
characters (char arg[D.
These square brackets surround a set of characters that define a search set
of possible characters making up the string (the input field).
If the first character in the brackets is a caret (/\), the search set is inverted
to include all ASCII characters except those between the square brackets.
(Normally, a caret will be included in the inverted search set unless
explicitly listed somewhere after the first caret.)

The input field is a string not delimited by whitespace .... scanf reads the
corresponding input field up to the first character it reaches that does not
appear in the search set (or in the inverted search set). Two examples of
this type of conversion are
Searches for any of the characters a, b, c, and d in the input
field.
%["abed] - Searches for any characters except a, b, c, and d in the input
field.
%[abed]

You can also use a range facility shortcut to define a range of characters
(numerals or letters) in the search set. For example, to catch all decimal
digits, you could define the search set by using %[0123456789] , or you
could use the shortcut to define the same search set by using %[0-9].

Chapter 2, The run-time library

447

scant

To catch alphanumeric characters, use the following shortcuts:
%[A-Z]
%[O-9A-Za-z]
%[A-FT-Z]

Catches all uppercase letters.
Catches all decimal digits and all letters (uppercase
and lowercase).
Catches all uppercase letters from A through F and
from T through Z.

The rules covering these search set ranges are straightforward:
• The character prior to the hyphen (-) must be lexically less than the one
after it.
• The hyphen must not be the first nor the last character in the set. (If it is
first or last, it is considered to just be the hyphen character, not a range
definer.)
• The characters on either side of the hyphen must be the ends of the
range and not part of some other range.
Here are some examples where the hyphen just means the hyphen
character, not a range between two ends:
%[-+*1]
%[z-a]
%[+O-9-A-Z]
%[+O-9A-Z-]
%[A-O-9+A-Z]

The four arithmetic operations
The characters z, -, and a
The characters + and - and the ranges 0-9 and A-Z
Also the characters + and - and the ranges 0-9 and A-Z
All characters except + and - and those in the ranges 0-9
and A-Z

%e, %E. %f, %g, and %G (floating-point) conversions
Floating-point numbers in the input field must conform to the following
generic format:
[+/-J ddddddddd [.J dddd [E I eJ [+/-J ddd

where [item] indicates that item is optional, and ddd represents decimal,
octal, or hexadecimal digits.
INF = infinity; NAN =
nota number

In addition, +INF, -INF, +NAN, and -NAN are recognized as floatingpoint numbers. Note that the sign and capitalization are required.
%d, %i, %0, %x, %0, %1, %0, %X, %c, %n conversions
A pointer to unsigned character, unsigned integer, or unsigned long can
be used in any conversion where a pointer to a character, integer, or long
is allowed.

448

Borland C++ Library Reference

scant

Assignmentsuppression
character

The assignment-suppression character is an asterisk (*); it is not to be
confused with the C indirection (pointer) operator (also an asterisk).
If the asterisk follows the percent sign (%) in a format specifier, the next
input field will be scanned but will not be assigned to the next address
argument. The suppressed input data is assumed to be of the type
specified by the type character that follows the asterisk character.

The success of literal matches and suppressed assignments is not directly
determinable.
Width specifiers

The width specifier (n), a decimal integer, controls the maximum number
of characters that will be read from the current input field.
If the input field contains fewer than n characters, ... scanf reads all the
characters in the field, then proceeds with the next field and format
specifier.
If a whitespace or nonconvertible character occurs before width characters
are read, the characters up to that character are read, converted, and
stored, then the function attends to the next format specifier.

A nonconvertible character is one that cannot be converted according to
the given format (such as an 8 or 9 when the format is octal, or a J or K
when the format is hexadecilnal or decimal).
Width
specifier
n

Input-size and
argument-type
modifiers

How width of stored input is affected

Up to 11 characters are read, converted, and stored in the current
address argument.

The input-size modifiers (N and F) and argument-type modifiers (h, I, and
L) affect how the ... scanf functions interpret the corresponding address
argument arg[f.

F and N override the default or declared size of argo
h, I, and L indicate which type (version) of the following input data is to
be used (h = short, 1 = long, L = long double). The input data will be
converted to the specified version, and the arg for that input data should
point to an object of the corresponding size (short object for %h, long or
double object for %1, and long double object for %L).

Chapter 2, The run-time library

449

scant

Modifier

How conversion is affected

F

Overrides default or declared size; arg interpreted as far pointer.

N

Overrides default or declared size; arg interpreted as near pointer.
Cannot be used with any conversion in huge model.

h

For d, i, 0, U, x types, convert input to short int, store in short
object.
For 0, 1,0, U, X types, no effect.
For e, I, c, S,
For d, i, 0,

f1,

ll, X

P types, no effect.
types, convert input to long int, store in long object.

For e, I, g types, convert input to double, store in double object.
For 0, 1,0, U, X types, no effect.
For c, S,
L
When scant stops
scanning

f1,

P types, no effect.

For e, I, g types, convert input to a long double, store in long
double object. L has no effect on other formats.

scanf might stop scanning a particular field ~efore reaching the normal
field-end character (whitespace), or might terminate entirely, for a variety
of reasons.
scanf stops scanning and storing the current field and proceed to the next
input field if any of the following occurs:

• An assignment-suppression character (*) appears after the percent
character in the format specifier; the current input field is scanned but
not stored.
• width characters have been read (width = width specification, a positive
decimal integer in the format specifier).
• The next character read cannot be converted under the current format
(for example, an A when the format is decimal).
• The next character in the input field does not appear in the search set
(or does appear in an inverted search set).
When scanf stops scanning the current input field for one of these
reasons, the next character is assumed to be unread and to be the first
character of the following input field, or the first character in a subsequent
read operation on the input.
scanf will terminate under the following circumstances:

• The next character in the input field conflicts with a corresponding
non-whitespace character in the format string.
• The next character in the input field is EOF.

450

Borland C++ Library Reference

scant

a The format string has been exhausted.
If a character sequence that is not part of a format specifier occurs in the
format string, it must match the current sequence of characters in the
input field; scanf will scan but not store the matched characters. When a
conflicting character occurs, it remains in the input field as if it were never
read.
Return value

scanf returns the number of input fields successfully scanned, converted,

and stored; the return value does not include scanned fields that were not
stored.
If scanf attempts to read at end-of-file, the return value is EOF.
If no fields were stored, the return value is O.
See also

atof, cscanf, fscanf, getc, printf, sscanf, vfscanf, vscanf, vsscanf

Example

#include 
#include 
int main(void)
{

char label [20J,;
char name[20J;
int entries = 0;
int loop, age;
double salary;
struct Entry_struct
char name[20);
int age;
float salary;
entry [20J ;
/* input a label as character string restricted to 20 characters */
printf("\n\nPlease enter a label for the chart: ");
scan£("%20s", label);
fflush(stdin);
/* flush input stream in case of bad input */

•

/* input number of entries as integer */
printf("How many entries will there be? (less than 20) ");
scanf("%d", &entries);
/* flush the input stream in case of bad input */
fflush(stdin) ;
/* input a name, restricting input to only upper- or lowercase letters */
for (loop=O;loop
char *_searchenv(const char *file, const char *varname, char *buf>;

_searchenv attempts to locate file, searching along the path specified by

the DOS environment variable varname. Typical environment variables
that contain paths are PATH, LIB, and INCLUDE.
_searchenv searches for the file in the current directory of the current

drive first. If the file is not found there, the environment variable varname
is fetched, and each directory in the path it specifies is searched in turn
until the file is found, or the path is exhausted.
When the file is located, the full path name is stored in the buffer pointed
to by buf. This string can be used in a call to access the file (for example,

452

Borland C++ Library Reference

_searchenv

with fopen or exec ... ). The buffer is assumed to be large enough to store
any possible filename. If the file cannot be successfully located, an empty
string (consisting of only a null character) will be stored at buf.
Return value

None.

See also

exec ... , _dos_findfirst, _dos_findnext, spawn ... , system

Example

#incl ude 
#include 

int main(void)
{

/* looks for TLINK */
_searchenv ( TLINK. EXE PATH ", buf) ;
if (buf[O] == '\0')
printf("TLINK.EXE not found\n");
else
printf("TLINK.EXE found in %s\n", buf);
II

II ,

II

/* looks for non-existent file */
_searchenv("NOTEXIST.FIL","PATH",buf);
i f (bu f [ 0] == '\ 0 ' )
printf("NOTEXIST.FIL not found\n");
else
printf("NOTEXIST.FIL found in %s\n", buf);
return 0;

Program output
TLINK.EXE found in C:\BIN\TLINK.EXE
NOTEXIST.FIL not found

searchpath
Function
Syntax

Searches the DOS path for a file.
#include 
char *searchpath(const char *file);

Chapter 2, The run-time library

453

· searchpath

Remarks

search path attempts to locate file, searching along the DOS path, which is

the PATH= ... string in the environn1ent. A pointer to the complete pathname string is returned as the function value.
searchpath searches for the file in the current directory of the current
drive first. If the file is not found there, the PATH environment variable is
fetched, and each directory in the path is searched in turn until the file is
found, or the path is exhausted.

When the file is located, a string is returned containing the full path name.
This string can be used in a call to access the file (for example, with fopen
or exec ... ).
The string returned is located in a static buffer and is overwritten on each
subsequent call to searchpath.
Return value

search path returns a pointer to a file name string if the file is successfully
located; otherwise, search path returns null.

See also

exec ... , findfirst, findnext, spawn ... , system

Example

#include 
#include 
int main(void)
{

char *Pi
/* looks for TLINK and returns a pointer to the path */
p = searchpath ( "TLINK. EXE ") i
printf("Search for TLINK.EXE : %s\n", p) i
/* looks for non-existent file */
p = searchpath ( "NOTEXIST . FIL ") ;
printf("Search for NOTEXIST.FIL %s\n", p);
return 0;

Program output
Search for TLINK.EXE : C:\BIN\TLINK.EXE
Search for NOTEXIST.FIL : (NULL)

sector
Function
Syntax

454

Draws and fills an elliptical pie slice.
#include 

Borland C++ Library Reference

sector

void far sector(int x, int y, int stangle, int endangle, int xradius, int yradius);

Remarks

Draws and fills an elliptical pie slice using (x,y) as the center point, xradius
and yradius as the horizontal and vertical radii, respectively, and drawing
from stangle to endangle. The pie slice is outlined using the current color,
and filled using the pattern and color defined by setfillstyle or
setfillpattern.

The angles for sector are given in degrees. They are measured counterclockwise with 0 degrees at 3 0' clock, 90 degrees at 12 0' clock, and so on.

If an error occurs while the pie slice is filling, graphresult returns a value
of -6 (grNoScanMem).
Return value

None.

See also

arc, circle, ellipse, getarccoords, getaspectratio, graphresult, pieslice,
setfillpattern, setfillstyle, setgraphbufsize

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */

int
int
int
int

gdriver = DETECT, gmode, errorcode;
midx, midy, i;
stangle = 45, endangle = 135;
xrad = lOa, yrad = 50;

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf ("Graphics error: %s \n", grapherrormsg (errorcode) ) ;
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */

midx = getmaxx() / 2;
midy = getmaxy() / 2;
/* loop through the fill patterns */

Chapter 2, The run-time library

455

sector

for (i=EMPTY_FILL; i
void segreadCstruct SREGS *segp);

segread places the current values of the segment registers into the
structure pointed to by segp.

This call is intended for use with intdosx and int86x.
Return value

None.

See also

FP_OFF, int86, int86x, intdos, intdosx, MK_FP, movedata

Example

#inc1ude 
#include 
int main (void)
{

struct SREGS segs;
segread(&segs) ;
printf("Current segment register settings\n\n");
printf("CS: %X DS: %X\n", segs.cs, segs.ds);
printf("ES: %X SS: %X\n", segs.es, segs.ss);
return 0;

456

Borland C++ Library Reference

setactivepage

setactivepage
Function
Syntax

Remarks

Sets active page for graphics output.
#include 
void far setactivepage(int page);

setactivepage makes page the active graphics page. All subsequent
graphics output will be directed to that graphics page.

The active graphics page might not be the one you see onscreen,
depending on how many graphics pages are available on your system.
Only the EGA, VGA, and Hercules graphics cards support multiple pages.
Return value

None.

See also

setvisualpage

Example

#ind ude
#include
#include
#include






int main(void)
{

/* select driver and mode that supports mUltiple pages */
int gdriver = EGA, gmode = EGAHI, errorcode;
int x, y, ht;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{

printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(l);
/* terminate with an error code */
x = getmaxx() / 2;
y = getmaxy() ) 2;
ht = textheight ( "W" ) ;

Chapter 2, The run-time library

457

setactivepage

/* select the off screen page for drawing */
setactivepage(l);
/* draw a line on page #1 */
line(O, 0, getmaxx(), getmaxy());

/* output a message on page #1 */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy (x, y, "This is page #1:");
outtextxy(x, y+ht, "Press any key to halt:");
/* select drawing to page #0 */
setactivepage(O) ;
/* output a message on page #0 */
outtextxy (x, y, "This is page #0.");
outtextxy(x, y+ht, "Press any key to view page #1:");
getch() ;
/* select page #1 as the visible page */
setvisualpage(l) ;
/* clean up */
getch () ;
closegraph ( ) ;
return 0;

se'~allpalette
Function
Syntax

Remarks

Changes all palette colors as specified.
#include 
void far setallpalette(struct palettetype far *palette);

setallpalette sets the current palette to the values given in the palettetype
structure pointed to by palette.

You can partially (or completely) change the colors in the EGA/VGA
palette with setallpalette.
The MAXCOLORS constant and the palettetype structure used by
setallpalette are defined in graphics.h as follows:
#define MAXCOLORS

15

struct palettetype

458

Borland C++ Library Reference

setallpalette

unsigned char size;
signed char colors [MAXCOLORS + 1];
};

size gives the number of colors in the palette for the current graphics
driver in the current mode.
colors is an array of size bytes containing the actual raw color numbers for
each entry in the palette. If an element of colors is -1, the palette color for
that entry is not changed.
The elements in the colors array used by setallpalette can be represented
by symbolic constants defined in graphics.h.
Table 2.6
Actual color table

eGA
Name

BLACK
BLUE
GREEN
CYAN
RED
MAGENTA
BROWN
LIGHTGRAY
DARKGRAY
LIGHTBLUE
LIGHTGREEN
LIGHTCYAN
LIGHTRED
LIGHTMAGENTA
YELLOW
WHITE

EGAlVGA
Value

0
1
2
3
4
5
6
7
8
9
10
11

12
13
14
15

Name

EGA_BLACK
EGA_BLUE
EGA_GREEN
EGA_CYAN
EGA_RED
EGA_MAGENTA
EGA_LIGHTGRAY
EGA_BROWN
EGA_DARKGRAY
EGA_LIGHTBLUE
EGA_LIGHTGREEN
EGA_LIGHTCYAN
EGA_LIGHTRED
EGA_LIGHTMAGENTA
EGA_YELLOW
EGA_WHITE

Value

0
1
2
3
4
5
7
20
56
57
58
59
60
61
62
63

Note that valid colors depend on the current graphics driver and current
graphics mode.
Changes made to the palette are seen immediately onscreen. Each time a
palette color is changed, all occurrences of that color onscreen will change
to the new color value.
..
Return value

setallpalette cannot be used with the IBM-8S14 driver.

If invalid input is passed to setallpalette, graphresult returns -11
(grError), and the current palette remains unchanged.

See also

getpalette, getpalettesize, graphresult, setbkcolor, setcolor, setpalette

Example

#include 
#include 
#include 

Chapter 2, The run-time library

459

setallpalette

#include 
int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
struct palettetype pal;
int color, maxcolor, ht;
int y = 10;
char msg[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{

printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */
maxcolor = getmaxcolor();
ht = 2 * textheight ( OW" ) ;
/* grab a copy of the palette */
getpalette(&pal) ;
/* display the default palette colors */
for (color=l;color<=maxcolor; color++)
setcolor(color) ;
sprintf(msg, "Color: %d", color);
outtextxy(l, y, msg);
y += ht;
/* wait for a key */
getch () ;
/* black out the colors one by one */
for (co10r=1; color<=maxcolor; color++)
setpa1ette(color, BLACK);
getch () ;
/* restore the palette colors */
setal1pa1ette(&pal);
/* clean up */
getch();
closegraph ( ) ;

460

Borland C++ Library Reference

setaspectratio

return 0;

setospectrotio
Function
Syntax

Remarks

Changes the default aspect ratio correction factor.
#include 
void far setaspectratio(int xasp, int yasp);

setaspectratio changes the default aspect ratio of the graphics system. The

graphics system uses the aspect ratio to make sure that circles are round
onscreen. If circles appear elliptical, the monitor is not aligned properly.
You could correct this in the hardware by realigning the monitor, but it's
easier to change in the software by using setaspectratio to set the aspect
ratio. To obtain the current aspect ratio from the system, call
getaspectratio.
Return value

None.

See also

circle, getaspectratio

Example

#include
#include
#include
#include






int main(void)
{

•

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int xasp, yasp, midx, midy;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{

print f ( "Graphics error: %s \n", grapherrormsg (errorcode) ) ;
printf("Press any key to halt:");
getch() ;
exit(l) ;
/* terminate with an error code */

Chapter 2, The run-time library

461

setaspectratio

midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor()) ;
/* get current aspect ratio settings */
getaspectratio(&xasp, &yasp);
/* draw normal circle */
circle(midx, midy, 100);
getch() ;
/* clear the screen */
cleardevice() ;
/* adjust the aspect for a wide circle */
setaspectratio(xasp/2, yasp);
circle (midx, midy, 100);
getch () ;
/* adjust the aspect for a narrow circle */
cleardevice();
setaspectratio(xasp, yasp/2);
circle (midx, midy, 100);
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

setbkcolor
Function
Syntax

Sets the current background color using the palette.
#include 
void far setbkcolor(int color);
DOS

Remarks

462

setbkcolor sets the background to the color specified by color. The
argument color can be a name or a number, as listed in the following table:

Borland C++ Library Reference

setbkcolor

Number

0
1
2
3
4
5

These symbolic
names are defined
in graphics.h.

Name

BLACK
BLUE
GREEN
CYAN
RED
MAGENTA
BROWN
LIGHTGRAY

6
7

Number

8
9
10
11
12
13
14
15

Name

DARKGRAY
LIGHTBLUE
LIGHTGREEN
LIGHTCYAN
LIGHTRED
LIGHTMAGENTA
YELLOW
WHITE

For example, if you want to set the background color to blue, you can call
setbkcolor(BLUE) /* or */ setbkcolor(l)

On eGA and EGA systems, setbkcolor changes the background color by
changing the first entry in the palette.
..

Return value

If you use an EGA or a VGA, and you change the palette colors with
setpalette or setallpalette, the defined symbolic constants might not give
you the correct color. This is because the parameter to setbkcolor indicates
the entry number in the current palette rather than a specific color (unless
the parameter passed is 0, which always sets the background color to
black).

None.

See also

getbkcolor, setallpalette, setcolor, setpalette

Example

#inc1ude
#include
#include
#include






int main (void)
{

•

/* select driver and mode that supports multiple background colors */
int gdriver = EGA, gmode = EGAHI, errorcode;
int bkcol, maxcolor, x, y;
char msg[80];

graphics and local variables */
initgraph(&gdriver, &gmode, 1111);
/*

initializ~

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */

Chapter 2, The run-time library

463

setbkcolor

/* maximum color index supported */
maxcolor = getmaxcolor();
/* for centering text messages */
settextjustify(CENTER_TEXT, CENTER_TEXT);
x = getmaxx() / 2;
y = getmaxy() / 2;
/* loop through the available colors */
for (bkcol=O; bkcol<=maxcolor; bkcoltt)
/* clear the screen */
cleardevice() ;
/* select a new background color */
setbkcolor(bkcol);
/* output a messsage */
if (bkcol == WHITE)
setcolor(EGA_BLUE);
sprintf(msg, "Background color: %d", bkcol);
outtextxy(x, y, msg);
getch () ;
/* clean up */
closegraph ( ) ;
return 0;

setblock, _dos_setblock
Function
Syntax

Remarks

Modifies the size of a previously allocated block.
#include 
int setblock(unsigned segx, unsigned newsize);
unsigned _dos_setblock(unsigned newsize, unsigned segx,
unsigned *maxp);

setblock and _dos_setblock modify the size of a memory segment. segx is
the segment address returned by a previous call to allocmem or
_dos_allocmem. newsize is the new, requested size in paragraphs. If the
sement cannot be changed to the new size, _dos_setblock stores the size of

the largest possible segment at the location pointed to by maxp.

464

Borland C++ Library Reference

setblock, _dos_setblock

Return value

setblock returns -1 on success. In the event of error, it returns the size of

the largest possible block (in paragraphs), and the global variable

_doserrno is set.
_dos_setblock returns 0 on success. In the event of error, it returns the

DOS error code, and the global variable errno is set to the following:
ENOMEM Not enough memory, or bad segment address
See also

allocmem, freemem

Example

#include
#include
#include
#include






int main(void)

/* Example for setblock. */

{

unsigned int size, segp;
int stat;
size = 64;
/* (64 x 16)
1024 bytes */
stat = allocmem(size, &segp);
if (stat == -1)
printf("Allocated memory at segment: %X\n", segp);
else {
printf("Failed: maximum number of paragraphs available is %d\n", stat);
exit(l) ;
stat = setblock(segp, size * 2);
if (stat== -1)
printf ("Expanded memory blo'ck at segment: %X\n", segp);
else
printf("Failed: maximum number of paragraphs available is %d\n", stat);
freemem(segp) ;
return 0;

•

#include 
#include 
int main(void)

/* Example for _dos_setblock. */

{

unsigned int size, segp, err, maxb;
size = 64; /* (64 x 16) = 1024 bytes */
err = _dos_allocmem(size, &segp);
if (err == 0)
printf ("Allocated memory at segment: %x\n", segp);
else {
perror("Unable to allocate block");

Chapter 2, The run-time library

465

setblock, _dos_setblock

printf (IlMaximum no. of paragraphs available is %u\n", segp);
return 1;
if (_dos_setblock(size * 2, segp, &maxb) == 0)
printf("Expanded memory block at segment: %X\n", segp);
else {
perror(IlUnable to expand block");
printf(IlMaximum no. of paragraphs available is %u\n", maxb);
_dos_freemem(segp);
return 0;

setbuf
Function
Syntax

Remarks

Assigns buffering to a stream.
#include 
void setbuf(FILE *stream, char *buf);

a buffering instead of an
automatically allocated buffer. It is used after stream has been opened.

setbuf causes the buffer buf to be used for 1/

If buf is null, I/O will be unbuffered; otherwise, it will be fully buffered.
The buffer must be BUFSIZ bytes long (specified in stdio.h).

stdin and stdout are unbuffered if they are not redirected; otherwise, they
are fully buffered. setbuf can be used to change the buffering style being
used.
Unbuffered means that characters written to a stream are immediately
output to the file or device, while buffered means that the characters are
accumulated and written as a block.
setbuf produces unpredictable results unless it is called immediately after
opening stream or after a call to fseek. Calling setbuf after stream has been
unbuffered is legal and will not cause problems.

A common cause for error is to allocate the buffer as an automatic (local)
variable and then fail to close the file before returning from the function
where the buffer was declared.
Return value

466

None.

Borland C++ Library Reference

setbuf

See also

fflush, fopen, fseek, setvbuf

Example

#include 
/* bufsiz is defined in stdio.h */
char outbuf[BUFSIZ];

int main(void)
{

/* attach buffer to standard output stream */
setbuf(stdout, outbuf);

/* put some characters into the buffer */
puts("This is a test of buffered output.\n\n");
puts("This output will go into outbuf\n");
puts("and won't appear until the buffer\n");
puts("fills up or we flush the stream.\n");
/* flush the output buffer */
fflush(stdout) ;
return 0;

setcbrk
Function
Syntax

Remarks

Sets control-break setting.
#include 
int setcbrk(int cbrkvalue);

setcbrk uses the DOS system call Ox33 to turn control-break checking on

or off.

Return value

value = a

Turns checking off (check only during I/O to console,
printer, or communications devices).

value = 1

Turns checking on (check at every system call).

setcbrk returns cbrkvalue, the value passed.

See also

getcbrk

Example

#include 
#include 
#include 

Chapter 2, The run-time library

467

setcbrk

int main(void)
{

int break_flag;
printf("Enter 0 to turn control break off\n");
printf("Enter 1 to turn control break on\n");
break_flag = getch() - 0;
setcbrk(break_flag) ;
if (getcbrk())
printf("Cntrl-brk flag is on\n");
else
printf("Cntrl-brk flag is off\n");
return 0;

setcolor
Function
Syntax

Remarks

Sets the current drawing color using the palette.
#include 
void far setcolor(int color);

setcolor sets the current drawing color to color, which can range from 0 to
getmaxcolor.

The current drawing color is the value to which pixels are set when lines,
and so on are drawn. The following tables show the drawing colors
available for the eGA and EGA, respectively.
Constant assigned to color number (pixel value)
Palette

a
1
2

3

CGA_LIGHTGREEN
CGA_LIGHTCYAN
CGA_GREEN
CGA_CYAN

Numeric value

0
1
2

3
4
5

468

3

2

number

BLACK
BLUE
GREEN
CYAN
RED
MAGENTA

CGA_LIGHTRED
CGA_LIGHTMAGENTA

CGA_YELLOW
CGA_WHITE
CGA_BROWN
CGA_LIGHTGRAY

Symbolic name

8
9
10
11

12
13

DARKGRAY
LIGHTBLUE
LIGHTGREEN
LIGHTCYAN
LIGHTRED
LIGHTMAGENTA

Borland C++ Library Reference

setcolor

6
7

BROWN

LIGHTGRAY

14
15

YELLOW

WHITE

You select a drawing color by passing either the color number itself or the
equivalent symbolic name to setcolor. For example, in CGACO mode, the
palette contains four colors: the background color, light green, light red,
and yellow. In this mode, either setcolor(3) or setcolor(CGA_YELLOW)
selects a drawing color of yellow.
Return value

None.

See also

getcolor, getmaxcolor, graphresult, setallpalette, setbkcolor, setpalette

Example

#include
#include
#include
#include






int main(void)
{

/* select driver and mode that supports mUltiple drawing colors */
int gdriver = EGA, gmode = EGAHI, errorcode;
int color, maxcolor, x, y;
char msg[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{

printf("Graphics error: %s\n", grapherrormsg(errorcode));
print f ( "Press any key to halt:") ;
getch() ;
exit(l);
/* terminate with an error code */
/*. maximum color ihdex supported * /
maxcolor = getmaxcolor();
/* for centering text messages */
settextjustify(CENTER_TEXT, CENTER_TEXT);
x = getmaxx() / 2;
y = getmaxy() / 2;
/* loop through the available colors */
for (color=l; color<=maxcolor; color++)
cleardevice();
/* clear the screen */
setcolor(color);
/* select new background color */

/* output a messsage */

Chapter 2, The run-time library

469

setcolor

sprintf(msg, "Color: %d", color);
outtextxy(x, y, msg);
getch();

/ * clean up * /
closegraph ( ) ;
return 0;

_setcursortype
Function
Syntax

Remarks

Selects cursor appearance.
#include 
void _setcursortype

int main (void)
{

/* display the normal cursor */
cprintf("\n\rNormal Cursor: ");
getch () ;
/* turn off the cursor */
_setcursortype(_NOCURSOR) ;
cprintf("\n\rNo Cursor
getch() ;

"I;

/* switch to a solid cursor */
_setcursortype(_SOLIDCURSOR) ;
cprintf("\n\rSolid Cursor: ");
getch() ;
/* switch back to the normal cursor */
_setcursortype(_NORMALCURSOR);
cprintf("\n\rNormal Cursor: ");

470

Borland C++ Library Reference

_setcursortype

getch () ;
return 0;

setdta
Function
Syntax

Remarks

Sets disk-transfer address.
#inc1ude 
void setdta(char far *dta);

setdta changes the current setting of the DOS disk-transfer address (Dr A)

to the value given by dta.
Return value

None.

See also

getdta

Example

#include
#include
#include
#include






int main (void)
{

char line[801, far *save_dta;
char buffer[2561
"SETDTA test!";
struct fcb blk;
int result;
/* get new file name from user. */
printf("Enter a file name to create:");
gets(line) ;

I

/* parse the new file name to the dta */
parsfnm(line, &blk, 1);
printf("%d %s\n", blk.fcb_drive, blk.fcb_name);
/* request DOS services to create file */
if (bdosptr(Ox16, &blk, 0) == -1) {
perror("Error creating file");
exit(l) ;
/* save old dta and set new dta */
save_dta = getdta();

Chapter 2, The run-time library

471

setdta

setdta (buffer) ;
/* write new records */
blk.fcb_recsize = 256;
blk.fcb_random = OL;
result = randbwr(&blk, 1);
printf("result = %d\n", result);

if (!result)
printf("Write OK\n");
else {
perror("Disk error");
exit (1) ;
/* request DOS services to close the file */
if (bdosptr(Ox10, &blk, 0) == -1) {
perror("Error closing file");
exi t (1) ;
/* reset the old dta */
setdta(save_dta);

return 0;

setfillpattern
Function
Syntax

Remarks

Selects a user-defined fill pattern.
#include 
void far setfillpattern(char far *upattern, int color);

setfillpattern is like setfillstyle, except that you use it to set a user-defined
8x8 pattern rather than a predefined pattern.

upattern is a pointer to a sequence of 8 bytes, with each byte corresponding to 8 pixels in the pattern. Whenever a bit in a pattern byte is set
to 1, the corresponding pixel is plotted.
Return value

472

None.

See also

getfillpattern, getfillsettings, graphresult, sector, setfillstyle

Example

#include 
#include 

Borland C++ Library Reference

setfillpattern

#include 
#include 
int main(void)
{

4

/* request autodetection */

int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;
/* a user-defined fill pattern */
char pattern[8] = {OxOO, Ox70, Ox20, Ox27, Ox24, Ox24, Ox07, OxOO};
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{

printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */
maxx = getmaxx();
maxy = getmaxy();
setcolor(getmaxcolor()) ;
/* select a user-defined fill pattern */
setfillpattern(pattern,'getmaxcolor()) ;
/* fill the screen with the pattern */
bar(O, 0, maxx, maxy);

/* clean up */
getch() ;
closegraph ( ) ;
return 0;

setfillstyle
Function
Syntax

Sets the fill pattern and color.
#include 
void far setfillstyle(int pattern, int color);

Chapter 2, The run-time library

473

setfillstyle

Remarks

setfillstyle sets the current fill pattern and fill color. To set a user-defined
fill pattern, do not give a pattern of 12 (USER_FILL) to setfillstyle; instead,
call setfillpattern.

The enumeration ft1Cpatterns, defined in graphics.h, gives names for the
predefined fill patterns, plus an indicator for a user-defined pattern.
Value

Name

EMPTY_FILL
SOLID_FILL
LINE_FILL
LTSLASH_FILL
SLASH_FILL
BKSLASH_FILL
LTBKSLASH_FILL
HATCH_FILL
XHATCH_FILL
INTERLEAVE_FILL
WIDE_DOT _FILL
CLOSE_DOT_FILL
USER_FILL

a
1
2

3
4
5
6
7
8
9
10
11
12

Description

Fill with background color
Solid fill
Fill with-Fill with / / /
Fill with / / /, thick lines
Fill with \ \ \, thick lines
Fill with \ \ \
Light hatch fill
Heavy crosshatch fill
Interleaving line fill
Widely spaced dot fill
Closely spaced dot fill
User-defined fill pattern

All but EMPTY_FILL fill with the current fill color; EMPTY_FILL uses the
current background color.
If invalid input is passed to setfillstyle, graphresult returns -11 (grError),
and the current fill pattern and fill color remain unchanged.
Return value

None.

See also

bar, bar3d, fill poly, floodfill, getfillsettings, graphresult, pieslice, sector,
setfill pattern

Example

#include
#include
#include
#include
#include







/* the names of the fill styles supported */
char *fname[] = { "EMPTY_FILL", "SOLID_FILL", "LINE_FILL", "LTSLASH_FILL",
"SLASH_FILL" , "BKSLASH_FILL", "LTBKSLASH_FILL", "HATCH_FILL",
"XHATCH_FILL", "INTERLEAVEJILL", "WIDE_OOT_FILL",
"CLOSE_OOTJILL", "USER_FILL" };

int main (void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;

474

Borland C++ Library Reference

setfillstyle

int style, midx, midy;
char stylestr[40];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */

midx = getmaxx() / 2;
midy = getmaxy() / 2;
for (style = EMPTY_FILL; style < USER_FILL; style++) {
/* select the fill style */
setfillstyle(style, getmaxcolor());
/* convert style into a string */
strcpy(stylestr, fname[style]);

/ * fill a bar * /
_ barJd(O, 0, midx-10, midy, 0, 0);
/* output a message */
outtextxy(midx, midy, stylestr);
/* wait for a key */
getch () ;
cleardevice ( ) ;
/* clean up */
getch();
closegraph ( ) ;
return 0;

•

setgraphbufsize
Function

Changes the size of the internal graphics buffer.

Syntax

#include 
unsigned far setgraphbufsize(unsigned bu/size);

Chapter 2, The run-time library

475

setgraphbufsize

Remarks

Some of the graphics routines (such as floodfill) use a memory buffer that
is allocated when initgraph is called, and released when closegraph is
called. The default size of this buffer, allocated by _graphgetmem, is 4,096
bytes.
You might want to make this buffer smaller (to save memory space) or
bigger (if, for example, a call to floodfill produces error -7: Out of flood
memory).
setgraphbufsize tells initgraph how much memory to allocate for this
internal graphics buffer when it calls _graphgetmem.

...

You must call setgraphbufsize before calling initgraph. Once initgraph has
been called, all calls to setgraphbufsize are ignored until after the next call
to closegraph.

Return value

setgraphbufsize returns the previous size of the internal buffer.

See also

closegraph, _graphfreemem, _graphgetmem, initgraph, sector

Example

#include
#include
#include
#include






#define BUFSIZE 1000 /* internal graphics buffer size */
int main(void)
(

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int x, y, oldsize;
char msg [80 J ;
/* set size of internal graphics buffer before calling initgraph */
oldsize = setgraphbufsize(BUFSIZE);
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) ( /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
print f ( "Press any key to halt:");
getch();
exit(l);
/* terminate with an error code */

476

Borland C++ Library Reference

setgraphbufsize

x = getmaxx() / 2;
y = getmaxy() / 2;
/* output some messages */
sprintf (msg , "Graphics buffer size: %d" BUFSIZE);
settextjustify(CENTER_TEXT , CENTER_TEXT);
outtextxy(x , y, msg);
sprintf (msg , "Old graphics buffer size: %d" oldsize);
outtextxy (x, y+textheight ("vi") msg);
I

I

I

/* clean up */
getch() ;
closegraph () ;
return 0;

setgraphmode
Function
Syntax

Remarks

Sets the system to graphics mode and clears the screen.
#include 
void far setgraphmode(int mode);

setgraphmode selects a graphics mode different than the default one set
by initgraph. mode must be a valid mode for the current device driver.
setgraphmode clears the screen and resets all graphics settings to their
defaults (current position, palette, color, viewport, and so on) .

You can use setgraphmode in conjunction with restorecrtmode to switch
back and forth between text and graphics modes.
Return value

If you give setgraphmode an invalid mode for the current device driver,
graphresult returns a value of -10 (grInvalidMode).

See also

getgraphmode, getmoderange, graphresult, initgraph, restorecrtmode

Example

#include
#include
#include
#include






int main(void)
{

/* request autodetection */

Chapter 2, The run-time library

477

•

setgraphmode

int gdriver
int x, y;

= DETECT, gmode, errorcode;

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, ""I;

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */

x
y

getmaxx()
getmaxy ( )

2;
2;

/* output a message */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "Press any key to exit graphics:");
getch() ;
/* restore system to text mode */
restorecrtmode();
printf("We're now in text mode.\n");
printf("Press any key to return to graphics mode:");
getch();
/* return to graphics mode */
setgraphmode(getgraphmode());
/* output a message */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "We're back in graphics mode.");
outtextxy (x, y+textheight ("W"), "Press any key to halt:");

/* clean up */
getch() ;
closegraph ( ) ;
return 0;

setjmp

478

Function

Sets up for nonlocal goto.

Syntax

#include 
int setjmp(jmp_buf jmpb);

Borland C++ Library Reference

setjmp

Remarks

setjmp captures the complete task state in jmpb and returns O.

A later call to longjmp with jmpb restores the captured task state and
returns in such a way that setjmp appears to have returned with the value
val.
A task state is
• all segment registers (CS, OS, ES, 55)

On

• register variables (51,
• stack pointer (SP)
• frame base pointer (BP)

• flags
A task state is complete enough that setjmp can be used to implement
coroutines.
setjmp must be called before longjmp. The routine that calls setjmp and
sets up jmpb must still be active and cannot have returned before the
longjmp is called. If it has returned, the results are unpredictable.
setjmp is useful for dealing with errors and exceptions encountered in a
low-level subroutine of a program.

..

You can't use setjmp and longjmp for implementing co-routines if your
program is overlaid. Normally, setjmp and longjmp save and restore all
the registers needed for co-routines, but the overlay manager needs to
keep track of stack contents and assumes there is only one stack. When
you implement co-routines there are usually either two stacks or two
partitions of one stack, and the overlay manager will not track them
properly.
You can have background tasks which run with their own stacks or
sections of stack, but you must ensure that the background tasks do not
invoke any overlaid code, and you must not use the overlay versions of
setjmp or longjmp to switch to and from background. When you avoid
using overlay code or support routines, the existence of the background
stacks does not disturb the overlay manager.

Return value
See also

setjmp returns· 0 when it is initially called. If the return is from a call to
longjmp, setjmp returns a nonzero value (as in the example).
longjmp, signal

Chapter 2, The run-time library

479

•

setjmp

Example

#include 
#include 
#include 
void subroutine (void) ;
jmp_buf jumper;
int main ()
{

int value;
value = setjmp(jumper);
if (value != 0) {
printf("Longjmp with value %d\n", value);
exit (value) ;
printf("About to call subroutine ... \n");
subroutine() ;
return 0;
void subroutine (void)
longjmp(jumper,l) ;

setlinestyle
Function

Syntax

Remarks

Sets the current line width and style.
#include 
void far setlinestyleCint linestyle, unsigned upattern, int thickness);

setlinestyle sets the style for all lines drawn by line, lineto, rectangle,
drawpoly, and so on.

The linesettingstype structure is defined in graphics.h as follows:
struct linesettingstype
int linestyle;
unsigned upattern;
int thickness;
};

480

Borland C++ Library Reference

setlinestyle

linestyle specifies in which of several styles subsequent lines will be drawn
(such as solid, dotted, centered, dashed). The enumeration line_styles,
defined in graphics.h, gives names to these operators:"
Name

Value

SOLID_LINE
DOTTED_LINE
CENTER_LINE
DASHED_LINE
USERBIT_LINE

0
1
2
3
4

Descrip.tion

Solid line
Dotted line
Centered line
Dashed line
User-defined line style

thickness specifies whether the width of subsequent lines drawn will be
normal or thick.
Name

Value

NORM_WIDTH
THICK_WIDTH

1
3

Description

1 pixel wide
3 pixels wide

upattern is a 16-bit pattern that applies only if linestyle is USERBIT_LINE
(4). In that case, whenever a bit in the pattern word is 1, the corresponding
pixel in the line is drawn in the current drawing color. For example, a
solid line corresponds to a upattern of OxFFFF (all pixels drawn), while a
dashed line can correspond to a upattern of Ox3333 or OxOFOF. If the
linestyle parameter to setlinestyle is not USERBIT_LINE (in other words, if
it is not equal to 4), you must still provide the upattern parameter, but it
will be ignored.
~

Return value

The linestyle parameter does not affect arcs, circles, ellipses, or pie slices.
Only the thickness parameter is used.
If invalid input is passed to setlinestyle, graphresult returns -11, and the
current line style remains unchanged.

See also

arc, bar3d, circle, drawpoly, ellipse, getlinesettings, graphresult, line,
linerel, lineto, pieslice, rectangle

Example

#include
#include
#include
#include
#include







/* the names of the line styles supported */
char *lname[] = { "SOLID_LINE", "DOTTED_LINE", "CENTER_LINE", "DASHED_LINE",
"USERBIT_LINE" };
int main(void)
{

Chapter 2, The run-time library

481

•

setlinestyle

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int style, midx, midy, userpat;
char stylestr[40];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, ""I;
/* read result of initialization */
errorcode = graphresult();
if (errorcode ! = grOk) { / * an error occurred * /
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf ( "Press any key to halt:") ;
getch () ;
/* terminate with an error code */
exit(l);

midx = getmaxx() / 2;
midy = getmaxy() / 2;
/* a user-defined line pattern */

/ * binary: "0000000000000001" * /
userpat = 1;
for (style=SOLID_LINE; style<=USERBIT_LINE; stylett)
{

/* select the line style */
setlinestyle(style, userpat, 1);

/* convert style into a string */
strcpy(stylestr, lname[style]);
/* draw a line */
line(O, 0, midx-10, midy);

/* draw a rectangle */
rectangle(O, 0, getmaxx(), getmaxy());
/* output a message */
outtextxy(midx, midy, stylestr);
/* wait for a key */
getch();
cleardevice ( ) ;
/* clean up */
closegraph() ;
return 0;

482

Borland C++ Library Reference

setlocole

setlocole
Function
Syntax

Remarks

Selects a locale.
#include 
char *setlocale(int category, char *locale);

Borland C++ supports only the "C" locale at present, so invoking this
function has no effect.
Possible values for the argument category:
LC_ALL
LC_COLLATE
LC_CTYPE
LC_MONETARY
LC_NUMERIC
LC_TIME

Return value

If selection is successful, a string is returned to indicate the locale that was
in effect prior to invoking the function. If it is not successful, a NULL
pointer is returned.

See also

localeconv

Example

#include 
#include 
int main( void)
{

char *old_locale;
/* only locale supported in Borland Ctt is "CO */
old_locale = set locale (LC_ALL, "C");
printf ("Old locale was %s \n" , old_locale) ;
return 0;

setmem
Function

Assigns a value to a range of memory.

Chapter 2, The run-time library

483

setmem

Syntax

Remarks
Return value

#include 
void setmem(void *dest, unsigned length, char value);

setmem sets a block of length bytes, pointed to by dest, to the byte value.

None.

See also

memset, strset

Example

#include 
#include 
#include 
int main (void)
{

char *dest;
dest = (char *) calloc(21, sizeof(char));
setmem(dest, 20, 'c');
printf("%s\n", dest);
return 0;

setmode
Function
Syntax

Remarks

Return value

Sets mode of an open file.
#include 
int setmode(int handle, int amode);

setmode sets the mode of the open file associated with handle to either
binary or text. The argument amode must have a value of either
a_BINARY or a_TEXT, never both. (These symbolic constants are defined
in fcntl.h.)
setmode returns the previous translation mode if successful. On error it

returns -1 and sets the global variable errno to
EINVAL
See also

484

Invalid argument

_creat, creat, _open, open

Borland C++ Library Reference

setmode

Example

#inc1ude 
#include 
#include do. h>
int main(void)
{

int result;
result = setmode(fileno(stdprn), O_TEXT);
if (result == -1)
perror("Mode not available\n");
else
printf("Mode successfully switched\n");
return 0;

Function
Syntax

Remarks

Sets the function to be called when a request for memory allocation
cannot be satisfied.
#include 
void ( * set_new_handler(void (* my_handler)O »0;

set_new_handler sets the function to be called when operator new cannot
allocate the requested memory. By default operator new will return zero if

it cannot allocate memory. You can affect this default behavior by setting
a new handler and calling set_new_handler.
If new cannot allocate the requested memory it calls the handler that was
set by a previous call to set_new_handler. my_handler should specify the
actions to be taken when new cannot satisfy a request for memory
allocation. If my_handler returns, then new will again attempt to satisfy the
request.

Ideally, tny_handler would free up memory and return. new would then be
able to satisfy the request and the program would continue. However, if
my_handler cannot provide memory for new, my_handler must terminate
the program. Otherwise, an infinite loop will be created.
The default handler is reset by set_new_handler(O).
Preferably, you should overload the operator newO to take appropriate
actions for your applications.

Chapter 2, The run-time library

485

Return value

set_new_handler returns the old handler, if it has been defined. By
default, no handler is installed.

The user-defined argument function, my_handler, should not return a
value.
See Also

_new_handler (global variable)

Example

#include 
#include 
#include 
void mem_warn() {
cerr « "\nCannot allocate!";
exit (1) ;
}

void main(void)
set_new_handler(mem_warn) ;
char *ptr = new char[lOO);
cout « "\nFirst allocation: ptr = " « hex « long(ptr);
ptr = new char[64000U);
cout « "\nFinal allocation: ptr = " « hex « long(ptr);
set_new_handler(O); II Reset to default.
}

Program output
First allocation: ptr = 283eOf30
Cannot allocate!

setpalette
Function
Syntax

Remarks

Changes one palette color.
#include 
void far setpalette(int colornum, int color);

setpalette changes the colornum entry in the palette to color. For example,
setpalette(O,5) changes the first color in the current palette (the back-

ground color) to actual color number 5. If size is the number of entries in
the current palette, colornum can range between 0 and (size -1).
You can partially (or completely) change the colors in the EGA/VGA
palette with setpalette. On a CGA, you can only change the first entry in

486

Borland C++ Library Reference

setpalette

the palette (colornum equals 0, the background color) with a call to
setpalette.

The color parameter passed to setpalette can be represented by symbolic
constants defined in graphics.h.
eGA

EGAlVGA

Value

Name

BLACK
BLUE
GREEN
CYAN
RED
MAGENTA
BROWN
LIGHTGRAY
DARKGRAY
LIGHTBLUE
LIGHTGREEN
LIGHTCYAN
LIGHTRED
LIGHTMAGENTA
YELLOW
WHITE

0
1
2
3
4
5
6
7
8
9
10
11

12
13

14
15

Name

EGA_BLACK
EGA_BLUE
EGA_GREEN
EGA_CYAN
EGA_RED
EGA_MAGENTA
EGA_LIGHTGRAY
EGA_BROvVN
EGA_DARKGRAY
EGA_LIGHTBLUE
EGA_LIGHTGREEN
EGA_LIGHTCYAN
EGA_LIGHTRED
EGA_LIGHTMAGENTA
EGA_YELLOW
EGA_WHITE

Value

0
1
2
3
4
5
7
20
56
57
58
59
60
61
62
63

Note that valid colors depend on the current graphics driver and current
graphics mode.
Changes made to the palette are seen immediately onscreen. Each time a
palette color is changed, all occurrences of that color onscreen change to
the new color value.
..

setpalette cannot be used with the IBM-8514 driver; use setrgbpalette

instead.
Return value

If invalid input is passed to setpalette, graphresult returns -11, and the

current palette remains unchanged.
See also

getpalette, graphresult, setallpalette, setbkcolor, setcolor, setrgbpalette

Example

#include
#include
#include
#include






int main (void)
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int color, maxcolor, ht;

Chapter 2, The run-time library

487

setpalette

int y = 10;
char msg[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode ! = grOk) { / * an error occurred * /
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */

maxcolor = getmaxcolor();
ht = 2 * textheight("W");
/* display the default colors */
for (color=l; color<=maxcolor; color++)
setcolor(color) ;
sprintf(msg, "Color: %d", color);
outtextxy(l, y, msg);
y += ht;
/* wait for a key */
getch() ;

/* black out the colors one by one */
for (color=l; color<=maxcolor; color++)
setpalette(color, BLACK);
getch() ;

/* clean up */
closegraph();
return 0;

setrgbpalette
Function
Syntax

488

Allows user to define colors for the IBM 8514.
#include 
void far setrgbpalette(int colornum, int red, int green, int blue);

Borland C++ Library Reference

setrgbpalette

Remarks

setrgbpalette can be used with the IBM 8514 and VGA drivers.

colornu111 defines the palette entry to be loaded, while red, green, and blue
define the component colors of the palette entry.
For the IBM 8514 display (and the VGA in 256K color mode), colornu111 is
in the range a to 255. For the remaining modes of the VGA, colornu111 is in
the range a to 15. Only the lower byte of red, green, or blue is used, and out
of each byte, only the 6 most significant bits are loaded in the palette.

t:::>

Return value

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
using setrg bpalette.
None.

See also

setpalette

Example

#include
#include
#include
#include






int main(void)
(

/* select driver and mode that supports use of setrgbpalette */
int gdriver = VGA, gmode = VGAHI, errorcode;
struct palettetype pal;
int i, ht, y, xmax;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) ( /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
/* terminate with an error code */
/* grab a copy of the palette */
getpalette(&pal) ;
/* create gray scale */
for (i=O; i




1* function prototype *1
void xat(int x, int y);
1* horizontal text justification settings *1
char *hjust [l ::: { "LEFT_TEXT", "CENTER_TEXT", "RIGHT_TEXT" };
1* vertical text justification settings *1
char *vjust [l ::: { "LEFT_TEXT", "CENTER_TEXT", "RIGHT_TEXT" };
int main (void)
{

1* request autodetection *1
int gdriver ::: DETECT, gmode, errorcode;
int midx, midy, hj, vj;
char msg [80] ;

1* initialize graphics and local variables *1
initgraph(&gdriver, &gmode, "");
1* read result of initialization *1
errorcode ::: graphresult();
if (errorcode !::: grOk) { I * an error occurred *I
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch () ;
exit(l);
1* terminate with an error code *1
midx ::: getmaxx() I 2;
midy ::: getmaxy() I 2;

1* loop through text justifications *1
for (hj:::LEFT_TEXT; hj<:::RIGHT_TEXT; hj++)
for (vj:::LEFT_TEXT; vj<:::RIGHT_TEXT; vj++)
cleardevice();
1* set the text justification *1
settextjustify(hj, vj);
1* create a message string *1
sprintf(msg, "%s %s", hjust[hj], vjust[vj]);
1* create crosshairs on the screen *1

Chapter 2, The run-time library

491

settextjustify

xat (midx, midy);
/* output the message */
outtextxy(midx, midy, msg);
getch() ;
/* clean up */
closegraph ( ) ;
return 0;

void xat(int x, int y)

/* draw an x at (x,y) */

{

line(x-4, y, x+4, y);
line(x, y-4, x, y+4);

settextstyle
Function
Syntax

Sets the current text characteristics for graphics output.
#include 
void far settextstyle




./* the names of the text styles supported */
char *fname[] = { "DEFAULT font", "TRIPLEX font",
"SMALL font",
"SANS SERIF font",
"GOTHIC font",
"SCRIPT font",
"SIMPLEX font", "TRIPLEX SCRIPT font",
"COMPLEX font", "EUROPEAN font",
"BOLD font"};
int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int style, midx, midy;
int size = 1;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */
midx = getmaxx() / 2;
midy = getmaxy() / 2;
settextjustify(CENTER_TEXT, CENTER_TEXT);
/* loop through the available text styles */
for (style=DEFAULT_FONT; style<=BOLD_FONT; style++)
cleardevice ( ) ;
if (style == TRIPLEX_FONT)
size = 4;
/* select the text style */
settextstyle(style, HORIZ_DIR, size);
/* output a message */
outtextxy(midx, midy, fname[style]);
getch() ;
/* clean up */
closegraph () ;

494

Borland C++ Library Reference

settextstyle

return 0;

setusercharsize
Function
Syntax

Remarks

Varies character width and height for stroked fonts.
#include 
void far setusercharsize(int multx, int divx, int multy, int divy);

setusercharsize gives you finer control over the size of text from stroked
fonts used with graphics functions. The values set by setusercharsize are
active only if charsize equals 0, as set by a previous call to settextstyle.

With setusercharsize, you specify factors by which the width and height
are scaled. The default width is scaled by multx : divx, and the default
height is scaled by multy: divy. For example, to make text twice as wide
and 50% taller than the default, set
multx = 2;
multy = 3;

Return value

divx = 1;
divy = 2;

None.

See also

gettextsettings, graphresult, settextstyle

Example

#incl ude
#include
#include
#include






int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */.

Chapter 2, The run-time library

495

setusercharsize

/* select a text style */
settextstyle(TRIPLEX_FONT, HORIZ_DIR, 4);
/* move to the text starting position */
moveto(O, getmaxy() / 2);
/* output some normal text */
outtext("Norm ");
/* make the text 1/3 the normal width */
setusercharsize(l, 3, 1, 1);
outtext("Short ");
/* make the text 3 times normal width */
setusercharsize (3, I, I, 1);
outtext ( "Wide" ) ;
/* clean up */
getch () ;
closegraph ( ) ;
return 0;

setvbuf
Function
Syntax

Remarks

Assigns buffering to a stream.
#include 
int setvbuf(FILE *stream, char *buf, int type, size_t size);

setvbuf causes the buffer buf to be used for II a buffering instead of an
automatically allocated buffer. It is used after the given stream is opened.

If buf is null, a buffer will be allocated using malloc; the buffer will use size
as the amount allocated. The buffer will be automatically freed on close.
The size parameter specifies the buffer size and must be greater than zero.

-..

The parameter size is limited to a maximum of 32,767.

stdin and stdout are unbuffered if they are not redirected; otherwise, they
are fully buffered. Unbuffered means that characters written to a stream are
immediately output to the file or device, while buffered means that the
characters are accumulated and written as a block.
The type parameter is one of the following:

496

Borland C++ Library Reference

setvbuf

_IOFBF The file is fully buffered. When a buffer is empty, the next input
operation will attempt to fill the entire buffer. On output, the
buffer will be completely filled before any data is written to
the file.
_IOLBF The file is line buffered. When a buffer is empty, the next input
operation will still attempt to fill the entire buffer. On output,
however, the buffer will be flushed whenever a newline
character is written to the file.
_IONBF The file is unbuffered. The buf and size parameters are ignored.
Each input operation will read directly from the file, and each
output operation will immediately write the data to the file.
A common cause for error is to allocate the buffer as an automatic (local)
variable and then fail to close the file before returning from the function
where the buffer was declared.
Return value

setvbut returns 0 on success. It returns nonzero if an invalid value is given
for type or size, or if there is not enough space to allocate a buffer.

See also

fflush, topen, setbuf

Example

#inc1ude 
int main(void)
{

FILE *input, *output;
char bufr[512];
input = fopen("file.in", "nb");
output = fopen("file.out", "W");
/* set up input stream for minimal disk access, using our own character buffer
*/

if (setvbuf(input, bufr, _IOFBF, 512) != 0)
printf("failed to set up buffer for input file\n");
else
printf(IIbuffer set up for input file\n");
/* set up output stream for line buffering using space that is obtained
thr,ough an indirect call to malloc */
if (setvbuf(output, NULL, _IOLBF, 132) != 0)
printf(IIfailed to set up buffer for output file\n");
else
printf ("buffer set up for output file\n");
/* perform file I/O here */

/* close files */
fc10se (input) ;
fc10se (output) ;

Chapter 2, The run-time library

497

setvbuf

return 0;

setverify
Function
Syntax

Remarks

Sets the state of the verify flag in DOS.
#include 
void setverify(int value);

setveri!y sets the current state of the verify flag to value .

• A value of 0 = verify flag off .
• A value of 1 = verify flag on.

The verify flag controls output to the disk. When verify is off, writes are
not verified; when verify is on, all disk writes are verified to ensure
proper writing of the data.
Return value

None.

See also

getverify

Example

#incl ude 
#include 
#incl ude 
int main(void)
{

int ver i fy-flag;
printf("Enter 0 to set verify
printf("Enter 1 to set verify
verify_flag = getch() - 0;
setverify(verify_flag) ;
if (getverify())
printf("DOS verify flag is
else
printf("DOS verify flag is
return 0;

498

flag off\n");
flag on\n");

on\n");
off\n");

Borland C++ Library Reference

setviewport

setviewport
Function
Syntax

Remarks

Sets the current viewport for graphics output.
#include 
void far setviewport(int left, int top, int right, intbottom, int clip);

setviewport establishes a new viewport for graphics output.

The viewport's corners are given in absolute screen coordinates by
(left,top) and (right,bottom). The current position (CP) is moved to (0,0) in
the new window.
The parameter clip determines whether drawings are clipped (truncated)
at the current viewport boundaries. If clip is nonzero, all drawings will be
clipped to the current viewport.
Return value

If invalid input is passed to setviewport, graphresult returns -11, and the
current view settings remain unchanged.

See also

clearviewport, getviewsettings, graphresult

Example

#include
#include
#include
#include






#define CLIP_ON 1

/* activates clipping in viewport */

int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{

print f ("Graphics error: %s \n ", grapherrormsg (errorcode) ) ;
print f ( Press any key to halt:");
getch();
II

Chapter 2, The run-time library

499

setviewport

,exit (1)

;

/* terminate with an error code */

setcolor(getmaxcolor()) ;
/* message in default full-screen viewport */
outtextxy(D, 0, "* <-- (0, 0) in default viewport");
/* create a smaller viewport */
setvlewport(50, 50, getmaxx()-50, getmaxy()-50, CLIP_ON);
/* display some text */
outtextxy(O, 0, "* <-- (0, 0) in smaller viewport");
/* clean up */
getch () ;
closegraph ( ) ;
return 0;

setvisualpage
Function
Syntax

Remarks
Return value

Sets the visual graphics page number.
#include 
void far setvisualpage(int page);

setvisualpage makes page the visual graphics page.

None.

See also

graphresult, setactivepage

Example

#include
#include
#include
#include






int main(void)
{

/* select driver and mode that supports multiple pages */
int gdriver = EGA, gmode = EGAHI, errorcode;
int x, y, ht;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, 1111);
/* read result of initialization */

500

Borland C++ Library Reference

setvisuolpage

errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{

printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(l);
/* terminate with an error code */
x = getmaxx() / 2;
y = getmaxy() / 2;
ht = textheight("W");
/* select the off screen page for drawing */
setactivepage(l) ;

/* draw a line on page #1 */
line(O, 0, getmaxx(), getmaxy());
/* output a message on page #1 */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "This is page #1:");
outtextxy (x, y+ht, "Press any key to halt:");
/* select drawing to page #0 */
setactivepage(O) ;
/* output a message on page #0 */
outtextxy(x, y, "This is page #0.");
outtextxy(x, y+ht, "Press any key to view page #1:");
getch() ;
/* select page #1 as the visible page */
setvisualpage(l) ;

/* clean up */
getch();
closegraph ( ) ;
return 0;

•

setwritemode
Function
Syntax

Sets the writing mode for line drawing in graphics mode.
#include 
void far setwritemode(int mode);

Chapter 2, The run-time library

501

setwritemode

Remarks

The following constants are defined:
COPY_PUT
XOR_PUT

=

/* MOV */

=

/* XOR*/

Each constant corresponds to a binary operation between each byte in the
line and the corresponding bytes onscreen. COPY_PUT uses the assembly
language MOV instruction, overwriting with the line whatever is on the
screen. XOR_PUT 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.
..

Return value

setwritemode currently works only with line, Iinerel, Iineto, rectangle,
and drawpoly.

None.

See also

drawpoly, line, Iinerel, Iineto, putimage

Example

#include
#include
#include
#include






int main ()
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int xmax, ymax;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{

printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf (" Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */
xmax
ymax

= getmaxx();
= getmaxy();

/* select XOR drawing mode */
setwritemode(XOR_PUT) ;
/* draw a line */
line(O, 0, xmax, ymax);

502

Borland C++ Library Reference

setwritemode

getch () ;
/* erase the line by drawing over it */
line(O, 0, xmax, ymax);
getch () ;
/* select overwrite drawing mode */
setwritemode(COPY_PUT);

/* draw a line */
line(O, 0, xmax, ymax);

/* clean up * /
getch () ;
closegraph ( ) ;
return 0;

signal
Function
Syntax

Remarks

Specifies signal-handling actions.
#include 
void (*signal(int sig, void (*func) (int sigL int subcode])))(int);

signal determines how receipt of signal number sig will subsequently be

treated. You can install a user-specified handler routine or use one of the
two predefined handlers, SIC_DFL and SIC_ICN, in signal.h.
Function pointer

Meaning

SIC_DFL
SIG_IGN
SIC_ERR

Terminates the program
Ignore this type signal
Indicates an error return from signal

The signal types and their defaults are as follows:

Chapter 2, The run-time library

503

signal

Signal type

Meaning

SIGABRT

Abnormal termination. Default action is equivalent to calling
_exit(3).

SIGFPE

Arithmetic error caused by division by 0, invalid operation, and
the like. Default action is equivalent to calling _exit(1).

SIGILL

Illegal operation. Default action is equivalent to calling _exit(1).

SIGINT

CTRL-C interrupt. Default action is to do an INT 23h.

SIGSEGV

Illegal storage access. Default action is equivalent to calling
_exit(1).

SIGTERM

Request for program termination. Default action is equivalent to
calling _exit(1).

signal.h defines a type called sig_atomic_t, the largest integer type the
processor can load or store atomically in the presence of asynchronous
interrupts (for the 8086 family, this is a 16-bit word; that is, a Borland c++
integer).
When a signal is generated by the raise function or by an external event,
the following happens:
1. If a user-specified handler has been installed for the signal, the action
for that signal type is set to SIG_DFL.
2. The user-specified function is called with the signal type as the
parameter.
User-specified handler functions can terminate by a return or by a call to
abort, _exit, exit, or longjrnp.
Borland c++ implements an extension to ANSI C when the signal type is
SIGFPE, SIGSEGV, or SIGILL. The user-specified handler function is
called with one or two extra parameters. If SIGFPE, SIGSEGV, or SIGILL
has been raised as the result of an explicit call to the raise function, the
user-specified handler is called with one extra parameter, an integer
specifying that the handler is being explicitly invoked. The explicit
activation values for SIGFPE, SIGSEGV and SIGILL are as follows (see
declarations in float.h):

504

SIGSEGV signal

Meaning

SIGFPE
SIGSEGV
SIGILL

FPE_EXPLICITGEN
SEGV_EXPLICITGEN
ILL_EXPLICITGEN

Borland C++ Library Reference

signal

If SIGFPE is raised because of a floating-point exception, the user handler
is called with one extra parameter that specifies the FPE_xxx type of the
signal. If SIGSEGV, SIGILL, or the integer-related variants of SIGFPE
signals (FPE_INTOVFLOW or FPE_INTDIVO) are raised as the result of a
processor exception, the user handler is called with two extra parameters:

. 1. The SIGFPE, SIGSEGV, or SIGILL exception type (see float.h for all
these types). This first parameter is the usual ANSI signal type.
2. An integer pointer into the stack of the interrupt handler that called
the user-specified handler. This pointer points to a list of the processor
registers saved when the exception occurred. The registers are in the
same order as the parameters to an interrupt function; that is, BP, OJ,
SI, OS, ES, OX, CX, BX, AX, IP, CS, FLAGS. To have a register value
changed when the handler returns, change one of the locations in this
list. For example, to have a new SI value on return, do something like
this:
*( (int*)list-pointer + 2)

= new_S1_value;

In this way, the handler can examine and make any adjustments to the
registers that you want. (See Example 2 for a demonstration.)
The following SIGFPE-type signals can occur (or be generated). They
correspond to the exceptions that the 8087 family is capable of detecting,
as well as the "INTEGER DIVIDE BY ZERO" and the "INTERRUPT ON
OVERFLOW" on the main CPU. (The declarations for these are in float.h.)

~

SIGFPE signal

Meaning

FPE_INTOVFLOW
FPE_INTDIVO
FPE_INVALID
FPE_ZERODIVIDE
FPE_OVERFLOW
FPE_UNDERFLOW
FPE_INEXACT
FPE_EXPLICITGEN

INTO executed with OF flag set
Integer divide by zero
Invalid operation
Division by zero
Numeric overflow
Numeric underflow
Precision
User program executed raise(SIGFPE)

The FPE_INTOVFLOW and FPE_INTDIVO signals are generated by
integer operations, and the others are generated by floating-point
operations. Whether the floating-point exceptions are generated depends
on the coprocessor control word, which can be modified with _controI87.
Denormal exceptions are handled by Borland C++ and not passed to a
signal handler.
The following SIGSEGV-type signals can occur:

Chapter 2, The run-time library

505

signal

SEGV_BOUND
SEGV_EXPLICITGEN

Bound constraint exception
raise(SIGSEGV) was executed

The 8088 and 8086 processors don't have a bound instruction. The 186,286,
386, and NEC V series processors do have this instruction. So, on the 8088
and 8086 processors, the SEGV_BOUND type of SIGSEGV signal won't
occur. Borland C++ doesn't generate bound instructions, but they can be
used in inline code and separately compiled assembler routines that are
linked in.
The following SIGILL-type signals can occur:
ILL_EXECUTION
ILL_EXPLICITGEN

Illegal operation attempted.
raise(SIGILL) was executed.

The 8088, 8086, NEC V20, and NEC V30 processors don't have an illegal
operation exception. The 186, 286, 386, NEC V40, and NEC V50 processors
do have this exception type. So, on 8088, 8086, NEC V20, and NEC V30
processors, the ILL_EXECUTION type of SIGILL won't occur.
When the signal type is SIGFPE, SIGSEGV, or SIGILL, a return fro'm a
signal handler is generally not advisable because the state of the 8087 is
corrupt, the results of an integer division are wrong, an operation that
shouldn't have overflowed did, a bound instruction failed, or an illegal
operation was attempted. The only time a return is reasonable is when the
handler alters the registers so that a reasonable return context exists or the
signal type indicates that the signal was generated explicitly (for example,
FPE_EXPLICITGEN, SEGV_EXPLICITGEN, or ILL_EXPLICITGEN).
Generally in this case you would print an error message and terminate the
program using _exit, exit, or abort. If a return is executed under any other
conditions, the program's action will probably be unpredictable upon
resuming.
Return value

See also
Exannple 1

If the call succeeds, signal returns a pointer to the previous handler
routine for the specified signal type. If the call fails,· Signal returns
SIG_ERR, and the external variable errno is set to EINV AL.

abort, _controI87, ctrlbrk, exit, longjmp, raise, setjmp
/* This example installs a signal handler routine to be run when Ctrl-Break is
pressed. */

#include 
#include 
#include 
void catcher(void)
{

printf("\nNow in break routine\n");

506

Borland C++ Library Reference

signal

exi t (1) ;
int main (void) {
signal (SIGINT,catcher) ;
for (;;)
printf("\nIn main() program\n");

Exannple 2

/* This example installs a signal handler routine for SIGFPE, catches an integer

overflow condition, makes an adjustment to AX register, and returns. This
example program MAY cause your computer to crash, and will produce runtime
errors depending on which memory model is used. */
#pragma inline
#include 
#include 
void Catcher(int *reglist)
{

printf ("Caught it! \n") ;
* (reglist + 8) = 3;

/* make return AX

=3

*/

int main(void)
signal (SIGFPE, Catcher) ;
aX,07FFFH
asm
mov
asm
ax
inc
asm
into

/* AX = 32767 */
/* cause overflow */
/* activate handler */

/* The handler set AX to 3 on return. If that hadn't happened, there would
have been another exception when the next 'into' was executed after the
'dec' instruction. */
/* no overflow now */
asm
ax
dec
asm
into
/* doesn't activate */
return 0;

sin, sinl
Function
Syntax

Calculates sine.

Real versions:
#include 
double sin(double x);
long double sinl(long double x);

Chapter 2, The run-time library

Complex version:
#include 
complex sin(complex x);

507

sin, sinl

DOS

•
•
•

sinl
Real sin
Complex sin

Remarks

UNIX

Windows

ANSI C

•
•
•

•

•

C++ only

•

sin computes the sine of the input value. Angles are specified in radians.
sinl is the long double version; it takes a long double argument and

returns a long double result.
Error handling for these functions can be modified through the functions
math err and _matherrl.
Return value

sin and sinl return the sine of the input value.

The complex sine is defined by
sin(z)

= (exp(i * z) -

exp(-i * z» / (20

See also

acos, asin, atan, atan2, complex, cos, tan

Example

#include 
#include 
int main(void)
{

double result, x = 0.5;
result = sin (x) ;
printf("The sin() of %1£ is %1£\n", x, result);
return 0;

sinh, sinhl
Function
Syntax

Calculates hyperbolic sine.

Real versions:

Complex version:

#include 
#include 
complex sinh(complex x);
double sinh(double x);
long double sinhl(long double x);
DOS

sinhl
Real sinh
Complex sinh

508

•
•
•

UNIX

•
•

Wi ndows

ANSI C

•
•
•

•

C++ only

•

Borland C++ Library Reference

sinh, sinhl

Remarks

sinh computes the hyperbolic sine, (eX - e-X)/2.
sinl is the long double version; it takes a long double argument and

returns a long double result.
Error handling for sinh and sinhl can be modified through the functions
math err and _matherrl.
The complex hyperbolic sine is defined by
sinh(z) = (exp(z) - exp(-z»/2
Return value

sinh and sinhl return the hyperbolic sine of x.

When the correct value overflows, these functions return the value
HUGE_VAL (sinh) or _LHUGE_VAL (sinh!) of appropriate sign. Also, the
global variable errno is set to ERANGE.
See cosh.
See also

acos, asin, atan, atan2, complex, cos, cosh, sin, tan,
tanh

Example

#include 
#include 
int main(void)
{

double result, x = 0.5;
result = sinh(x);
printf("The hyperbolic sin() of %If is %If\n", x, result);
return 0;

sleep
Function
Syntax

Remarks

Suspends execution for an interval (seconds).
#include 
void sleep( unsigned seconds);

With a call to sleep, the current program is suspended from execution for
the number of seconds specified by the argument seconds. The interval is
only accurate to the nearest hundredth of a second or the accuracy of the
DOS clock, whichever is less accurate.

Chapter 2, The run-time library

509

sleep

Return value

None.

See also

delay

Example

#include 
#include 
int main (void)
{

int i;
for (i=l; i<5; itt) {
printf("Sleeping for %d seconds\n" , i);
sleep(i) ;
return 0;

sopen
Function
Syntax

Remarks

Opens a shared file.
#include 
#include 
#include 
#include 
int sopen(char *path, int access, int shflagL int mode]);

path and prepares it for shared reading or
writing, as determined by access, shflag, and mode.

sapen opens the file given by

For sapen, access is constructed by ORing flags bitwise from the following
two lists. Only one flag from the first list can be used; the remaining flags
can be used in any logical combination.
List 1: Read/write flags

O_RDONLY
0_WRONLY
o_RDWR

Open for reading only.
Open for writing only.
Open for reading and writing.

List 2: Other access flags

O_NDELAY
O_APPEND

510

Not used; for UNIX compatibility.
If set, the file pointer is set to the end of the file prior to
each write.

Borland C++ Library Reference

sopen

O_CREAT

O_TRUNC

If the file exists, this flag has no effect. If the file does not
exist, the file is created, and the bits of mode are used to
set the file attribute bits as in chmad.
If the file exists, its length is truncated to o. The file
attributes remain unchanged.
Used only with O_CREAT. If the file already exists, an
error is returned.
This flag can be given to explicitly open the file in binary
mode.
This flag can be given to explicitly open the file in text
mode.

These 0_ ... symbolic constants are defined in fcntl.h.
If neither O_BINARY nor a_TEXT is given, the file is opened in the
translation mode set by the global variable Jmode.
If the O_CREAT flag is used in constructing access, you need to supply the
mode argument to sapen from the following symbolic constants defined in
sys \stat.h.
Value of mode

Access permission

S_IWRITE
S_IREAD
S_IREAD I S_IWRITE

Permission to write
Permission to read
Permission to read/write

shflag specifies the type of file-sharing allowed on the file path. Symbolic
constants for shflag are defined in share.h.

Return value

Value of shflag

What it does

SH_COMPAT
SH_DENYRW
SH_DENYWR
SH_DENYRD
SH_DENYNONE
SH_DENYNO

Sets compatibility mode
Denies read/write access
Denies write access
Denies read access
Permits read/write access
Permits read/write access

I

On successful completion, sapen returns a nonnegative integer (the file
handle), and the file pointer (that marks the current position in the file) is
set to the beginning of the file. On error, it returns -1, and the global
variable errno is set to
ENOENT
EMFILE
EACCES
EINVACC

Chapter 2, The run-time library

Path or file function not found
Too many open files
Permission denied
Invalid access code

511

sopen

See also

chmod, close, creat, lock, Iseek, _open, open, unlock, unmask

Example

#include
#include
#include
#include
#include
#include








int main(void)
int handle, status;
handle = sopen("c:\\autoexec.bat", O_ROONLY, SH_OENYNO, S_IREAO);
if (handle < 0) {
printf("sopen failed\n");
exit(l) ;
status = access("c:\\autoexec.bat", 6);
if (status == 0)
printf("read/write access allowed\n");
else
printf("read/write access not allowed\n");
close (handle) ;
return 0;

sound
Function
Syntax

Remarks

Turns PC speaker on at specified frequency.
#include 
void sound(unsigned frequency);

sound turns on the PC's speaker at a given frequency. frequency specifies

the frequency of the sound in hertz (cycles per second). To turn the
speaker off after a call to sound, call the function nosound.
See also

delay, nosound

Example

1* Emits a 440-Hz tone for 1 seconds. *1
#include 

int main(void)
{

512

Borland C++ Library Reference

sound

sound(440) ;
delay(1000) ;
nosound() ;
return 0;

spawn\, spawnle, spawnlp, spawnlpe, spawnv, spawnve,
spawnvp, and spawnvpe
Function
Syntax

Creates and runs child processes.
#include 
#include 
int spawnl(int mode, char *path, char *argO, argl, ... , argn, NULL);
int spawnle(int mode, char *path, char *argO, argl, ... , argll, NULL,
char *envp[]);
int spawnlp(int mode, char *path, char *argO, argl, ... , argn, NULL);
int spawnlpe(int mode, char *patlz, char *argO, argl, ... , argn, NULL, char

*envp[]);
int spawnv(int mode, char *path, char *argv[]);
int spawnve(int mode, char *path, char *argv[], char *envp[]);
int spawnvp(int mode, char *path, char *argv[]);
int spawnvpe(int mode, char *path, char *argv[], char *envp[]);

Remarks

The functions in the spawn ... family create and run (execute) other files,
known as child processes. There must be sufficient memory available for
loading and executing a child process.
The value of mode determines what action the calling function (the parent
process) takes after the spawn ... call. The possible values of mode are
Puts parent process "on hold" until child process
completes execution.

b.!!>

P_NOWAIT

Continues to run parent process while child process runs.

P_OVERLAY

Overlays child process in memory location formerly
occupied by parent. Same as an exec ... call.

P _NOW AIT is currently not available; using it generates an error value.

Chapter 2, The run-time library

513

spawnl, spawnle, spawnlp, spawnlpe, spawnv, spawnve, spawnvp, and spawnvpe

path is the file name of the called child process. The spawn ... function calls
search for path using the standard DOS search algorithm:

No extension or no period: Search for exact file name; if not successful,
DOS adds .COM and searches again. If still not successful, it adds .EXE
and searches again.
1'1 Extension given: Search only for exact file name .
.. Period given: Search only for file name with no extension.
II If path does not contain an explicit directory, spawn ... functions that
have the p suffix will search the current directory, then the directories
set with the DOS PATH environment variable.
III

The suffixes I, v, p, and e added to the spawn ... "family name" specify that
the named function operates with certain capabilities.
p

The function will search for the file in those directories specified by
the PATH environment variable. Without the p suffix, the function
will search only the current working directory.
The argument pointers argO, argl, ... , argn are passed as separate
arguments. Typically, the I suffix is used when you know in
advance the number of arguments to be passed.

v

The argument pointers argv[O), ... , arg[n) are passed as an array of
pointers. Typically, the v suffix is used wh~n a variable number of
arguments is to be passed.

e

The argument envp can be passed to the child process, allowing you
to alter the environment for the child process. Without the e suffix,
child processes inherit the environment of the parent process.

Each function in the spawn ... family must have one of the two argumentspecifying suffixes (either I or v). The path search and environment
inheritance suffixes (p and e) are optional.
For example,
• spawnl takes separate arguments, searches only the current directory

for the child, and passes on the parent's environment to the child.
a spawnvpe takes an array of argument pointers, incorporates PATH in
its search for the child process, and accepts the envp argument for
altering the child's environment.
The spawn ... functions must pass at least one argument to the child
process (argO or argv[O)): This argument is, by convention, a copy of path.
(Using a different value for this Oth argument won't produce an error.) If

514

Borland C++ Library Reference

spawnl, spawnle, spawnlp, spawnlpe, spawnv, spawnve, spawnvp, and spawnvpe

you want to pass an ernpty argument list to the child process, then argO or
must be NULL.

argv[O}

Under DOS 3.x, path is available for the child process; under earlier
versions, the child process cannot use the passed value of the Oth
argument (argO or argv[O}).
When the I suffix is used, argO usually points to path, and argl, .... , argn
point to character strings that form the new list of arguments. A
mandatory null following argn marks the end of the list.
When the e suffix is used, you pass a list of new environment settings
through the argument envp. This environment argument is an array of
character pointers. Each element points to a null-terminated character
string of the form
envvar = value

where envvar is the name of an environment variable, and value is the
string value to which envvar is set. The last element in envp[J is null. When
envp is null, the child inherits the parents' environment settings.
The combined length of argO + argl + '" + argn (or of argv[O) + argv[1} + ...
+ argv[n]), including space characters that separate the arguments, must
be < 128 bytes. Null-terminators are not counted.
When a spawn ... function call is made, any open files remain open in the
child process.
Return value

On a successful execution, the spawn ... functions return the child
process's exit status (0 for a normal termination). If the child specifically.
calls exit with a nonzero argument, its exit status can be set to a nonzero
value.
On error, the spawn ... functions return -1, and the global variable errno is
set to
E2BIG
EINVAL
ENOENT
ENOEXEC
ENOMEM

See also
Example 1

Arg list too long
Invalid argument
Path or file name not found
Exec format error
Not enough core

abort, atexit, _exit, exit, exec ... , _fpreset, search path, system
#include 
#include 
#include 
void spawnl_example(void)

Chapter 2, The run-time library

515

spawnl, spawn Ie, spawnlp, spawnlpe, spawnv, spawnve, spawnvp, and spawnvpe

int result;
clrscr () ;
result = spawnl (P_vJAIT, "bcc.exe", NULL);
if (result == -1) {
perror ( "Error from spawnl") ;
exit(l);

void spawnle_example(void)
{

int result;
clrscr () ;
result = spawnle(P_WAIT, "bcc.exe", NULL, NULL);
if (result == -1) {
perror( "Error from spawnle");
exit(l);

int main(void)
{

spawnl_example() ;
spawnle_example() ;

_splitpath
Function
Syntax

Remarks

Splits a full path name into its components.
#include 
void _splitpath(const char *path, char *drive, char *dir, char *name,
char *ext);

_splitpath takes a file's full path name (path) as a string in the form

X:\DIR\SUBDIR\NAME.EXT

and splits path into its four components. It then stores those components
in the strings pointed to by drive, dir, name, and ext. (All five components
must be passed, but any of them can be a null, which means the corresponding component will be parsed but not stored.)

516

Borland C++ Library Reference

_splitpath

The Inaximum sizes for these strings are given by the constants
_MAX_DRIVE, _MAX_DIR, _MAX_PATH, _MAX_FNAME, and _MAX_EXT (defined
in stdlib.h), and each size includes space for the null-terminator. These
constants are defined in stdlib.h.
Constant

Max

String

MAX]ATH
MAX_DRIVE
MAX_orR
MAX]NAME
_MAX_EXT

(80)
(66)

path
drive; includes colon (:)
dir; includes leading and trailing backslashes (\)

(9)
(5)

ext; includes leading dot (.)

(3)

name

_splitpath assumes that there is enough space to store each non-null

component.
When _splitpath splits path, it treats the punctuation as follows:
I:J

drive includes the colon (C:, A:, and so on).

13

dir includes the leading and trailing backslashes (\BC\include \, \

source \, and so on).
[J name includes the file name.
D ext includes the dot preceding the extension (.C, .EXE, and so on).
_makepath and _splitpath are invertible; if you split a given path with
_splitpath, then merge the resultant components with _makepath, you

end up with path.
Return value

None.

See also

_full path, _makepath

Example

#include
#include
#include
#include






int main(void)
{

char
char
char
char
char

s[_MAX_PATH];
drive [_MAX_DRIVE] ;
dir[_MAX_DIR];
file[_MAX_FNAME];
ext[_MAX_EXT];

getcwd(s,_MAX_PATH) ;
1* get current working directory *1
if (s [s t rl en (s) -1] ! = ' \ \ ' )
strcat(s,"\\");
1* append a trailing \ character *1
_splitpath(s,drive,dir,file,ext); 1* split the string to separate elems *1

Chapter 2, The run-time library

517

_splitpath

strcpy (file, "DATA");
strcpy(ext,".TXT");
_makepath(s,drive,dir,file,ext); /* merge everything into one string */
puts (s);
/* display resulting string * /
return 0;

sprintf
Function
Syntax

Remarks

Writes formatted output to a string.
#include 
int sprintf(char *buffer, const char *formatL argument, " .]);

sprintf accepts a series of arguments, applies to each a format specifier

contained in the format string pointed to by format, and outputs the
formatted data to a string.
See prinff for details
on format specifiers.

Return value

sprintf applies the first format specifier to the first argument, the second to

the second, and so on. There must be the same number of format
specifiers as arguments.
sprintf returns the number of bytes output. sprintf does not include the
terminating null byte in the count. In the event of error, sprintf returns
EOF.

See also

fprintf, printf

Example

#include 
#include 
int main(void)
{

char buffer[80];
sprintf (buffer, "An approximation of pi is %f\n", M_PI);
puts (buffer) ;
return 0;

sqrt, sqrtl
Function

518

Calculates the positive square root.

Borland C++ Library Reference

sqrt, sqrtl

Syntax

Real versions:

Complex version:

#include 
double sqrt(double x);
long double sqrtl(long double x);

#include 
complex sqrt(complex x);

DOS

sqrtl
Realsqrt

Complex sqrt

Remarks

UNIX

•
•
•

Windows

ANSI C

•
•
•

•

•

C++ only

•

sqrt calculates the positive square root of the argument x.
sqrtl is the long double version; it takes a long double argument and

returns a long double result.
Error handling for these functions can be modified through the functions
matherr and _matherrl.
For complex numbers x, sqrt (xl gives the complex root whose arg is arg
(x) /2.

The complex square root is defined by
sqrt(z)
Return value

= sqrt(abs(z» (cos(arg(z) /2) + i sin(arg(z) /2»

On success, sqrt and sqrtl return the value calculated, the square root of x.
If x is real and positive, the result is positive. If x is real and negative, the
global variable errno is set to
EDaM

Domain error

See also

complex, exp, log, pow

Example

#inc1ude 
#include 
int main (void)
double x = 4.0, result;
result = sqrt(x);
printf("The square root of %If is %If\n", x, result);
return 0;

srand
Function

Initializes random number generator.

Chapter 2, The run-time library

519

srand

Syntax

Remarks

Return value

#include 
void srand (unsigned seed);

The random number generator is reinitialized by calling srand with an
argument value of 1. It can be set to a new starting point by calling srand
with a given seed number.
None.

See also

rand, random, randomize

Example

#include 
#include 
#include 
int main(void)
{

int i;
time_t t;
srand( (unsigned) time(&t));
printf("Ten random numbers from 0 to 99\n\n");
for(i=O; idO; itt)
printf("%d\n", rand() % 100);
return 0;

sscanf
Function
Syntax

Scans and formats input from a string.
#include 
int sscanf(const char *buffer, const char *formatL address, ... J);
1r-__- r____+-____-r_A_N_:I_~

Remarks
See scanffor details
on format specifiers.

520

sscanf scans a series of input fields, one character at a time, reading from

a string. Then each field is formatted according to a format specifier
passed to sscanf in the format string pointed to by format. Finally, sscanf
stores the formatted input at an address passed to it as an argument
following format. There must be the same number of format specifiers and
addresses as there are input fields.

Borland C++ Library Reference

sscanf

sscanf might stop scanning a particular field before it reaches the normal
end-of-field (whitespace) character, or it might terminate entirely, for a
number of reasons. See scanf for a discussion of possible causes.
Return value

sscanf returns the number of input fields successfully scanned, converted,

and stored; the return value does not include scanned fields that were not
stored. If no fields were stored, the return value is O.
If sscanf attempts to read at end-of-string, the return value is EOF.
See also

fscanf, scanf

Example

#include 
#include 
#include 
char *names[4] = {"Peter", "I1ike", "Shea", "Jerry"};
#define NUMITEMS
int main(void)
{

int
loop, age;
char temp[4] [80], name[20];
long salary;
/* clear the screen */
clrscr () ;
/* create name, age and salary data */
for (loop=O; loop < NUMITEMS; ++loop)
sprintf(temp[loop], "%s %d %ld", names[loop],
random(10) + 20,
random(5000) + 27500L
);

/* print title bar */
printf("%4s I %-20s I %5s I %15s\n",
"#", "Name", ")\.ge", "Salary");
printf("
-----------------------"--------------------------\n") ;

II

/* input a name, age and salary data */
for (loop=O; loop < NUlvlITEMS; ttloop) {
sscanf(temp[loop]'''%s %d %ld" , &name, &age, &salary);
printf ("%4d I %-20s I %5d I %15ld\n",
loop + 1, riame, age, salary);
return 0;

Chapter 2, The run-time library

521

_status87

_stotus87
Function
Syntax

Remarks

Gets floating-point status.
#include 
unsigned int _status87(void);

_status87 gets the floating-point status word, which is a combination of

the 80x87 status word and other conditions detected by the 80x87
exception handler.
Return value
Example

The bits in the return value give the floating-point status. See float.h for a
complete definition of the bits returned by _status87.
#inc1 ude 
#include 
int main(void)
{

float Xi
double y = 1.Se-lOOi
printf("Status 87 before error: %x\n", _status87()) i
X = Yi
/* force an error to occur */

Y = Xi
printf("Status 87 after error: %x\n", _status87())
return ai

i

stime
Function
Syntax

Sets system date and time.
#include 
int stime(time_t *tp);
DOS

Remarks
Return value
See also

522

stime sets the system time and date. tp points to the value of the time as
measured in seconds from 00:00:00 GMT, January 1, 1970.
stime returns a value of O.
asctime, ftime, gettime, gmtime, localtime, time, tzset

Borland C++ Library Reference

stime

Example

#include 
#include 
int main(void)
time_t t;
t = time (NULL) ;
printf("Current date is %s", ctiem(&t));
t -= 24L*60L*60L; /* Back up to same time previous day. */
stime(&t) ;
printf("\nNew date is %s", ctime(&t));
return 0;

stpcpy
Function
Syntax

Remarks
Return value

Copies one string into another.
#include 
char *stpcpyCchar *dest, canst char *src);

stpcpy copies the string src to dest, stopping after the terminating null
character of src has been reached.
stpcpy returns dest + strlenCsrc).

See also

strcpy

Example

#include 
#include 
int main(void)
char string [10 1 ;
char *strl = "abcdefghi";
stpcpy(string, strl);
printf ("%s\n", string);
return 0;

Chapter 2, The run-time library

523

street, _'street

streat, _fstreot
Function
Syntax

Appends one string to another.
#include 
Near version: char *strcat(char *dest, canst char *sre);
Far version: char far * far _fstrcat(char far *dest, canst char far *sre)
DOS

Near version

•

Return value
Example

Windows

ANSI C

•

•

•

•

Far version

Remarks

UNIX

C++ only

•

strcat appends a copy of sre to the end of dest. The length of the resulting
string is strlen(dest) + strlen(sre).
strcat returns a pointer to the concatenated strings.
#include 
#include 
int main (void)
{

char destination[25];
char *blank = " ", *c = "et+", *turbo
strcpy(destination, turbo);
strcat(destination, blank);
strcat(destination, c);
printf("%s\n", destination);
return 0;

=

"Turbo";

strehr, _fstrehr
Function
Syntax

Scans a string for the first occurrence of a given character.
#include 
Near version: char *strchr(const char *s, int e);
Far version: char far * far _fstrchr(const char far *s, int e)
DOS

Near version
Far version

524

•
•

UNIX

•

Windows

ANSI C

•

•

C++ only

•

Borland C++ Library Reference

strchr, _fstrchr

Remarks

strchr scans a string in the forward direction, looking for a specific
character. strchr finds the first occurrence of the character c in the string s.
The null-terminator is considered to be part of the string, so that, for
example,
strchr(strs,O)

returns a pointer to the terminating null character of the string strs.
Return value

strchr returns a pointer to the first occurrence of the character c in s; if c
does not occur in s, strchr returns null.

See also

strcspn,strrchr

Example

#include 
#include 
int main(void)
{

char string[15];
char *ptr, c = 'r';
strcpy (string, "This is a string");
ptr = strchr(string, c);
if (ptr)
printf("The character %c is at position: %d\n", c, ptr-string);
else
printf("The character was not found\n");
return 0;

strcmp
Function

Syntax

Compares one string to another.
#include 
int strcmp(const char *sl, const char *s2);
UNIX

Remarks

Return value

Wi ndows

strcmp performs an unsigned comparison of sl to s2, starting with the
first character in each string and continuing with subsequent characters
until the corresponding characters differ or until the end of the strings is
reached.
.
strcmp returns

Chapter 2, The run-time library

a value that is

525

strcmp

< 0 if s1 is less than s2
== 0 if s1 is the same as s2
> 0 if s1 is greater than s2
See also

strcmpi, strcoll, stricmp, strncmp, strncmpi, strnicmp

Example

#include 
#include 
int main (void)
{

char *bufl = "aaa", *buf2 = "bbb", *buf3
"ccc";
int ptr;
ptr = strcmp(buf2, bufl);
if (ptr > 0)
printf("buffer 2 is greater than buffer l\n");
else
printf("buffer 2 is less than buffer l\n");
ptr = strcmp(buf2, buf3);
if (ptr > 0)
printf("buffer 2 is greater than buffer 3\n");
else
printf("buffer 2 is less than buffer 3\n");
return 0;

strcmpi
Function
Syntax

Remarks

Compares one string to another, without case sensitivity.
#include 
int strcmpi(const char *s1, const char *s2);

strcmpi performs an unsigried comparison of s1 to s2, without case
sensitivity (same as stricmp-implemented as a macro).

It returns a value « 0, 0, or > 0) based on the result of comparing s1 (or

part of it) to s2 (or part of it).
The routine strcmpi is the same, respectively, as stricmp. strcmpi is
implemented through a macro in string.h and translates calls from
strcmpi to stricmp. Therefore, in order to use strcmpi, you must include
the header file string.h for the macro to be available~ This macro is
provided for compatibility with other C compilers.

526

Borland C++ Library Reference

strcmpi

Return value

strcmpi returns an int value that is

< a if sl is less than s2
== a if sl is the same as s2
> a if sl is greater than s2
See also

strcmp, strcoll, stricmp, strncmp, strncmpi, strnicmp

Example

#inc1ude 
#include 
int main (void)
{

char *bufl = "BBB",
int ptr;
ptr = strcmpi(buf2,
if (ptr > 0)
printf ("buffer 2
if (ptr < 0)
printf ("buffer 2
if (ptr == 0)
printf("buffer 2
return 0;

*buf2

= "bbb";

bufl);
is greater than buffer 1 \n") ;
is less than buffer 1 \n") ;
equals buffer l\n");

strcoll
Function
Syntax

Remarks
Return value

Compares two strings.
#include 
int strcoll(char *sl, char *s2);

strcoll compares the string pointed to by 81 to the string pointed to by s2,
according to the collating sequence set by setlocale.
strcoll returns a value that is

< a if sl is less than s2

== aif sl is the same as s2
> a if sl is greater than 82
See also

strcmp, strcmpi, stricmp, strncmp, strncmpi, strnicmp, strxfrm

Example

#include 

Chapter 2, The run-time library

527

strcoll

#include 
int main (void)
{

char *two = "International";
char tone = "Borland";
int check;
check = strcoll(one, two);
if (check == 0)
printf("The strings are equal\n");
if (check < 0)
printf("%s comes before %s\n", one, two);
if (check> 0)
printf("%s comes before %s\n", two, one);
return 0;

strcpy
Function
Syntax

Remarks
Return value

Copies one string into another.
#include 
char *strcpy(char *dest, canst char *src);

Copies string src to dest, stopping after the terminating null character has
been moved.
strcpy returns dest.

See also

stpcpy

Example

#include 
#include 
int main (void)
{

char string[10];
char *strl = "abcdefghi";
strcpy(string, strl);
printf("%s\n", string);
return 0;

528

Borland C++ Library Reference

strcspn, _fstrcspn

strcspn _fstrcspn
I

Function
Syntax

Scans a string for the initial segment not containing any subset of a given
set of characters.
#include 
Near version: size_t strcspn(const char *sl, canst char *s2);
Far version: size_t far far _fstrcspn(const char far *sl, canst char far *s2)
DOS

Near version

•
•

Far version

Return value

UNIX

Windows

ANSI C

•
•

•

I

C++ only

strcspn returns the length of the initial segment of string sl that consists
entirely of characters not from string s2.

See also

strchr, strrchr

Example

#include 
#include 
#include 
int main(void)
{

char *string1 = "1234567890", *string2
"7470C8";
int length;
length = strcspn(string1, string2);
printf("Character where strings intersect is at position %d\n", length);
return 0;

I

_strdate
Function
Syntax

Remarks

Converts current date to string.
#include 
char *_strdate(char *buj);

_strdate converts the current date to a string, storing the string in the
buffer buf. The buffer must be at least 9 characters long.

Chapter 2, The run-time library

529

_strdate

The string has the following form:
MM!DD!YY

where MM, DO, and YY are all two-digit numbers representing the
month, day, and year. The string is terminated by a null character.
Return value

_strdate returns buf, the address of the date string.

See also

asctime, ctime, localtime, strftime, _strtime, time

Example

#include 
#include 
void main (void).
{

char datebuf[9l, timebuf[9li
_strdate(datebuf) i
_strtime(timebuf)i
printf("Date: %s Time: %s\n",datebuf,timebuf)

i

strdup _fstrdup
I

Function
Syntax

Copies a string into a newly created location.
#include 
Near version: char *strdup(const char *s);
Far version: char far * far _fstrdup(const char far *s)
DOS

UNIX

•
•

•

Near version
For version

Remarks

Return value

Windows

ANSI C

C++ only

•

•

strdup makes a duplicate of string s, obtaining space with a call to malloc.
The allocated space is (strlen(s) + 1) bytes long. The user is responsible for
freeing the space allocated by strdup ~hen it is no longer needed.
strdup returns a pointer to the storage location containing the duplicated
string, or returns null if space could not be allocated.

See also

free

Example

#include 
#include 
#include 
int main (void)
{

char *dup_str, *string

530

=

"abcde"i

Borland C++ Library Reference

strdup, _fstrdup

dup_str = strdup(string);
printf ("%s\n", dup_str);
free(dup_str);
return 0;

_strerror
Function
Syntax

Remarks

Builds a customized error message.
#include 
char *_strerror(const char *s);

_strerror allows you to generate customized error messages; it returns a

pointer to a null-terminated string containing an error message.
El
[J

If s is null, the return value points to the most recent error message.
If s is not null, the return value contains s (your customized error
message), a colon, a space, the most-recently generated system error
message, and a new line. s should be 94 characters or less.

_strerror is the same as strerror in version 1.0 of Turbo C.
Return value

_strerror returns a pointer to a constructed error string. The error message

string is constructed in a static buffer that is overwritten with each call to
_strerror.
See also

perror,strerror

Example

#include 

•

int main(void)
{

FILE *fp;
/* open a file for writing */

fp

=

fopen("TEST.$$$", "W");

/* force an error condition by attempting to read */

if

(!

fp) fgetc (fp) ;

if (ferror(fp))
/* display a custom error message */

printf("%s", _strerror("Custom"));
fclose (fp) ;

Chapter 2, The run-time library

531

_strerror

return 0;

strerror
Function
Syntax

Remarks
Return value

Returns a pointer to an error message string.
#include 
char *strerror(int errnum);

strerror takes an int parameter errnwn, an error number, and returns a
pointer to an error message string associated with errnum.
strerror returns a pointer to a constructed error string. The error message
string is constructed in a static buffer that is overwritten with each call to
strerror.

See also

perror, _strerror

Example

#include 
#include 
int main(void)
{

char *buffer;
buffer = strerror(errno);
printf("Error: %s\n", buffer);
return 0;

strftime
Function

Formats time for output.

Syntax

#include 
size_t strftime(char *s, size_t maxsize, const char *fmt, const struct tm *t);

Remarks

strftime formats the time in the argument t into the array pointed to by

the argument s according to the ftnt specifications. The format string

532

Borland C++ Library Reference

strftime

consists of zero or more directives and ordinary characters. Like printf, a
directive consists of the % character followed by a character that
determines the substitution that is to take place. All ordinary characters
are copied unchanged. No more than maxsize characters are placed in s.
Return value

strftime returns the number of characters placed into s. If the number of
characters required is greater than maxsize, strftime returns o.
Format specifier

%%
%a

%A
%b

%B
%c

%d

%H
%I
%j

%m

%M
%p
%S

%U
%w

%W
%x

%X

%y
%Y

%Z

Substitutes

Character %
Abbreviated weekday name
Full weekday name .
Abbreviated month name
Full month name
Date and time
Two-digit day of the month (01 to 31)
Two-digit hour (00 to 23)
Two-digit hour (01 to 12)
Three-digit day of the year (001 to 366)
Two-digit month as a decimal number (1 - 12)
Two-digit minute (00 to 59)
AM or PM
Two-digit second (00 to 59)
Two-digit week number where Sunday is the first day of
the week (00 to 53)
Weekday where 0 is Sunday (0 to 6)
Two-digit week number where Monday is the first day of
the week (00 to 53)
Date
Time
Two-digit year without century (00 to 99)
Year with century
Time zone name, or no characters if no time zone

See also

localtime, mktime, time

Example

#include 
#include 
#include 
int main(void)
{

struct tm *time_now;
time_t sees_now;
char str[80];
tzset();
time (&secs_now) ;
time_now = localtime(&secs_now);
strftime(str, 80, "It is %M minutes after %1 o'clock (%Z)
time_now) ;

Chapter 2, The run-time library

%A, %8 %d 19%y",

533

strftime

printf("%s\n",str);
return 0;

stricmp _fstricmp
I

Function
Syntax

Remarks

Compares one string to another, without case sensitivity.
#include 
Near version: int stricmp(const char *s1, const char *s2);
Far version: int far _fstricmp(const char far *s1, const char far *s2)

stricmp performs an unsigned comparison of s1 to s2, starting with the
first character in each string and continuing with subsequent characters
until the corresponding characters differ or until the end of the strings is
reached. The comparison is not case sensitive.

It returns a value « 0, 0, or > 0) based on the result of comparing s1 (or
part of it) to s2 (or part of it).

The routines stricmp and strcmpi are the same; strcmpi is implemented
through a macro in string.h that translates calls from strcmpi to stricmp.
Therefore, in order to use strcmpi, you must include the header file
string.h for the macro to be available.
Return value

stricmp returns an int value that is

°
°

< if s1 is less than s2
if s1 is the same as s2
> if s1 is greater than s2

°

==

See also

strcmp, strcmpi, strcoll, strncmp, strncmpi, strnicmp

Example

#inc1ude 
#include 
int main(void)
{

char *bufl = "BBB", *buf2 = "bbb";
int ptr;
ptr = strcmpi(buf2, bufl);
if (ptr > 0)
printf ("buffer 2 is greater than buffer 1\n");
if (ptr < 0)

534

Borland C++ Library Reference

stricmp, _fstricmp

printf("buffer 2 is less than buffer I\n");
if (ptr == 0)
printf("buffer 2 equals buffer I\n");
return 0;

strlen _fstrlen
I

Function
Syntax

Calculates the length of a string.
#include 
Near version: size_t strlen(const char *5);
Far version: size_t _fstrlen(const char far *5)
DOS

Near version

•

Return value

Windows

ANSIC

•

•

•

•

Far version

Remarks

UNIX

C++ only

•

strlen calculates the length of s.
strlen returns the number of characters in 5, not counting the null-

terminating character.
Example

#include 
#include 
int main (void)
{

char *string = "Borland International";
printf("%d\n", strlen(string));
return 0;

strlwr

I

_

•

fstrlwr
Function
Syntax

Converts uppercase letters in a string to lowercase.
#include 
Near version: char *strlwr(char *5);
Far version: char far * far _fstrlwr(char char far *s)

Chapter 2, The run-time library

535

strlwr, _fstrlwr

Remarks

strlwr converts uppercase letters

CA to Z) in string s to lowercase Ca to z).

No other characters are changed.
Return value

strlwr returns a pointer to the string s.

See also

strupr

Example

#include 
#include 
int rnain(void)
{

char *string = "Borland International";
printf("string prior to strlwr: %s\n", string);
strlwr (string) ;
printf("string after strlwr:
%s\n", string);
return 0;

strncot _fstrncot
I

Function
Syntax

Appends a portion of one string to another.
#include 
Near version: char *strncatCchar *dest, const char *src, size_t maxlen);
Far version: char far * far _fstrncatCchar far *dest, const char far *src,
size_t maxlen)
DOS

Near version

•
•

For version

Remarks

UNIX

Windows

ANSI C

•
•

•

•

C++ only

strncat copies at most maxlen characters of src to the end of dest and then

appends a null character. The maximum length of the resulting string is
strlenCdest) + maxlen.
Return value
Example

strncat returns dest.
#include 
#include 
int rnain(void)
{

char destination[25l;
char *source = " States";
strcpy (destination, "United");
strncat(destination, source, 7);

536

Borland C++ Library Reference

strncot, _fstrncot

printf("%s\n", destination);
return 0;

strncmp, _fstrncmp
Function
Syntax

Compares a portion of one string to a portion of another.
#include 
Near version: int strncmp(const char *sl, const char *s2, size_t maxlen);
Far version: int far _fstrncmp(const char far *sl, const char far *82,
size_t maxlen)
DOS

Near version

•

Far version

•

Remarks

UNIX

Wi ndows

ANSI C

•
•

•

•

C++ only

strnemp makes the same unsigned comparison as stremp, but looks at no
more than 111axlen characters. It starts with the first character in each string

and continues with subsequent characters until the corresponding characters differ or until it has examined 111axlen characters.
Return value

strnemp returns an int value based on the result of comparing sl (or part
of it) to 82 (or part of it).

< 0 if sl is less than s2
0 if sl is the same as s2
> 0 if sl is greater than s2

==

See also

stremp, streoll, striemp, strnempi, strniemp

Example

#include 
#include 
int main(void)
{

char *bufl = "aaabbb", *buf2
"bbbccc", *buf3
"ccc";
int ptr;
ptr = strncmp(buf2,bufl,3);
if (ptr > 0)
printf("buffer 2 is greater than buffer l\n");
else
printf("buffer 2 is less than buffer l\n");
ptr = strncmp(buf2,buf3,3);
if (ptr > 0)
printf("buffer 2 is greater than buffer 3\n");
else

Chapter 2, The run-time library

537

strncmp, _fstrncmp

printf("buffer 2 is less than buffer 3\n");
return(O);

strncmpi
Function
Syntax

Remarks

Compares a portion of one string to a portion of another, without case
sensitivity.
#include 
int strncmpi(const char *51, const char *52, size_t n);

strncmpi performs a signed comparison of 51 to 52, for a maximum length

of n bytes, starting with the first character in each string and continuing
with subsequent characters until the corresponding characters differ or
until n characters have been examined. The comparison is not case sensitive. (strncmpi is the same as strnicmp-implemented as a macro). It
returns a value « 0, 0, or > 0) based on the result of comparing 51 (or part
of it) to 52 (or part of it).
The routines strnicmp and strncmpi are the same; strncmpi is
implemented through a macro in string.h that translates calls from
strncmpi to strnicmp. Therefore, in order to use strncmpi, you must
include the header file string.h for the macro to be available. This macro is
provided for compatibility with other C compilers.
Return value

strncmpi returns an int value that is

< 0 if 51 is less than 52
0 if 51 is the same as 52
> 0 if s1 is grea ter than 52

==

Example

#include 
#include 
int main(void)
{

char *bufl = "BBBccc", *buf2
"bbbccc";
int ptr;
ptr = strncmpi(buf2,bufl,3);
if (ptr > 0)
printf("buffer 2 is greater than buffer I\n");
if (ptr < 0)

538

Borland C++ Library Reference

strncmpi

printf("buffer 2 is less than buffer l\n");
if (ptr == 0)
printf("buffer 2 equals buffer l\n");
return 0;

strncpy, _fstrncpy .
Function
Syntax

Copies a given number of bytes from one string into another, truncating
or padding as necessary.
#include 
Near version: char *strncpy(char *dest, const char *src, size_t maxlen);
Far version: char far * far _fstrncpy(char far *dest, const char far *src,
size_t maxlen)
DOS

Near version

•

Far version

•

Remarks

Return value
Example

UNIX

Windows

ANSI C

•

•

•

C++ only

•

strncpy copies up to maxlen characters from src into dest, truncating or
null-padding dest. The target string, dest, might not be null-terminated if
the length of src is maxlen or more.
strncpy returns

dest.

#include 
#include 
int main(void)
{

char string[lO];
char *strl = "abcdefghi";
strncpy(string, strl, 3);
string[3] = '\0';
printf ("%s\n", string);
return 0;

•

strnicmp, _fstrnicmp
Function
Syntax

Compares a portion of one string to a portion of another, without case
sensitivity.
#include 

Chapter 2, The run-time library

539

strnicmp, _fstrnicmp

Near version: int strnicmp(const char *sl, const char *s2, size_t maxlen);
Far version: int far _fstrnicmp(const char far *sl, canst char far *s2,
size_t maxlen)

Remarks

strnicmp performs a signed comparison of sl to s2, for a maximum length
of maxlen bytes, starting with the first character in each string and
continuing with subsequent characters until the corresponding characters
differ or until the end of the strings is reached. The comparison is not case
sensitive.

It returns a value « 0, 0, or > 0) based on the result of comparing sl (or

part of it) to s2 (or part of it).
Return value

strnicmp returns an int value that is

< 0 if sl is less than s2

== 0 if sl is the same as s2
> 0 if sl is greater than s2
Example

#include 
#include 
int main(void)
{

char *bufl = I BBBccc ", *buf2 = "bbbccc ";
int ptr;
ptr = strnicmp(buf2, bufl, 3);
if (ptr > 0)
printf("buffer 2 is greater than buffer l\n");
if (ptr < 0)
printf(IIbuffer 2 is less than buffer I\n");
if (ptr

==

0)

llrintf ("buffer 2 equals buffer 1\n");
return 0;

strnset _fstrnset
I

Function
Syntax

540

Sets a specified number of characters in a string to a given character.
#include 
Near version: char *strnset(char *s, int ch, size_t n);
Far version: char far * far _fstrnset(char far *s, int ch, size_t n)

Borland C++ Library Reference

strnset, _fstrnset

Remarks

strnset copies the character ch into the first 11 bytes of the string s . If 11 >
strlen(s), then strlen(s) replaces n. It stops when 11 characters have been

set, or when a null character is found.
Return value

strnset returns s.

Example

#include 
#include 
int main (void)
{

char *string = "abcdefghijklrnnopqrstuvwxyz";
char letter; 'x';
printf("string before strnset: %s\n", string);
strnset(string, letter, 13);
printf("string after strnset: %s\n", string);
return 0;

strpbrk, _fstrpbrk
Function

Scans a string for the first occurrence of any character from a given set.

Syntax

#include 
Near version: char *strpbrk(const char *sl, canst char *s2);
Far version: char far * far _fstrpbrk(const char far *sl, canst char far *s2)

Near version
For version

Remarks

DOS

UNIX

•
•

•

Windows

ANSI C

•
•

•

C++ only

strpbrk scans a string, sl, for the first occurrence of any character

appearing in s2.
Return value
Example

strpbrk returns a pointer to the first occurrence of any of the characters in
s2. If none of the s2 characters occurs in sl, it returns null.
#include 
#include 
int main (void)
char *string1

Chapter 2, The run-time library

"abcdefghijklrnnopqrstuvwxyz";

541

strpbrk, _fstrpbrk

char *string2 = "onm";
char *ptr;
ptr = strpbrk(stringl, string2);
if (ptr)
printf("strpbrk found first character: %C\ri", *ptr);
else
printf("strpbrk didn't find character in set\n");
return 0;

strrchr, _fstrrchr
Function
Syntax

Scans a string for the last occurrence of a given character.
#include 
Near version: char *strrchr(const char *s, int c);
Far version: char far * far _fstrrchr(const char far *s, int c)
DOS

Near version

•
•

Far version

Remarks

Return value

UNIX

Windows

ANSI C

•

•

•

C++ only

•

strrchr scans a string in the reverse direction, looking for a specific
character. strrchr finds the last occurrence of the character c in the string s.
The null-terminator is considered to be part of the string.
strrchr returns a pointer to the last occurrence of the character c. If c does
not occur in s, strrchr returns null.

See also

strcspn, strchr

Example

#include 
#include 
int main (void)
{

char string[151, *ptr, c = 'r';
strcpy(string, "This is a string");
ptr = strrchr(string, c);
if (ptr)
printf("The character %c is at position: %d\n", c, ptr-string);
else
printf("The character was not found\n");
return 0;

542

Borland C++ Library Reference

strrev, _fstrrev

strrev _fstrrev
I

Function
Syntax

Remarks

Return value
Example

Reverses a string.
#include 
Near version: char *strrev(char *s);
Far version: char far * far _fstrrev(char far *s)

strrev changes all characters in a string to reverse order, except the

terminating null character. (For example, it would change string\O to
gnirts\O.)
strrev returns a pointer to the reversed string.
#include 
#include 
int main(void)
{

char *forward = "string";
printf("Before strrev(): %s\n", forward);
strrev (forward) ;
printf("After strrev(): %s\n", forward);
return 0;

strset _fstrset
I

Function
Syntax

#include 
Near version: char *strset(char *s, int ch);
Far version: char far * far _fstrset(char far *s, int ch)
DOS

UNIX

Windows

I

•

I

•
Remarks

•

Sets all characters in a string to a given character.

ANSI C

I C++ only

\I

I

I

strset sets all characters in the string s to the character ch. It quits when

the terminating null character is found.
Return value

strset returns s.

Chapter 2, The run-time library

543

strset, _fstrset

See also

setmem

Example

#include 
#include 
int main(void)
{

char string[10] = "123456789";
char symbol = 'c';
printf("Before strset(): %s\n", string);
strset(string, symbol);
printf("After strset(): %s\n", string);
return 0;

strspn, _fstrspn
Function

Scans a string for the first segment that is a subset of a given set of
characters.

Syntax

#include 
Near version: size_t strspn(const char *sl, canst char *s2);
Far version: size_t far _fstrspn(const char far *sl, canst char far *s2)
DOS

Near version

•

Windows

ANSI C

•

•

•

•

For version

Remarks

UNIX

C++ only

•

strspn finds the initial segment of string sl that consists entirely of

characters from string s2.
Return value
Example

strspn returns the length of the initial segment of 81 that consists entirely
of characters from 82.
#include 
#include 
#include 
int main (void)
{

char *string1 = "1234567890", *string2
"123DC8";
int length;
length = strspn(string1, string2);
printf("Character where strings differ is at position %d\n", length);
return 0;

544

Borland C++ Library Reference

strstr, _fstrstr

strstr, _fstrstr
Function
Syntax

Scans a string for the occurrence of a given substring.
#include 
Near version: char *strstr(const char *sl, canst char *s2);
Far version: char far * far --.:..fstrstr(const char far *sl, canst char far *s2)
DOS

Near version

UNIX

II

Wi ndows

II

II

ANSI C

II

,C++ only

II

II

Far version

Remarks
Return value
Example

strstr scans sl for the first occurrence of the substring s2.
strstr returns a pointer to the element in sl, where s2 begins (points to s2
in sl). If s2 does not occur in sl, strstr returns null.
#include 
#include 
int main (void)
{

char *strl = "Borland International", *str2
ptr = strstr(strl, str2);
printf("The substring is: %s\n", ptr);
return 0;

"nation", *ptr;

_strtime
Function
Syntax

Converts current time to string.
#include 
char *_strtime(char *buj);
C++ only

Remarks

_strtime converts the current time to a string, storing the string in the
buffer buf. The buffer must be at least 9 characters long.

The string has the following
form:
HH:MM:SS

Chapter 2, The run-time library

545

_strtime

where HH, MM, and 55 are all two-digit numbers representing the hour,
minute, and second, respectively. The string is terminated by a null
character.
Return value

_strtime returns buf, the address of the, time string.

See also

asctime, ctime, localtime, strftime, _strdate, time

Example

#incl ude 
#include 
void main(void)
{

char datebuf[9l

I

timebuf[9l;

_strdate(datebuf);
_strtime(timebuf);
printf("Date: %s Time: %s\n",datebuf,timebuf);

strtod _strtold
I

Function
Syntax

strlod
_strlo/d

Remarks

Convert a string to a double or long double value.
#include 
double strtod(const char *s, char **endptr);
long double _strtold(const char *s, char **endptr);
DOS

UNIX

•
•

•

Windows

ANSI C

•

•

C++ only

•

strtod converts a character string, s, to a double value. s is a sequence of
characters that can be interpreted as a double value; the characters must
match this generic format:
[wsl [snl [dddj [.j [dddj [fmt [snjdddj

where
[ws]
[sn]
[ddd]

= optional whitespace
= optional sign (+ or-)

[fmt]

= optional e or E
= optional decimal point

[.]

=

optional digits

strtod also recognizes +INF and -INF for plus and minus infinity, and

+NAN and -NAN for Not-a-Number.

546

Borland C++ Library Reference

strtod, _strtold

For example, here are some character strings that strtod can convert to
double:

+ 1231.1981 e-1
502.85E2
+ 2010.952
strtod stops reading the string at the first character that cannot be
interpreted as an appropriate part of a double value.

If endptr is not null, strtod sets *endptr to point to the character that
stopped the scan (*endptr = &stopper). endptr is useful for error detection.
_strtold is the long double version; it converts a string to a long double

value.
Return value

These functions return the value of s as a double (strtod) or along double
Cstrtold). In case of overflow, they return plus or minus HUGE_VAL
(strtod) or _LHUGE_VAL Cstrtold).

See also

atof

Example

#include 
#include 
int main(void)
{

char input[80] , *endptr;
double value;
. printf ("Enter a floating point number:");
gets (input) ;
value = strtod(input, &endptr);
printf("The string is %s the number is %If\n'', input, value);
return 0;

strtok, _fstrtok
Function
Syntax

Searches one string for tokens, which are separated by delimiters defined
in a second string.
#include 
Near version: char *strtok(char *s1, const char *s2);
Far version: char far * far _fstrtok(char far *s1, const char far *s2)-

Chapter 2, The run-time library

547

strtok, _fstrtok

Near version
For version

Remarks

DOS

UNIX

•
•

•

Windows

ANSI C

•

•

C++ only

•

strtok considers the string 51 to consist of a sequence of zero or more text

tokens, separated by spans of one or more characters from the separator
string 52.
The first call to strtok returns a pointer to the first character of the first
token in 51 and writes a null character into 51 immediately following the
returned token. Subsequent calls with null for the first argument will
work through the string 51 in this way, until no tokens remain.
The separator string, 52, can be different from call to call.
Return value

strtok returns a pointer to the token found in 51. A null pointer is returned

when there are no more tokens.
Example

#include 
#include 
int main(void)
{

char input[16)
char *p;

= "abc,d";

/* strtok places a NULL terminator
in front of the token, if found */
p = strtok(input, ",");
if (p)
printf("%s\n", p);
/* a second call to strtok using a NULL as the first parameter returns a
pointer to the character following the token */
p = strtok(NULL, ",");
if (p)
printf("%s\n", p);
return 0;

strtol
Function
Syntax

548

Converts a string to a long value.
#include 
long strtol(const char *5, char **endptr, int radix);

Borland C++ Library Reference

strtol

Remarks

strtol converts a character string,s, to a long integer value. 5 is a sequence
of characters that can be interpreted as a long value; the characters must

match this generic format:
[\liS]

[sn]

[0]

[x]

[ddd]

where
[ws]

= optional whitespace

[sn] = optional sign (+ or-)
[0]

= optional zero (0)

[x] = optional x or X
[ddd] = optional digits

strtol stops reading the string at the first character it doesn't recognize.

If radix is between 2 and 36, the long integer is expressed in base radix. If
radix is 0, the first few characters of 5 determine the base of the value being
converted.
First
character

Second
character

0
0

1-7
xorX

1-9

String interpreted as

Octal
Hexadecimal
Decimal

If radix is 1, it is considered to be an invalid value. If radix is less than 0 or
greater than 36, it is considered to be an invalid value.
Any invalid value for radix causes the result to be 0 and sets the next
character pointer *endptr to the starting string pointer.
If the value in 5 is meant to be interpreted as octal, any character other
than 0 to 7 will be unrecognized.
If the value in s is meant to be interpreted as decimal, any character other
than 0 to 9 will be unrecognized.
If the value in 5 is meant to be interpreted as a number in any other base,
then only the numerals and letters used to represent numbers in that base
will be recognized. (For example, if radix equals 5, only 0 to 4 will be
recognized; if radix equals 20, only 0 to 9 and A to J will be recognized.)
If endptr is not null, strtol sets *endptr to point to the character that
stopped the scan (*endptr = &stopper).

Chapter 2, The run-time library

549

strtol

Return value

strtol returns the value of the converted string, or 0 on error.

See also

atoi, atol, strtoul

Example

#include 
#include 
int main(void)
{

char *string = "87654321", *endptr;
long lnumber;
/* strtol converts string to long integer */
lnumber = strtol(string, &endptr, 10);
printf("string = %s long = %ld\n", string, lnumber);
return 0;

strtoul
Function
Syntax

Remarks

Return value

Converts a string to an unsigned long in the given radix.
#include 
unsigned long strtoul(const char *s, char **endptr, int radix);

strtoul operates the same as strtol, except that it converts a string str to an
unsigned long value (where strtol converts to a long). Refer to the entry
for strtol for more information.
strtoul returns the converted value, an unsigned long, or 0 on error.

See also

atol, strtol

Example

#include 
#include 
int main (void)
{

char *string = "87654321", *endptr;
unsigned long lnumber;
lnumber = strtoul(string, &endptr, 10);
printf("string = %s long = %lu\n", string, lnumber);
return 0;

550

Borland C++ Library Reference

strupr, _fstrupr

strupr, _fstrupr
Function
Syntax

Converts lowercase letters in a string to uppercase.
#include 
Near version: char *struprCchar *s);
Far version: char far * far _fstruprCchar far *s)

I
I
Remarks
Return value

DOS

I
• I

UNIX

Windows

I

•

I

ANSI C

I C++ only
I

strupr converts lowercase letters Ca-z) in string s to uppercase CA-Z). No
other characters are changed.
strupr returns s.

See also

strlwr

Example

#include 
#include 
int main(void)
{

char *string

= "abcdefghijklmnopqrstuvwxyz" , *ptri

/* converts string to uppercase characters */
ptr = strupr(string) i
printf ("%s\n", ptr) i
return 0i

strxfrm
Function
Syntax

Transforms a portion of a string.
#include
.
size_t strxfrmCchar *s1, char *s2, size_t n);
DOS

UNIX

•
Remarks
Return value

I
I

Windows

ANSI C

•

•

C++ only

I
I

strxfrm transforms the string pointed to by s2 into the string s1 for no
more than n characters.

Number of characters copied.

Chapter 2, The run-time library

551

strxfrm

See also

strcoll, strncpy

Example

#include 
#include 
#include 
int main(void)
{

char *target, *source
int length;

=

"Frank Borland";

/* allocate space for the target string */
target = (char *) calloc(80, sizeof(char));
/* copy the source over to the target and get the length */
length = strxfrm(target, source, 80);
/* print out the results */
printf("%s has the length %d\n", target, length);
return 0;

swab
Function
Syntax

Remarks

Return value
Example

Swaps bytes.
#include 
void swab(char *from, char *to, int nbytes);

swab copies nbytes bytes from the from string to the to string. Adjacent
even- and odd-byte positions are swapped. This is useful for moving data
from one machine to another machine with a different byte order. nbytes
should be even.

None.
#include 
#include 
#include 
char source[15] = "rFna koBlrna d";
char target[15];
int main (void)
(

swab(source, target, strlen(source));

552

Borland C++ Library Reference

swab

printf("This is target: %s\n", target);
return 0;

system
Function
Syntax

Remarks

Issues a DOS command.
#include 
int system(const char *command);

system invokes the DOS COMMAND.COM file to execute a DOS

command, batch file, or other program named by the string command,
from inside an executing C program.
To be located and executed, the program must be in the current directory
or in one of the directories listed in the PATH string in the environment.
The COMSPEC environment variable is used to find the
COMMAND.COM file, so that file need not be in the current directory.
Return value

If command is a NULL pointer, then system returns nonzero if a command
processor is available. If command is not a NULL pointer, system returns
zero if the command processor was successfully started. If an error
occurred, a -1 is returned and errno is set to ENOENT, ENOMEM, E2BIG,
orENOEXEC.

See also

exec ... , _fpreset, search path, spawn ...

Example

#include 
#include 
int main(void)
{

printf(IIAbout to spawn command.com and run a DOS command\n");
system( "dir");
return 0;

Chapter 2, The run-time library

553

tan, tanl

tan, toni
Function
Syntax

Calculates the tangent.

Real version:
#include 
double tan(double x);
long double tanl(long double x);
DOS

fanl

•

Rea/fan

•
•

Complex fan

Remarks

UNIX

Windows

ANSI C

Complex version:
#include 
complex tan(complex x);

C++ only

•
•

•
•

•

•

tan calculates the tangent. Angles are specified in radians.
tanl is the long double version; it takes a long double argument and

returns a long double result.
Error handling for these routines can be modified through the functions
math err and _matherrl.
The complex tangent is defined by
tan(z)
Return value

= sin(z) /

cos(z)

tan and tanl return the tangent of x, sin(x) / cos(x).

See also

acos, asin, atan, atan2, complex, cos, sin

Example

#include 
#include 
int main (void)
{

double result, x = 0.5;
result = tan (x) ;
printf("The tangent of %If is %If\n", x, result);
return 0;

tanh, tanhl
Function

554

Calculates the hyperbolic tangent.

Borland C++ Library Reference

tanh, tanhl

Syntax

Complex version:
Real versions:
#include 
#include 
complex tanh(complex x);
double tanh(double x);
long double tanhl(long double x);
DDS

tanhl

Rea/tanh

•
•

Complex tanh

•

Remarks

UNIX

Wi ndows

ANSI C

•
•

•

•

•

C++ only

•

tanh computes the hyperbolic tangent, sinh(x) / cosh(x).
tanhl is the long double version; it takes a long double argument and

returns a long double result.
Error handling for these functions can be modified through the functions
math err and _matherrl.
The complex hyperbolic tangent is defined by
tanh(z) = sinh(z) / cosh(z)
Return value

tanh and tanhl return the hyperbolic tangent of x.

See also

complex, cos, cosh, sin, sinh, tan

Example

#include 
#include 
int main(void)
{

double result, x = 0.5;
result = tanh(x);
printf ("The hyperbolic tangent of %If is %If\n'', x, result) i
return 0;

tell
Function
Syntax

Gets the current position of a file pointer.
#include 
long tell(int handle);

Chapter 2, The run-time library

555

tell

Remarks
Return value

tell gets the current position of the file pointer associated with handle and

expresses it as the number of bytes from the beginning of the file.
tell returns the current file pointer position. A return of -1 (long) indicates

an error, and the global variable errno is set to
EBADF

Bad file number

See also

fgetpos, fseek, ftell, Iseek

Example

#include
#include
#include
#include






int main(void)
{

int handle;
char msg[] = "Hello world";
if ((handle = open("TEST.$$$", O_CREAT
perror("Error:") ;
return 1;

O_TEXT 10_APPEND)) ==

-1)

{

write(handle, msg, strlen(msg));
printf ("The file pointer is at byte %ld\n", tell (handle)) ;
close(handle) ;
return 0;

tempnam
Function
Syntax

Remarks

Creates a unique file name in specified directory.
#include 
char *tempnam(char *dir, char *prefix)

The tempnam function creates a unique filename in arbitrary directories.
It attempts to use the following directories, in the order shown, when
creating the file name:
• The directory specified by the TMP environment variable .
• The dir argument to tempnam.
II The P_tmpdir definition in stdio.h. If you edit stdio.h and change this
definition, tempnam will NOT use the new definition.

556

BorlandC++ Library Reference

tempnam

II

The current working directory.

If any of these directories is NULL, or undefined, or does not exist, it is
skipped.

The prefix argument specifies the first part of the filename; it cannot be
longer than 5 characters, and may not contain a period (.). A unique
filename is created by concatenating the directory name, the prefix, and 6
unique characters. Space for the resulting filename is allocated with
malloe; the caller should free this filename when no longer needed by
calling free. The unique file is not actually created; tempnam only verifies
that it does not currently exist.
-..

Return value

If you do create a temporary file using the name constructed by tempnam,
it is your responsibility to delete the file name (for example, with a call to
remove). It is not deleted automatically. (tmpfile does delete the file name.)
If tempnam is successful, it returns a pointer to the unique temporary file
name, which the caller may pass to free when it is no longer needed.
Otherwise, if tempnam cannot create a unique filename, it returns NULL.

See also

mktemp, tmpfile, tmpnam

Example

#include 
#include 

I

void main(void)
{

FILE *stream;
int i;
char *name;
for (i = 1; i <= 10; itt) {
if ((name = tempnam (
tmp ", wow
== NULL)
perror("tempnam couldn't create name");
else {
printf("Creating %s\n",name);
if ((stream = fopen (name, "wb")) == NULL)
perror("Could not open temporary file\n");
else
fclose (stream) ;
II \

\

II

II ) )

•

free (name);
printf ("Warning: temp files not deleted. \n") ;

Chapter 2, The run-time library

557

textoHr

textattr
Function
Syntax

Remarks

Sets text attributes.
#include 
void textattr(int newattr);

textattr lets you set both the foreground and background colors in a single
call. (Normally, you set the attributes with textcolor and textbackground.)

This function does not affect any characters currently on the screen; it only
affects those displayed by functions (such as cprintf) performing text
mode, direct video output after this function is called.
The color information is encoded in the newattr parameter as follows:

7

6

5

4

I

3

2

1

0

IBlblblbl fl fl fl fl
I
In this 8-bit newattr parameter,

ffff is the 4-bit foreground color (0 to 15).
bbb is the 3-bit background color (0 to 7).
B is the blink-enable bit.
If the blink-enable bit is on, the character blinks. This can be accomplished
by adding the constant BLINK to the attribute.
If you use the symbolic color constants defined in conio.h for creating text
attributes with textattr, note the following limitations on the color you
select for the background:
• You can only select one of the first eight colors for the background .
• You must shift the selected background color left by 4 bits to move it
into the correct bit positions.
These symbolic constants are listed in the following table:

558

Borland C++ Library Reference

textaHr

Symbolic constant

BLACK
BLUE
GREEN
CYAN
RED
MAGENTA
BROWN
LIGHTGRAY
DARKGRAY
LIGHTBLUE
LIGHTGREEN
LIGHTCYAN
LIGHTRED
LIGHTMAGENTA
YELLOW
WHITE
BLINK

Return value

Numeric
value

o
1
2
3

4
5
6
7

8
9
10
11

12
13
14
15
128

Foreground or background?

Both
Both
Both
Both
Both
Both
Both
Both
Foreground only
Foreground only
Foreground only
Foreground only
Foreground only
Foreground only
Foreground only
Foreground only
Foreground only

None.

See also

gettextinfo, highvideo, lowvideo, normvideo, textbackground, textcolor

Example

#include 
int main(void)
{

int i;
clrscr () ;
for (i = 0; i < 9; iff) {
textattr(i + ((i+l) « 4));
cprintf(nThis is a test\r\nn);
return 0;

textbackground
Function

Selects new text background color.

Syntax

#include 
void textbackground(int newcolor);

Chapter 2, The run-time library

559

textbackground

Remarks

textbackground selects the background color. This function works for
functions that produce output in text mode directly to the screen. newcolor
selects the new background color. You can set newcolor to an integer from
a to 7, or to one of the symbolic constants defined in conio.h. If you use
symbolic constants, you must include conio.h.

Once you have called textbackground, all subsequent functions using
direct video output (such as cprintf) will use newcolor. textbackground
does not affect any characters currently onscreen.
The following table lists the symbolic constants and the numeric values of
the allowable colors:
.
Symbolic constant

Numeric value

BLACK
BLUE
GREEN
CYAN
RED
MAGENTA
BROWN
LIGHTGRAY

Return value

a
1
2

3
4
5
6
7

None.

See also

gettextinfo, textattr, textcolor

Example

#include 
int main(void)
{

int i, j;
clrscr () ;
for (i=O; i<9; itt)
for (j=O; j<80; jtt)
cprintf ("e") ;
cprintf (" \r\n") ;
textcolor(itl) ;
textbackground(i);
}

return 0;

textcolor
Function

560

Selects new character color in text mode.

Borland C++ Library Reference

textcolor

Syntax

Remarks

#include 
void textcolor(int newcolor);

textcolor selects the foreground character color. This function works for

the console output functions. newcolor selects the new foreground color.
You can set newcolor to an integer as given in the table below, or to one of
the symbolic constants defined in conio.h. If you use symbolic constants,
you must include conio.h.
Once you have called textcolor, all subsequent functions using direct
video output (such as cprintf) will use newcolor. textcolor does not affect
any characters currently onscreen.
The following table lists the allowable colors (as symbolic constants) and
their numeric values:
Symbolic constant

Numeric value

o

BLACK
BLUE
GREEN
CYAN
RED
MAGENTA
BROWN
LIGHTGRAY
DARKGRAY
LIGHTBLUE
LIGHTGREEN
LIGHTCYAN
LIGHTRED
LIGHTMAGENTA
YELLOW
WHITE
BLINK

1
2

3
4
5
6
7
8
9

10
11

12
13
14
15
128

You can make the characters blink by adding 128 to the foreground color.
The predefined constant BLINK exists for this purpose; for exmTIple,
textcolor(CYAN + BLINK)

...

i

Some monitors do not recognize the intensity signal used to create the
eight "light" colors (8-15). On such monitors, the light colors will be
displayed as their "dark" equivalents (0-7). Also, systems that do not
display in color can treat these numbers as shades of one color, special

Chapter 2, The run-time library

561

iii

textcolor

patterns, or special attributes (such as unde~lined, bold, italics, and so on).
Exactly what you'll see on such systems depends on your hardware.
Return value

None.

See also

gettextinfo, highvideo, lowvideo, normvideo, textattr, textbackground

Example

#include 
int main(void)
int i;
for (i=O; idS'; itt) {
textcolor(i) ;
cprintf("Foreground Color\r\n");
return 0;

textheight
Function
Syntax

Remarks

Returns the height of a string in pixels.
#inc1ude 
int far textheight(char far *textstring);

The graphics function textheight takes the current font size and
multiplication factor, and determines the height of textstring in pixels. This
function 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 so
on.
For example, with the 8x8 bit-mapped font and a multiplication factor of 1
(set by settextstyle), the string TurboC++ is 8 pixels high.

-..

Return value

562

Use textheight to compute the height of strings, instead of doing the
computations manually. By using this function, no source code
modifications have to be made when different fonts are selected.
textheight returns the text height in pixels.

See also

gettextsettings, outtext, outtextxy, settextstyle, textwidth

Example

#include 
#include 

Borland C++ Library Reference

textheight

#include 
#include 
int main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int y = 0;
int i;
char msg [80·] ;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode ! = grOk) { / * an error occurred * /
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(l);
/* terminate with an error code */
/* draw some text on the screen */
for (i=l; i<11; itt) {
/* select the text style, direction, and size */
settextstyle(TRIPLEX_FONT, HORIZ_DIR, i);
/* create a message string */
sprintf(msg, "Size: %d", i);
/* output the message */
outtextxy(l, y, msg);
/* advance to the next text line */
y += textheight(msg);
/* clean up */
getch() ;
closegraph ( ) ;
return 0;

textmode
Function
Syntax

Puts screen in text mode.
#include 
void textmode(int newmode);

Chapter 2, The run-time library

563

textmode

Remarks

textmode selects a specific text mode.

You can give the text mode (the argument newmode) by using a symbolic
constant from the enumeration type text_mQdes (defined in conio.h). If you
use these constants, you must include conio.h.
The text_modes type constants, their numeric values, and the modes they
specify are given in the following table:
Symbolic
constant

LASTMODE
BW40
C40
BW80
C80
MONO
C4350

Numeric
value

-1

a
1
2

3
7
64

Text mode

Previous text mode
Black and white, 40 columns
Color, 40 columns
Black and white, 80 columns
Color, 80 columns
Monochrome, 80 columns
EGA 43-line and VGA 50-line modes

When textmode is called, the current window is reset to the entire screen,
and the current text attributes are reset to normal, corresponding to a call
to normvideo.
Specifying LASTMODE to textmode causes the most recently selected text
mode to be reselected.
textmode should be used only when the screen is in text mode (pre-

sumably to change to a different text mode). This is the only context in
which textmode should be used. When the screen is in graphics mode, use
restorecrtmode instead to escape temporarily to text mode.
Return value

None.

See also

gettextinfo, window

Example

#include 
int main(void)
textmode(BW40) ;
cprintf (" ABC") ;
getch();
textmode(C40) ;
cprintf ("ABC");
getch() ;
textmode (BW80) ;

564

Borland C++ Library Reference

textmode

cprintf ("ABC") ;
getch();
textmode(C80) ;
cprintf ("ABC");
getch();
textmode(MONO) ;
cprintf ("ABC");
getch();
return 0;

textwidth
Function
Syntax

Remarks

Returns the width of a string in pixels.
#include 
int far textwidth(char far *textstring);

The graphics function textwidth takes the string length, current font size,
and multiplication factor, and determines the width of textstring in pixels.
This function is useful for computing viewport widths, sizing a title to
make it fit on a graph or in a box, and so on.

~

Return value

Use textwidth to compute the width of strings, instead of doing the
computations manually. When you use this function, no source code
modifications have to be made when different fonts are selected.
textwidth returns the text width in pixels.

See also

gettextsettings, outtext, outtextxy, settextstyle, textheight

Example

#include
#include
#include
#include






int,main(void)
{

/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int x = 0, y = 0;
int i;
char msg [801 ;

Chapter 2, The run-time library

565

textwidth

/* initialize graphics and local variables */
initgraph(&gdrtver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf (" Press any key to halt:");
getch() ;
exit(l);
/* terminate with an error code */

y = getmaxy() / 2;
settextjustify(LEFT_TEXT, CENTER_TEXT);
for (i = 1; i < 11; i ++) {
/* select the text style, direction, and size */
settextstyle(TRIPLEX_FONT, HORIZ_DIR, i);
/* create a message string */
sprintf(msg, "Size: %d", i);
/* output the message */
outtextxy(x, y, msg);
/* advance to the end of the text */
x += textwidth(msg);
/* clean up */
getch() ;
closegraph() ;
return 0;

time
Function
Syntax

Remarks

Return value

566

Gets time of day.
#inc1ude 
time_t time(time_t *timer);

time gives the current time, in seconds, elapsed since 00:00:00 GMT,
January 1, 1970, and stores that value in the location pointed to by timer,
provided that timer is not a null pointer.
time returns the elapsed time in seconds, as described.

Borland C++ Library Reference

time

See also

asctime, ctime, difftime, ftime, gettime, gmtime, localtime, settime, stime,
tzset

Example

#include 
#include 
#include 
int main(void)
(

time_t t;
t = time (NULL) ;
printf("The number of seconds since January I, 1970 is %ld",t);
return 0;

tmpfile
Function
Syntax

Remarks

Opens a "scratch" file in binary mode.
#include 
FILE *tmpfile(void);

tmpfile creates a temporary binary file and opens it for update (w + b). The
file is automatically removed when it's closed or when your program
terminates.
tmpfile creates the temporary file in the directory defined by the TMP

environment variable. If TMP is not defined, the TEMP environment
variable is used. If neither TMP or TEMP is defined, tmpfile creates the
files in the current directory.
Return value

tmpfile returns a pointer to the stream of the temporary file created. If the
file can't be created, tmpfile returns null.

See also

fopen, tmpnam

Example

#include 
#include 
int main (void)
(

*tempfp;
tempfp = tmpfile();
if (tempfp)

FILE

Chapter 2, The run-time library

567

tmpfile

printf("Temporary file created\n");
else {
printf ("Unable to create temporary file\n");
exit(l);
return 0;

tmpnam
Function
Syntax

Remarks

Creates a unique file name.
#include 
char *tmpnam(char *s);

tmpnam creates a unique file name, which can safely be used as the name
of a temporary file. tmpnam generates a different string each time you call

it, up to TMP_MAX times. TMP_MAX is defined in stdio.h as 65,535.
The parameter to tmpnam, s, is either null or a pointer to an array of at
least L_tmpnam characters. L_tmpnam is defined in stdio.h. If s is null,
tmpnam leaves the generated temporary file name in an internal static
object and returns a pointer to that object. If s is not null, tmpnam places
its result in the pointed-to array, which must be at least L_tmpnam
characters long, and returns s.
tmpnam creates the temporary file in the directory defined by the TMP

environment variable. If TMP is not defined, the TEMP environment
variable is used. If neither TMP or TEMP is defined, tmpnam creates the
files in the current directory.
-..

If you do create such a temporary file with tmpnam, it is your responsibility to delete the file name (for example, with a call to remove). It is not
deleted automatically. (tmpfile does delete the file name.)

Return value , If s is null, tmpnam returns a pointer to an internal static object.
Otherwise, tmpnam returns s.

See also

tmpfile

Example

#include 
int main(void)
{

568

Borland C++ Library Reference

tmpnam

char name [13 J ;
tmpnam (name) ;
printf ("Temporary name: %s\n", name);
return 0;

toascii
Function
Syntax

Translates characters to ASCII format.
#include 
int toascii(int c);
DOS

UNIX

•
Remarks

Wi ndows

•

•

ANSI C

I c++
I

only

I

JI

toascii is a macro that converts the integer c to ASCII by clearing all but

the lower 7 bits; this gives a value in the range a to 127.

Return value
Example

toascii returns the converted value of c.
#include 
#include 
int main(void)
{

int number, result;
number = 511;
result = toascii(number);
printf("%d %d\n", number, result);
return 0;

_tolower
Function
Syntax

Remarks

Translates characters to lowercase.
#include 
int _tolower(int ch);

_tolower is a macro that does the same conversion as tolower, except that
it should be used only when ch is known to be uppercase (A-Z).

Chapter 2, The run-time library

569

_tolower

To use _tolower, you must include ctype.h.
Return value

_tolower returns the converted value of ch if it is uppercase; otherwise, the

result is undefined.
Example

#include 
#include 
#include 
int main(void)
{

int length, i;
char *string = "THIS IS A STRING.";
1* We should be checking each character to make sure it is an uppercase before
passing it to _tolower! The result of passing it a non-uppercase is
undefined. *1
length = strlen(string);
for (i = 0; i < length; itt)
string[i] = _tolower(string[i]);
printf("%s\n",string);
return 0;

tolower
Function
Syntax

Remarks

Translates characters to lowercase.
#include 
int tolower(int ch);

tolower is a function that converts an integer ch (in the range EOF to 255)

to its lowercase value (a to z; if it was uppercase, A to Z). All others are left
unchanged.
Return value

tolower returns the converted value of ch if it is uppercase; it returns all.

others unchanged.
Example

#include 
#include 
#include 
int main (void)
{

int length, i;

570

Borland C++ Library Reference

tolower

char *string = "THIS IS A STRING";
length = strlen(string);
for (i = 0; i < length; itt)
string[i] = tolower(string[i]);
printf("%s\n",string) ;
return 0;

_toupper
Function
Syntax

Remarks

Translates characters to uppercase.
#include 
int _toupper(int ch);

_toupper is a macro that does the same conversion as toupper, except that
it should be used only when ch is known to be lowercase (a to z).

To use _toupper, you must include ctype.h.
Return value

_toupper returns the converted value of ch if it is lowercase; otherwise, the

result is undefined.
Example

#include 
#include 
#include 
int main(void)
{

int length, i;
char *string = "this is a string";
/* We should be checking each character to make sure it is lowercase before
passing it to _toupper. The result passing a non-lowercase is undefined. */
length = strlen(string);
for (i = 0; i < length; itt)
string[i] = _toupper(string[i]);
printf("%s\n",string);
return 0;

Chapter 2, The run-time library

571

•

toupper

toupper
Function
Syntax

Remarks

Translates characters to uppercase.
#include 
int toupper(int ch);

toupper is a function that converts an integer ch (in the range EOF to 255)
to its uppercase value (A to Z; if it was lowercase, a to z). All others are left

unchanged.
Return value

toupper returns the converted value of ch if it is lowercase; it returns all

others unchanged.
Example

#incl ude 
#include 
#include 
int main(void)
{

int length, i;
char *string = "this is a string";
length = strlen(string);
for (i = 0; i < length; itt)
string[i] = toupper(string[i]);
printf("%s\n",string) ;
return 0;

tzset
Function
Syntax

Remarks

Sets value of global variables daylight, timezone, and tzname.
#include 
void tzset( void)

tzset is available on XENIX systems.
tzset sets the daylight,

timezone, and tzname global variables based on the
environment variable TZ. The library functions ftime and localtime use

572

Borland C++ Library Reference

tzset

these global variables to correct Greenwich mean time (GMT) to whatever
the local time zone is. The format of the TZ environment string follows:
TZ = zzz[+/-]d[d] [111]

zzz is a three-character string representing the name of the current time
zone. All three characters are required. For example, the string "PST"
could be used to represent Pacific Standard Time.

[+j-]d[d] is a required field containing an optionally signed number with 1
or more digits. This number is the local time zone's difference from GMT
in hours. Positive numbers adjust westward from GMT. Negative numbers adjust eastward from GMT. For example, the number 5 = EST, +8 =
PST, and -1 = continental Europe. This number is used in the calculation
of the global variable timczone. timezone is the difference in seconds
between GMT and the local time zone.
III is an optional three-character field that represents the local time zone
daylight saving time. For example, the string "PDT" could be used to
represent Pacific daylight saving time. If this field is present, it will cause
the global variable daylight to be set nonzero. If this field is absent, daylight
will be set to zero.
If the TZ environment string isn't present or isn't in the preceding form, a
default TZ = "EST5EDT" is presumed for the purposes of assigning values
to the global variables daylight, timezone, and tzname.

The global variable tzname[O] points to a three-character string with the
value of the time-zone name from the TZ environment string. tzname[1]
points to a three-character string with the value of the daylight saving
time-zone name from the TZ environment string. If no daylight saving
name is present, tzname[1] points to a null string.
Return value

None.

See also

asctime, ctime, ftime, gmtime, localtime, stime, time

Example

#include
#include
#include

•





int main(void)
{

time_t td;
putenv ("TZ=PST8PDT") ;
tzset();
time (&td) ;
printf("Current time = %s\n", asctime(localtime(&td)));

Chapter 2, The run-time library

573

tzset

return 0;

ultoa
Function
Syntax

Remarks

Converts an unsigned long to a string.
#include 
char *ultoa(unsigned long value, char *string, int radix);

ultoa converts value to a null-terminated string and stores the result in
string. value is an unsigned long.

radix specifies the base to be used in converting value; it must be between 2
and 36, inclusive. ultoa performs no overflow checking, and if value is
negative and radix equals 10, it does not set the minus sign.
..

Return value

The space allocated for string must be large enough to hold the returned
string, including the terminating null character (\0). ultoa can return up to
33 bytes.
ultoa returns string.

See also

itoa, Itoa

Example

#include 
#include 
int main(void)
{

unsigned long lnumber = 3123456789L;
char string[25];
ultoa(lnumber,string,10);
printf(llstring = %s unsigned long = %lu\n",string,lnumber);
return 0;

574

Borland C++ Library Reference

umask

umask
Function
Syntax

Remarks

Sets file read/write permission mask.
#include 
unsigned umask(unsigned mode);

The umask function sets the access permission mask used by
open and creat. Bits that are set in mode will be cleared in the
access permission of files subsequently created by open and creat.
The mode can have one of the following values, defined in sys \
stat.h:

Return value

Value of mode

Access permission

S_IWRITE
S_IREAD
S_IREAD I S_IWRITE

Permission to write
Permission to read
Permission to read and write

The previous value of the mask. There is no error return.

See also

creat, open

Example

#include 
#include 
#include 
#define FILENAME "TEST.$$$"
int main (void)
{

II

unsigned oldmaski
FILE *fi
struct stat statbuf;
1* Cause subsequent files to be created as read-only *1
oldmask = umask(S_IWRITE)i
printf ("Old mask = Ox%x\n", oldmask);
1* Create a zero-length file */
if ((f = fopen(FILENAME, "w")) == NULL)
perror("Unable to create output file");
return (1);

Chapter 2, The run-time library

575

umask

fclose (f) ;
/* Verify that the file is read-only */
if (stat (FILENAME,&statbuf) != 0) {
perror("Unable to get information about output file");
return (1);

if (statbuf.st_mode & S_IWRITE)
print f ("Error! %s is writable! \n" , FILENAME) ;
else
printf("Success! %s is not writable. \n" ,FILENAME);
return(O);

ungetc
Function
Syntax

Remarks

Return value

Pushes a character back into input stream.
#include 
int ungetc(int c, FILE *stream);

ungetc pushes the character c back onto the named input stream,
which must be open for reading. This character will be returned
on the next call to getc or fread for that stream. One character can
be pushed back in all situations. A second call to ungetc without a
call to getc will force the previous character to be forgotten. A call
to fflush, fseek, fsetpos, or rewind erases all memory of any
pushed-back characters.

On success, ungetc returns the character pushed back; it returns
EOF if the operation fails.

See also

fgetc, getc, getchar

Example

#include 
#include 
int main(void)
{

int i=O;
char Chi
puts("Input an integer followed by a char:");
/* read chars until nondigit or EOF */
while( (ch = getchar()) != EOF && isdigit(ch))

576

Borland C++ Library Reference

ungetc

i

= 10 *

i + ch - 48;

/* convert ASCII into int value */

/* if nondigit char was read, push it back into input buffer */
if (ch ! = EOF)

ungetc(ch, stdin);
printf("i = %d, next char in buffer = %c\n", i, getchar());
return 0;

ungetch
Function
Syntax

Remarks

Return value

Pushes a character back to the keyboard buffer.
#include 
int ungetch(int ch);

ungetch pushes the character ch back to the console, causing ch to
be the next character read. The ungetch function fails if it is called
more than once before the next read.
'
ungetch returns the character ch if it is successful. A return value
of EOF indicates an error.

See also

getch, getche

Example

#include 
#include 
#include 
int main(void)
{

int i=O;
char ch;
puts (" Input an integer followed by a char:");

•

/* read chars until nondigit or EOF */
while((ch = getche()) != EOF && isdigit(ch))
i = 10 * i + ch - 48;
/* convert ASCII into int value */
/* if nondigit char was read, push it back into input buffer */
if (ch != EOF)
ungetch (ch) ;
printf("\n\ni
%d, next char in buffer = %c\n", i, getch());
return 0;

Chapter 2, The run-time library

577

unixtodos

unixtodos
Function
Syntax

Remarks

Converts date and time from UNIX to DOS format.
#include 
void unixtodos(long time, struct date *d, struct time *t);

unixtodos converts the UNIX-format time given in time to DOS
format and fills in the date and time structures pointed to by d
and t.

time must not represent a calender time earlier than Jan 1 1980
00:00:00.
Return value

None.

See also

dostoun ix

Example

#inc1ude 
#include 
char *month[]

"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

= { "

#define SECONDS PER_DAY 86400L

/* number of secs in one day

struct date dt;
struct time tm;
int main(void)
{

unsigned long val;
/* get today's date and time */
getdate(&dt);
gettime (&tm) ;
printf("Today is %d %s %d\n", dt.da_day, month[dt.da_mon],
dt .da-year) ;
/* convert date and time to unix format (number of secs since Jan 1,
1970 */
val = dostounix(&dt, &tm);
/* subtract 42 days worth of seconds */
val -= (SECONDS_PER_DAY * 42);
/* convert back to dos time and date */
unixtodos(val, &dt, &tm);

578

Borland C++ Library Reference

unixtodos

printf("42 days ago it was %d %s %d\n", dt.da_day, month[dt.da_monl,
dt . da-year) ;
return 0;

unlink
Function
Syntax

Remarks

Deletes a file.
#include 
int unlink(const char *filename);

unlink deletes a file specified by filename. Any DOS drive, path,
and file name can be used as a filename. Wildcards are not
allowed.

Read-only files cannot be deleted by this call. To remove readonly files, first use chmod or _chmod to change the read-only
attribute.
~

Return value

If your file is open, be sure to close it before unlinking it.

On successful completion, unlink returns O. On error, it returns -1
and the global variable errno is set to one of the following values:
ENOENT
EACCES

Path or file name not found
Permission denied

See also

chmod, remove

Example

#include 
#include do. h>

II

int main(void)
{

FILE *fp = fopen("junk.jnk","w");
int status;
fprintf(fp, "junk");
status = access("junk.jnk",O);
if (status == 0)
printf("File exists\n");
else
printf("File doesn't exist\n");
fclose(fp) ;
unl ink ( "j unk. j nk" ) ;

Chapter 2, The run-time library

579

unlink

status = access("junk.jnk",O);
if (status == 0)
printf("File exists\n"),
else
printf("File doesn't exist\n");
return 0;

unlock
Function
Syntax

Remarks

Releases file-sharing locks.
#include 
int unlock(int handle, long offset, long length);

unlock provides an interface to the DOS 3.x file-sharing
mechanism.
unlock removes a lock previously placed witl) a call to lock. To
avoid error, all locks must be removed before a file is closed. A
program must release all locks before completing.

Return value

unlock returns 0 on success, -1 on error.

See also

lock, sopen

Example

#include
#include
#include
#include
#include
#include








int main (void)
{

int handle, status;
long length;
handle = sopen("c:\\autoexec.bat",O_RDONLY,SH_DENYNO,S_IREAD);
if (handle < 0) {
printf("sopen failed\n");
exit (1) ;
length
status

580

= filelength(handle);
= lock(handle,OL,length/2);

Borland C++ Library Reference

unlock

if (status == 0)
printf("lock succeeded\n");
else
print f ( "lock failed \n" ) ;
status = unlock(handle,OL,length/2);
if (status == 0)
printf("unlock succeeded\n");
else
printf("unlock failed\n");
close (handle) ;
return 0;

utime
Function
Syntax

Remarks

Sets file time and date.
#include 
int utime(char *path, struct utimbuf *times);

utime sets the modification time for the file path. The modification
time is contained in the utimbuf structure pointed to by times. This
structure is defined in utime.h, and has the following format:
struct utimbuf {
time_t actime;
time_t modtime;

/* access time */
/* modification time */

};

The DOS file system supports only a modification time; therefore,
on DOS utime ignores actime and uses only modtime to set the file's
modification time.
If times is NULL, the file's modification time is set to the current
time.
Return value

utime returns a if it is successful. Otherwise, it returns -1, and the
global variable errno is set to one of the following:

EACCES
EMFILE
ENOENT
See also

Permission denied
Too many open files
Path or file name not found

setftime, stat, time

Chapter 2, The run-time library

581

utime

Example

/* Copy timestamp from one file to another */
#include 
#include 
#include 
int main( int argc, char *argv[]
{

struct stat src_stat;
struct utimbuf times;
if (argc ! = 3) {
printf( "Usage: copy time  \n" );
return 1;
if (stat (argv[l],&src_stat) != 0) {

perror("Unable to get status of source file");
return 1;
times.modtime = times.actime = src_stat.st_mtime;
if (utime(argv[2],×) != 0) {
perror("Unable to set time of destination file");
return 1;
return 0;

Function
Syntax

Remarks

582

Implement a variable argument list.
#include 
void va_start(va_list ap, lastfix);
type va_arg(va_list ap, type);
void va_end(va_list ap);

Some C functions, such as vfprintf and vprintf, take variable
argument lists in addition to taking a number of fixed (known)
parameters. The va_arg, va_end, and va_start macros provide a
portable way to access these argument lists. They are used for
stepping through a list of arguments when the called function
does not know the number and types of the arguments being
passed.

Borland C++ Library Reference

The header file stdarg.h declares one type (va_list) and three
macros (va_start, va_arg, and va_end).
VB_list This array holds information needed by va __ arg and
va_end. When a called function takes a variable argument list, it

declares a variable ap of type va_list.
va_start: This routine (implemented as a macro) sets ap to point to

the first of the variable arguments being passed to the function.
va_start must be used before the first call to va_arg or va __end.
va_start takes two parameters: ap and lastfix. (ap is explained

under va_list in the preceding paragraph; lastfix is the name of the
last fixed parameter being passed to the called function.)
va_arg: This routine (also implemented as a macro) expands to an
expression that has the same type and value as the next argument
being passed (one of the variable arguments). The variable np to
va_arg should be the same ap that va_start initialized.

b!$>

Because of default promotions, you can't use char, unsigned char,
or float types with va_argo
The first time va_arg is used, it returns the first argument in the
list. Each successive time va_arg is used, it returns the next
argument in the list. It does this by first dereferencing ap, and
then incrementing ap to point to the following item. va_arg uses
the type to both perform the dereference and to locate the
following item. Each successive time va_arg is invoked, it
modifies ap to point to the next argument in the list.
va_end: This macro helps the called function perform a normal
return. va_end might modify ap in such a way that it cannot be
used unless va_start is recalled. va_end should be called after
va_arg has read all the arguments; failure to do so might cause

strange, undefined behavior in your program.
Return value
See also
Example 1

•

va_start and va_end return no values; va_arg returns the current
argument in the list (the one that ap is pointing to).
v ... printf, v ... scanf
#inc1ude 
#include 
/* calculate sum of a 0 terminated list */
void sum(char *msg, ... )
int total

Chapter 2, The run-time library

=

0;

583

va_list ap;
int arg;
va_start (ap, msg);
while ((arg = va_arg(ap,int))
total += arg;
printf(msg, total);
va_end (ap) ;

!=

0)

int main(void)
sum("The total of 1+2+3+4 is %d\n", 1,2,3,4,0);
return 0;

Program output
The total of 1+2+3+4 is 10
Example 2

#include 
#include 
void error(char *format, ... )
{

va_list argptr;
printf("Error: ");
va_start (argptr, format);
vprintf(format, argptr);
va_end (argptr) ;
int main(void)
int value = -1;
error(IIThis is just an error message\n");
error("Invalid value %d encountered\n", value);
return 0;

Program output
Error: This is just an error message
Error: Invalid value -1 encountered

vfprintf
Function
Syntax

584

Writes formatted output to a stream.
#include 
int vfprintf(FILE *stream, canst char *format, va_list arglist);

Borland c++ Library Reference

vfprintf

Remarks

Available on UNIX System V.
The v ... printf functions are known as alternate entry points for the
... printf functions. They behave exactly like their ... printf
counterparts, but they accept a pointer to a list of arguments
instead of an argument list.

See prinff for details
on format specifiers.

Return value

vfprintf accepts a pointer to a series of arguments, applies to each

argument a format specifier contained in the format string
pointed to by format, and outputs the formatted data to a stream.
There must be the same number of format specifiers as
arguments.
vfprintf returns the number of bytes output. In the event of error,
vfprintf returns EOP.

See also

printf, va_arg, va_end, va_start

Example

#inelude 
#inelude 
FILE *fp;
int vfpf(ehar *fmt, ... )
{

va_list argptr;
int ent;
va_start (argptr, fmt);
ent = vfprintf(fp, fmt, argptr);
va_end (argptr) ;
return (ent) ;
int main(void)
{

int inumber = 30;
float fnumber = 90.0;
char string[4] = "abc";
fp = tmpfile () ;
if (fp == NULL) {
perror ( "tmpfile () call");
exit (1) ;
vfpf("%d %f %s", inumber, fnumber, string);
rewind ( fp) ;
fseanf(fp, "%d %f %s", &inumber, &fnumber, string);
printf("%d %f %s\n", inumber, fnumber, string);

Chapter 2, The run-time library

585

vfprintf

fc10se (fp);
return 0;

vfsconf
Function
Syntax

Remarks

Scans and formats input from a stream.
#include 
int vfscanf{FILE *stream, const char *format, va_list arglist);

Available on UNIX System V.
The v ... seanf functions are known as alternate entry points for the
... seanf functions. They behave exactly like their ... seanf
counterparts, but they accept a pointer to a list of arguments
instead of an argument list.

See scant for details
on format specifiers.

vfseanf scans a series of input fields, one character at a time,
reading from a stream. Then each field is formatted according to a
format specifier passed to vfseanf in the format string pointed to
by format. Finally, vfseanf stores the formatted input at an address
passed to it as an argument following format. There must be the
same number of format specifiers and addresses as there are input
fields.
vfseanf might stop scanning a particular field before it reaches the
normal end-of-field (whitespace) character, or it might terminate
entirely, for a number of reasons. See seanf for a discussion of
possible causes:

Return value

vfseanf returns the number of input fields successfully scanned,

converted, and stored; the return value does not include scanned
fields that were not stored. If no fields were stored, the return
value is O.
If vfseanf attempts to read at end-of-file, the return value is EOF.
See also

fseanf, seanf, va_arg, va_end, va_start

Example

#inc1ude 
#include 
FILE *fp;

586

Borland C++ Library Reference

vfscanf

int vfsf(ehar *fmt, ... )
{

va_list argptr;
int cnt;
va_start (argptr, fmt);
ent = vfscanf(fp, fmt, argptr);
va_end (argptr) ;
return (cnt);

int main (void)
{

int inumber = 30;
float fnumber = 90.0;
char string[4] = "abc";
fp = tmpfile () ;
if (fp == NULL) {
perror("tmpfile() call");
exit(l) ;
fprintf(fp,"%d %f %s\n",inumber,fnumber,string);
rewind ( fp) ;
vfs f ( "%d %f %s", &inumber, &fnumber, string) ;
printf("%d %f %s\n",inumber,fnumber,string);
fclose (fp);
return 0;

vprintf
Function
Syntax

Remarks

Writes formatted output to stdout.
#include 
int vprintf(const char *format, va_list arglist);

Available on UNIX System V.
The v ... printf functions are known as alternate entry points for the
... printf functions. They behave exactly like their ... printf
counterparts, but they accept a pointer to a list of arguments
instead of an argument list.

See printf for details
on format specifiers.

vprintf accepts a pointer to a series of arguments, applies to each a
format specifier contained in the format string pointed to by

Chapter 2, The run-time library

587

vprintf

format, and outputs the formatted data to stdout. There must be
the same number of format specifiers as arguments.
_
Return value

When you use the SS!=DS flag, vprintf assumes that the address
being passed is in the SS segment.
vprint returns the number of bytes output. In the event of error,
vprint returns EOF.

See also

printf, va_arg, va_end, va_start

Example

#include 
int vpf(ehar *fmt, ... )
{

va_list argptr;
int ent;
va_start (argptr, format);
ent = vprintf(fmt, argptr);
va_end (argptr) ;
return (ent) ;
int main (void)
{

int inumber = 30;
float fnumber = 90.0;
char *string = "abc";
vpf ("%d %f %s\n", inumber, fnumber, string);
return 0;

vscanf
Function
Syntax

Remarks

Scans and formats input from stdin.
#include 
int vscanf(const char *format, va_list arglist);

Available on UNIX system V.
The v ... scanf functions are known as alternate entry points for the
.. .scanf functions. They behave exactly like their .. .scanf
counterparts, but they accept a pointer to a list of arguments
instead of an argument list.

588

Borland C++ Library Reference

vscanf

See scanf for details
on format specifiers.

vscanf scans a series of input fields, one character at a time,

reading from stdin. Then each field is formatted according to a
format specifier passed to vscanf in the format string pointed to
by format. Finally, vscanf stores the formatted input at an address·
passed to it as an argument following format. There must be the
same number of format specifiers and addresses as there are input
fields.
vscanf might stop scanning a particular field before it reaches the
normal end-of-field (whitespace) character, or it might terminate
entirely, for a number of reasons. See scanf for a discussion of

possible causes.
Return value

vscanf returns the number of input fields successfully scanned,
converted, and stored; the return value does not include scanned
fields that were not stored. If no fields were stored, the return
value is O.

If vscanf attempts to read at end-of-file, the return value is EOF.
See also

fscanf, scanf, va_arg, va_end, va_start

Example

#include 
#include 
int vscnf(char *fmt, ... )
va_list argptr;
int cnt;
printf("Enter an integer, a float, and a string (e.g., i,f,s,)\n");
va_start (argptr, fmt);
cnt = vscanf(fmt, argptr);
va_end (argptr) ;
return (cnt') ;
int main(void)
{

int inumber;
float fnumber;
char string[80);
vscnf (" %d, %f, %s", &inumber, &fnumber, string);
printf (" %d %f %s\n", inumber, fnumber, string);
return 0;

Chapter 2, The run-time library

589

vsprintf

vsprintf
Function
Syntax

Remarks

See prinff for details
on format specifiers.

Return value

Writes formatted output to a string.
#include 
int vsprintf(char *buffer, const char *format, va_list arglist);

Available on UNIX system V. The v ... printf functions are known
as alternate entry points for the ... printf functions. They behave
exactly like their ... printf counterparts, but they accept a pointer
to a list of arguments instead of an argument list.
vsprintf accepts a pointer to a series of arguments, applies to each

a format specifier contained in the format string pointed to by
format, and outputs the formatted data to a string. There must be
the same number of format specifiers as arguments.
vsprintf returns the number of bytes output. In the event of error,
vsprintf returns EOF.

See also

printf, va_arg, va_end, va_start

Example

#include 
#include 
char buffer[80];
int vspf(char *fmt, ... )
{

va_list argptr;
int cnt;
va_start (argptr, fmt);
cnt = vsprintf(buffer, fmt, argptr);
va_end (argptr) ;
return (cnt) ;
int main (void)
{

int inumber = 30;
float fnumber = 90.0;
char string[4] = "abc";
vspf (" %d, %f %s", inumber, fnumber, string);
printf ("%s\n", buffer);
return 0;

590

Borland C++ Library Reference

vsscanf

vsscanf
Function
Syntax

Remarks

Scans and formats input from a stream.
#include 
int vsscanf(const char *buffer, const char *format, va_list argiist);

Available on UNIX system V.
The v ... scanf functions are known as alternate entry points for the
... scanf functions. They behave exactly like their ... scanf
counterparts, but they accept a pointer to a list of arguments
instead of an argument list.

See scanf for details
on format specifiers.

vsscanf scans a series of input fields, one character at a time,
reading from a stream. Then each field is formatted according to a
format specifier passed to vsscanf in the format string pointed to
by format. Finally, vsscanf stores the formatted input at an
address passed to it as an argument following format. There must
be the same number of format specifiers and addresses as there
are input fields.
vsscanf might stop scanning a particular field before it reaches

the normal end-of-field (whitespace) character, or it might
terminate entirely, for a number of reasons. See scanf for a
discussion of possible causes.
Return value

vsscanf returns the number of input fields successfully scanned,
converted, and stored; the return value does not include scanned
fields that were not stored. If no fields were stored, the return
value is O.

•

If vsscanf attempts to read at end-of-string, the return value is
EOF.
See also

fscanf, scanf, sscanf, va_arg, va_end, va_start, vfscanf

Example

#include 
#include 
char buffer[80] = "30 90.0 abc";
int vssf(char *fmt,
oj
'0

Chapter 2, The run-time library

591

vsscanf

va_list argptr;
int ent;
fflush(stdin) ;
va_start (argptr, fmt);
ent = vsscanf(buffer, fmt, argptr);
va_end(argptr);
return(ent);
int main(void)
{

int inumber;
float fnumber;
char string[80];
vssf("%d %f %s", &inumber, &fnumber, string);
printf("%d %f %s\n", inumber, fnumber, string);
return 0;

wcstombs
Function
Syntax

Remarks

Converts a wchar_t array into a multibyte string.
#include 
size_t wcstombs(char *s, const wchar_t *pwcs, size_t n);

wcstombs converts the type wchar_t elements contained in pwcs
into a multibyte character string s. The process terminates if either
a null character or an invalid multibyte character is encountered.

No more than n bytes are modified. If n number of bytes are
processed before a null character is reached, the array s will not be
null terminated.
The behavior of wcstombs is affected by the setting of LC_CTYPE
category of the current locale.
Return value

592

If an invalid multibyte character is encountered, wcstombs
returns (size_t) -1. Otherwise, the function returns the number of
bytes modified, not including the terminating code, if any.

Borland C++ Library Reference

wctomb

wctomb
Function
Syntax

Remarks

Converts wchar_t code to a multibyte character.
#include 
int wctomb(char *5, wchar_t we);

If 5 is not null, wctomb determines the number of bytes needed to
represent the multibyte character corresponding to we (including
any change in shift state). The multibyte character is stored in 5.
At most MB_CUR_MAX characters are stored. If the value of we is
zero, wctomb is left in the initial state.
The behavior of wctomb is affected by the setting of LC_CTYPE
.category of the current locale.

Return value

If 5 is a null pointer, wctomb returns a nonzero or zero value, if
multibyte characters encodings, respectively, do or do not have
state-dependent encodings.
If 5 is not a null pointer, wctomb returns -1 if the we value does
not represent a valid multibyte character. Otherwise, wctomb
returns the number of bytes that are contained in the multibyte
character corresponding to we. In no case will the return value be
greater than the value of MB_CUR_MAX macro.

wherex
Function
Syntax

#include 
int wherex(void);
DOS

UNIX

•
Remarks

•

Gives horizontal cursor position within window.

I
I

Windows

ANSI C

C++ only

wherex returns the x-coordinate of the current cursor position

(within the current text window).
Return value

wherex returns an integer in the range 1 to 80.

Chapter 2, The run-time library

593

wherex

See also

gettextinfo, gataxy, wherey

Example

#include 
int main (void)
{

clrscr () ;
gotoxy(10,lO) ;
cprintf("Current location is X: %d
getch () ;
return 0;

Y: %d\r\n", wherex(), wherey());

wherey
Function
Syntax

Remarks

Gives vertical cursor position within window.
#include 
int wherey(void);

wherey returns the y-coordinate of the current cursor position

(within the current text window).
Return value

wherey returns an integer in the range 1 to 25, 43, or 50.

See also

gettextinfo, gataxy, wherex

Example

#include 
int main (void)
{

clrscr();
gotoxy(lO,lO) ;
cprintf ("Current location is X: %d
getch();
return 0;

Y: %d\r\n", wherex (), wherey () ) ;

window
Function
Syntax

594

Defines active text mode window.
#include 

Borland C++ Library Reference

window

void window(int left, int top, int right, int bottom);

Remarks

window defines a text window onscreen. If the coordinates are in
any way invalid, the call to window is ignored.

left and top are the screen coordinates of the upper left corner of
the window. right and bottom are the screen coordinates of the
lower right corner.
The minimum size of the text window is one column by one line.
The default window is full screen, with these coordinates:
80-column mode:
40-column mode:
Return value

1,1,80,25
1,1,40,25

None.

See also

clreol, clrscr, delline, gettextinfo, gotoxy, insline, puttext,
textmode

Example

#incl ude 

int main(void)
{

window(lO,lO,40,ll) ;
textcolor(BLACK) ;
textbackground(WHITE);
cprintf("This is a test\r\n");
return 0;

_write
Function
Syntax

Remarks

Writes to a file.
#include 
int _writeCint handle, void *buf, unsigned len);

_write attempts to write len bytes from the buffer pointed to by buf

to the file associated with handle. The maximum number of bytes

Chapter 2, The run-time library

595

_write

that _write can write is 65,534, because 65,535 (OxFFFF) is the same
as -1, which is the error return indicator for _write.
_write does not translate a linefeed character (LF) to a CR/LF pair
because all its files are binary files.

If the number of bytes actually written is less than that requested,
. the condition should be considered an error and probably
indica tes a full disk.

For disk files, writing, always proceeds from the current file
pointer. On devices, bytes are directly sent to the device.
For files opened with the 0 _APPEND option, the file pointer is
not positioned to EOF by _write before writing the data.
Return value

_write returns the number of bytes written. In case of error, _write

returns -1 and sets the global variable errno to one of the
following:
EACCES
EBADF

Permission denied
Bad file number

See also

Iseek, _read, write

Example

#include
#include
#include
#include
#include
#include








int main(void)
void *buf;
int handle, bytes;
buf = malloc(200);
/* Create a file TEST.$$$ in the current directory and write 200
bytes to it. If TEST.$$$ already exists, overwrite. */
if ((handle = open("TEST.$$$", O_CREAT I O_WRONLY 10_BINARY,
S_IWRITE I S_IREAD)) == -1)
printf("Error Opening File\n");
exit(l) ;
if ((bytes = _write (handle, buf, 200))
printf("Write Failed.\n");
exit (1) ;

596

==

-1) {

Borland C++ Library Reference

_write

printf(lI_write: %d bytes written.\n",bytes);
return 0;

write
Function
Syntax

Remarl{s

Writes to a file.
#include 
int write(int handle, void *bllf, unsigned len);

write writes a buffer of data to the file or device named by the
given handle. handle is a file handle obtained from a creat, open,
dup, or dup2 call.

This function attempts to write len bytes from the buffer pointed
to by buf to the file associated with handle. Except when write is
used to write to a text file, the number of bytes written to the file
,will be no more than the number requested.
The maximum number of bytes that write can write is 65,534,
because 65,535 (OxFFFF) is the same as -1, which is the error
return indicator for write. On text files, when write sees a linefeed
(LF) character, it outputs aCR/LF pair.
If the number of bytes actually written is less than that requested,
the condition should be considered an error and probably
indicates a full disk. For disks or disk files, writing, always
proceeds from the current file pointer. For devices, bytes are sent
directly to the device. For files opened with the 0 _APPEND
option, the file pointer is positioned to EOF by write before
writing the data.
Return value

write returns the number of bytes written. A write to a text file
does not count generated carriage returns. In case of error, write

returns -1 and sets the global variable errna to one of the
following:
EACCES
EBADF
See also

Permission denied
Bad file number

creat, Iseek, open, read, _write

Chapter 2, The run-time library

597

598

Borland C++ Library Reference

c

H

A

p

T

E

R

3
Global variables
Borland C++ provides you with predefined global variables for many
common needs, such as dates, times, command-line arguments, and so on.
This chapter defines and describes them.

_8087
Function
Syntax
Declared in
Remarks

Coprocessor chip flag.
extern int _8087;
dos.h
The _8087 variable is set to a nonzero value (1, 2, or 3) if the startup code
autodetection logic detects a floating-point coprocessor (an 8087, 80287, or
80387, respectively). The _8087 variable is set to 0 otherwise.
The autodetection logic can be overridden by setting the 87 environment
variable to YES or NO. (The commands are SET 87=YES and SET 87=NO; it is
essential that there be no spaces before or after the equal sign.) 'In this
case, the _8087 variable will reflect the override.
Refer to Chapter 9, "Memory management," in the Programmer's Guide for
more information about the 87 environment variable.

Chapter 3, Global variables

599

Function
Syntax
Declared in

Keeps a count of command-line arguments.
extern int _argc;
dos.h

Remarks

_argc has the value of argc passed to main when the program starts.

Function

An array of pointers to command-line arguments.

Syntax
Declared in
Remarks

extern char *_argv[];
dos.h
_argv points to an array containing the original command-line arguments
(the elements of argv[J) passed to main when the program starts.

_ctype
Function
Syntax
Declared in
Remarks

An array of character attribute information.
extern char _ctype[]
ctype.h

_ctype is an array of character attribute information indexed by ASCII
value + 1. Each entry is a set of bits describing the character.
This array is used by isdigit, isprint, and so on.

daylight
Function
Syntax
Declared in
Remarks

600

Indicates whether daylight saving time adjustments will be made.
extern int daylight;
time.h

daylight is used by the time and date functions. It is set by the tzset, ftime,
and localtime functions to 1 for daylight saving time, a for standard time.

Borland C++ Library Reference

directvideo

directvideo
Function
Syntax
Declared in
Remarks

Flag that controls video output.
extern int directvideo;
conio.h

directvideo controls whether your program's console output (from cputs,
for example) goes directly to the video RAM (directvideo = 1) or goes via
ROM BIOS calls (directvideo = 0).
The default value is directvideo = 1 (console output goes directly to video
RAM). In order to use directvideo = I, your system's video hardware must
be identical to IBM display adapters. Setting directvideo = 0 allows your
console output to work on any system that is IBM BIOS-compatible.

environ
Function
Syntax
Declared in
Remarks

Accesses DOS environment variables.
extern char * environ[ ];
dos.h

environ is an array of pointers to strings; it is used to access and alter the
DOS environment variables. Each string is of the form
envvar = varvalue
where envvar is the name of an environment variable (such as PATH), and
varvalue is the string value to which envvar is set (such as C: \BIN;C: \DOS).
The string varvalue may be empty.
When a program begins execution, the DOS environment settings are
passed directly to the program. Note that env, the third argument to main,
is equal to the initial setting of environ.
The environ array can be accessed by getenv; however, the putenv function
. is the only routine that should be used to add, change or delete the environ
array entries. This is because modification can resize and relocate the
process environment array, but environ is automatically adjusted so that it
always points to the array ..

See also

getenv, putenv

Chapter 3, Global variables

601

errno, _doserrno, sys_errlist, sys_nerr

errno, _doserrno, sys_errlist, sys_nerr
Function
Syntax

Declared in
Remarks

Enable perror to print error messages.
extern int errno;
extern int _doserrno;
extern char * sys_errlist[ ];
extern int sys_nerr;
errno.h, stdlib.h (errno, _doserrno, sys_errlist, sys_nerr)
dos.h Cdoserrno)

errno, sys_errlist, and sys_nerr are used by perror to print error messages
when certain library routines fail to accomplish their appointed tasks.
_doserrno is a variable that maps many DOS error codes to errno; however,
perror does not use _doserrno directly.
_doserrno: When a DOS system call results in an error, _doserrno is set to
the actual DOS error code. errno is a parallel error variable inherited from
UNIX.

errno: When an error in a math or system call occurs, errno is set to
indicate the type of error. Sometimes errno and _doserrno are equivalent.
At other times, errno does not contain the actual DOS error code, which is
contained in _doserrno. Still other errors might occur that set only errno,
not _doserrno.
sys_errlist: To provide more control over message formatting, the array of
message strings is provided in sys_errlist. You can use errno as an index
into the array to find the string corresponding to the error number. The
string does not include any newline character.
sys_nerr: This variable is defined as the number of error message strings in
sys_errlist.
The following table gives mnemonics and their meanings for the values
stored in sys_errlist.

602

Borland C++ Library Reference

errno, _doserrno, sys_errlist, sys_nerr

Mnemonic

Meaning

E2BIG
EACCES
EBADF
ECONTR
ECURDIR
EDOM
EEXIST
EFAULT
EINVACC
EINVAL
EINVDAT
EINVDRV
EINVENV
EINVFMT
EINVFNC
EINVMEM
EMFILE
ENMFILE
ENODEV
ENOENT
ENOEXEC
ENOFILE
ENOMEM
ENOPATH
ENOTSAM
ERANGE
EXDEV
EZERO

Arg list too long
Permission denied
Bad file number
Memory blocks destroyed
Attempt to remove CurDir
Domain error
File already exists
Unknown error
Invalid access code
Invalid argument
Invalid data
Invalid drive specified
Invalid environment
Invalid format
Invalid function number
Invalid memory block address
Too many open files
No more files
No such device
No such file or directory
Exec format error
No such file or directory
Not enough memory
Path not found
Not same device
Result out of range
Cross-device link
Error 0

The following list gives mnemonics for the actual DOS error codes to
which _doserrno can be set. (This value of _doserrno mayor may not be
mapped (through errno) to an equivalent error message string in
sys_errlist.
Mnemonic

DOS error code

E2BIG
EACCES
EACCES
EACCES
EBADF
EFAULT
EINVAL
EINVAL
EM FILE
ENOENT
ENOEXEC

Bad environ
Access denied
Bad access
Is current dir
Bad handle
Reserved
Bad data
Bad function
Too many open
No such file or directory
Bad format

Chapter 3, Global variables

603

errno, _doserrno, sys_errlisf, sys_nerr

ENOMEM
ENOMEM
EN OM EM
EXDEV
EXDEV

Mcb destroyed
Out of memory
Bad block
Bad drive
Not same device

Refer to your DOS reference manual for more information about DOS
error return codes.
Example

#include 
#include 
extern char *sys_errlist[li
main( )
{

int i

= 0;

while (sys_errlist [i ++ 1) printf ( %s \n ", sys_errlist [i 1) i
return 0 i
II

Function

Syntax
Declared in
Remarks

Determines default file-translation mode.
extern int Jmode;
fcntl.h
Jmode determines in which mode (text or binary) files will be opened and
translated. The value of _fmode is a_TEXT by default, which specifies that
files will be read in text mode. If Jmode is set to a_BINARY, the files are
opened and read in binary mode. (a_TEXT and a_BINARY are defined in
fcntl.h.)

In text mode, on input carriage-return/linefeed (CR/LF) combinations are
translated to a single linefeed character (LF). On output, the reverse is
true: LF characters are translated to CR/LF combinations.
In binary mode, no such translation occurs.
You can override the default mode as set by Jmode by specifying a t (for
text mode) or b (for binary mode) in the argument type in the library
routines fopen, fdopen, and freopen. Also, in the routine open, the
argument access can include either a_BINARY or a_TEXT, which will
explicitly define the file being opened (given by the open pathname
argument) to be in either binary or text mode.

604

Borland C++ Library Reference

_heaplen

_heaplen
Function
Syntax
Declared in
Remarks

Holds the length of the near heap.
extern unsigned _heaplen;
dos.h

_heaplen specifies the size (in bytes) of the near heap in the small data
models (tiny, small, and medium). _heaplen does not exist in the large data
models (compact,large, and huge), as they do not have a near heap.
In the small and medium models, the data segment size is computed as
follows:
data segment [small/medium]

= global data

+ heap + stack

where the size of the stack can be adjusted with _stklen.
If _heaplen is set to 0, the program allocates 64K bytes for the data
segment, and the effective heap size is
64K - (global data + stack) bytes

By default, _heaplen equals 0, so you'll get a 64K data segment unless you
specify a particular _heaplen value.
In the tiny model, everything (including code) is in the same segment, so
the data segment computations are adjusted to include the code plus 256
bytes for the program segment prefix (PSP).
data segment [tiny]

=

256 + code + global data + heap + stack

If _heaplen equals 0 in the tiny model, the effective heap size is obtained by
subtracting the PSP, code, global data, and stack from 64K.

In the compact and large models, there is no near heap, and the stack is in
its own segment, so the data segment is simply
data segment [compact/large]

= global data

In the huge model, the stack is a separate segment, and each module has
its own data segment.
See also

_stklen

Chapter 3, Global variables

605

new_handler
Function
Syntax

Traps new allocation miscues.
typedef void (*pvf)O;
pvf _new_handler;

Or, as an alternative, you can set using the function seCnew_handler, like this:
pvf set_new_handler(pvf p);
Remarks

_new_handler contains a pointer to a function that takes no arguments and
returns void. If operator newO is unable to allocate the space required, it
will call the function pointed to by _new_handler; if that function returns it
will try the allocation again. By default, the function pointed to by
_new__handler simply terminates the application. The application can
replace this handler, however, with a function that can try to free up some
space. This is done by assigning directly to _new_handler or by calling the
function set_new_handler, which returns a pointer to the former handler.

_new_handler is provided primarily for compatibility with C++ version 1.2.
In most cases this functionality can be better provided by overloading
operator newO.

_osmajor, _osminor
Function
Syntax
Declared in
Remarks

Contain the major and minor DOS version numbers.
extern unsigned char _osmajor;
extern unsigned char _osminor;
dos.h
The Inajor and minor version numbers are available individually through

_osmajor and _osininor. _osmajor is the major version number, and _osminor
is the minor version number. For example, if you are running DOS version

3.2, _osmajor will be 3, and _osminor will be 20.
These variables can be useful when you want to write modules that will
run on DOS versions 2.x and 3.x. Some library routines behave differently
depending on the DOS version number, while others only work under
DOS 3.x. (For example, refer to _open, creatnew, and ioctl in the lookup
section of this Reference Guide.)

606

Borland C++ Library Reference

_ovrbuffer

_ovrbuffer
Function
Syntax
Declared in
Remarks

Change the size of the overlay buffer.
unsigned _ovrbuffer

=

size;

dos.h
The default overlay buffer size is twice the size of the largest overlay. This
is adequate for some applications. But imagine that a particular function
of a program is implemented through many modules, each of which is
overlaid. If the total size of those modules is larger than the overlay
buffer, a substantial amount of swapping will occur if the modules make
frequent calls to each other.
The solution is to increase the size of the overlay buffer so that enough
memory is available at any given time to contain all overlays that make
frequent calls to each other. You can do this by setting the _ovrbuffer global
variable to the required size in paragraphs. For example, to set the overlay
buffer to 128K, include the following statement in your code:
unsigned _ovrbuffer = Ox2000;

There is no general formula for determining the ideal overlay buffer size.
Borland's Turbo Profiler can help provide a suitable value.
See also

_OvrlnitEms, _OvrlnitExt

Function

Contains the segment address of .the program segment prefix (PSP) for the
current program.

Syntax
Declared in
Remarks

extern unsigned int _psp;
dos.h
The PSP is a DOS process descriptor; it contains initial DOS information
about the program.
Refer to the DOS Programmer's Reference Manual for more information on
the PSP.

Chapter 3, Global variables

607

_stklen

_stklen
Function
Syntax
Declared in
Remarks

Holds size of the stack.
extern unsigned _stklen;
dos.h

_stklen specifies the size of the stack for all six memory models. The
minimum stack size allowed is 128 words; if you give a smaller value,
_stklen is automatically adjusted to the minimum. The default stack size is
4K.

'

In the small and medium models, the data segment size is computed as
follows:
data segment [small,medium)

= global data

+

heap + stack

where the size of the heap can be adjusted with _heaplen.
In the tiny model, everything (including code) is in the same segment, so
the data segment computations are adjusted to include the code plus 256
bytes for the program segment prefix (PSP).
data segment [tiny)

= 256

+ code + global data + heap + stack

In the compact and large models, there is no near heap, and the stack is in
its own segment, so the data segment is simply
data segment [compact ,large)

='

global data

In the huge model, the stack is a separate segment, and each module has
its own data segment.
See also

_heaplen

Example

#include 
/* Set the stack size to be greater than the default. */
/* This declaration must go in the global data area. */

extern unsigned _stklen

= 54321U;

main( )
{

/* show the current stack length */
printf("The stack length is: %u\n", _stklen);
return 0;

608

Borland C++ Library Reference

timezone

timezone
Function
Syntax
Declared in
Remarks

Contains difference in seconds between local time and GMT.
extern long timezone;
time.h
timezone is used by the time-and-date functions.

This variable is calculated by the tzset function; it is assigned a long value
that is the difference, in seconds, between the current local time and
Greenwich mean time.

tzname
Function
Syntax
Declared in
Remarks

Array of pointers to time zone names.
extern char * tzname[2]
time.h
The global variable tzname is an array of pointers to strings containing
abbreviations for time zone names. tzname[O] points to a three-character
string with the value of the time zone name from the TZ environment
string. The global variable tzname[1] points to a three-character string
with the value of the daylight saving time zone name from the TZ
environment string. If no daylight saving name is present, tzname[l]
points to a null string.

_version
Function
Syntax
Declared in
Remarks

Contains the DOS version number.
extern unsigned int _version;
dos.h
_version contains the DOS version number, with the major version number
in the low byte and the minor version number in the high byte. (For DOS
version x.y, the x is the major version number, and y is the minor.)

Chapter 3, Global variables

609

_wscroll

_wscroll
Function
Syntax
Declared in
Remarks

Enables or disables scrolling in console I/O functions.
extern int _wscroll
conio.h

_wscroll is a console I/O flag. Its default value is 1. If you set _wscroll to 0,
scrolling is disabled. This can be useful for drawing along the edges of a
window without having your screen scroll.

610

Borland C++ Library Reference

A

p

p

E

N

x

D

A

Run-time library cross-reference
This appendix is an overview of the Borland C++ library routines
and include files.
In this chapter, we
• explain why you might want to obtain the source code for the
Borland C++ run:-time library
• list and describe the header files
• summarize the different categories of tasks performed by the
library routines
Borland C++ comes equipped with over 600 functions and macros
that you call from within your C and C++ programs to perform a
wide variety of tasks, including low- and high-level I/O, string
and file manipulation, memory allocation, process control, data
conversion, mathematical calculations, and much more. These
functions and macros, called library routines, are documented in
Chapter 2 of this book.
Borland C++'s routines are contained in the library files Cx.LIB,
MATHx.LIB, and GRAPHICS.LIB. Support for Windows
development is provided by CWx.LIB, MATHWx.LIB, and
OVERLAY.LIB. The letter x represents one of the six distinct
memory models supported by Borland. Each model except the
tiny model has its own library file and math file, containing
versions of the routines written for that particular model. (The
tiny model shares the small model's library and math files.) See

Appendix A, Run-time library cross-reference

611

the Programmer's Guide, Chapter 9, "Memory management" for
complete details.
In C++, you must always use
prototypes.

Borland C++ implements the ANSI C standard which, among
other things, allows (and strongly recommends) function
prototypes to be given for the routines in your C programs. All of
Borland C++'s library routines are declared with prototypes in
one or more header files.

Reasons to access the run-time library source code
There are several good reasons why you may wish to obtain the
source code for the run-time library routines:
• You may find that a particular function you want to write is
similar to, but not the same as, a Borland C++ function. With
access to the run-time library source code, you could tailor the
library function to your own needs, and avoid having to write a
separate function of your own.
• Sometimes, when you are debugging code, you may wish to
know more about the internals of a library function. Having the
source code to the run-time library would be of great help in
this situation.
• You may want to eliminate leading underscores on C symbols.
Access to the run-time library source code will let you eliminate
them.
• You can learn a lot from studying tight, professionally written
library source code.
For all these reasons, and more, you will want to have access to
the Borland C++ run-time library source code. Because Borland
believes strongly in the concept of "open architecture," we have
made the Borland C++ run-time library source code available for
licensing. All you have to do is fill out the order form distributed
with your Borland C++ package, include your payment, and we'll
ship you the Borland C++ run-time library source code.

The Borland C++ header files
c++ header files, and
header files defined by ANSI
C, are marked in the margin.

612

Header files, also called include files, provide function prototype
declarations for library functions. Data types and symbolic con-

Borland C++ Library Reference

stants used with the library functions are also defined in them,
along with global variables defined by Borland C++ and by the
library functions. The Borland C++ library follows the ANSI C
standard on names of header files and their contents.

ANSI C

alloc.h

Declares memory management functions (allocation, deallocation, etc.).

assert.h

Defines the assert debugging macro.

~bcd.h

Declares the C++ class bed and the overloaded
operators for bed and bed math functions.

bios.h

Declares various functions used in calling IBMPC ROM BIOS routines.

~ complex.h

Declares the C++ complex math functions.

conio.h

Declares various functions used in calling the
DOS console II 0 routines.

~

constrea.h

Declares C++ classes and methods to support
console output.

ANSI C

ctype.h

Contains information used by the character
classification 'and character conversion macros
(such as isalpha and toaseii).

dir.h

Contains structures, macros, and functions for
working with directories and path names.

direct.h

Defines structures, macros, and functions for
dealing with directories and path names.

dirent.h

Declares functions and structures for POSIX
directory operations.

dos.h

Defines various constants and gives declarations
needed for DOS and 8086-specific calls.

errno.h

Defines constant mnemonics for the error codes.

fcntl.h

Defines symbolic constants used in connection
with the library routine open.

ANSI C

float.h

Contains parameters for floating-point routines.

~

fstream.h

Declares the C++ stream classes that support file
input and output.

ANSI C

~ generic.h

graphics.h

Appendix A, Run-time library cross-reference

Contains macros for generic class declarations.
Declares prototypes for the graphics functions.

613

io.h

Contains structures and declarations for low-level
input/output routines.

~iomanip.h

Declares the C++ streams I/O manipulators and
contains macros for creating parameterized
mani pula tors.

~

iostream.h

Declares the basic C++ (version 2.0) streams (I/O)
routines.

ANSI C

limits.h

Contains environmental parameters, information
about compile-time limitations, and ranges of
integral quantities.

ANSI C

locale.h

Declares functions that provide country- and
language-specific information.

sys \locking.h

Definitions for mode parameter of locking
function.

malloc.h

Memory management functions and variables.

math.h

Declares prototypes for the math functions and
math error handlers.

mem.h

Declares the memory-manipulation functions.
(Many of these are also defined in string.h.)

memory.h

Memory manipulation functions.

ANSI C

~new.h

ANSI C

ANSI C

Access to operator new and newhandler.

process.h

Contains structures and declarations for the
spawn ... and exec ... functions.

search.h

Declares functions for searching and sorting.

setjmp.h

Defines a type jmp_buf used by the longjrnp and
setjrnp functions and declares the functions
longjrnp and setjrnp.

share.h

Defines parameters used in functions that make
use of file-sharing.

signal.h

Defines constants and declarations for use by the
signal and raise functions.

614

ANSI C

stdarg.h

Defines macros used for reading the argument list
in functiQns declared to accept a variable number
of arguments (such as vprintf, vscanf, etc.).

ANSI C

stddef.h

Defines several common data types and macros.

Borland C++ Library Reference

ANSI C

stdio.h

Defines types and macros needed for the
Standard I/O Package defined in Kernighan and
Ritchie and extended under UNIX System V.
Defines the standard I/O predefined streams
stdin, stdout, stdprn, and stderr, and declares
streanl-levell/O routines.

~

stdiostr.h

Declares the C++ (version 2.0) stream classes for
use with stdio FILE structures;

ANSI C

stdlib.h

Declares several commonly used routines:
conversion routines, search/ sort routines, and
other miscellany.

ANSI C

string.h

Declares several string-manipulation and
memory-manipulation routines.

~ strstrea.h

ANSI C

Declares the C++ stream classes for use with byte
arrays in memory.

sys\stat.h

Defines symbolic constants used for opening and
creating files.

time.h

Defines a structure filled in by the timeconversion routines asctime, localtime, and
gmtime, and a type used by the routines ctime,
difftime, gmtime, localtime, and stime; also
provides prototypes for these routines.

sys \ timeb.h

Declares the function ftime and the struchue
timeb that ftime returns.

sys \ types.h

Declares the type time_t used with time functions.

utime.h

Declares the utime function and the utimbuf
struct that it returns.

values.h

Defines important constants, including machine
dependencies; provided for UNIX System V
compatibility.

varargs.h

Definitions for accessing parameters in functions
that accept a variable number of arguments.
Provided for UNIX compatibility; you should use
stdarg.h for new code.

Appendix A, Run-time library cross-reference

615

Library routines by category
The Borland C++ library routines perform a variety of tasks. In
this section, we list the routines, along with the include files in
which they are declared, under several general categories of task
performed. Chapter 2 contains complete information about the
functions listed below.

Classification
routines

These routines classify ASCII characters as letters, control
characters, punctuation, uppercase, etc.
isalnum
isalpha
isaseii
isentrl

Conversion
routines

isdigit
isgraph
islower
isprint

(stdlib.h)
(stdlib.h)
(stdlib.h)
(stdlib.h)
(stdlib.h)
(stdlib.h)
(stdlib.h)

Itoa
_strdate
_strtime
strtod
strtol
_strtold
strtoul

ispunct
isspaee
isupper
isxdigit

(ctype.h)
(ctype.h)
(ctype.h)
(ctype.h)

(stdlib.h)
(time. h)
(time.h)
(stdlib.h)
(stdlib.h)
(stdlib.h)
(stdlib.h)

toaseii
_tolower
tolower
_toupper
toupper
ultoa

(ctype.h)
(ctype.h)
(ctype.h)
(ctype.h)
(ctype.h)
(stdlib.h)

These routines manipulate directories and path names.
(dir.h)
ehdir
(direct.h)
ehdrive
(dirent.h)
elosedir
(dos.h)
- dos_findfirst
(dos.h)
dos_findnext
_dos_getdiskfree (dos.h)
(dos.h)
_dos_getdrive
(dos.h)
dos_setdrive
(dir.h)
findfirst
(dir.h)
findnext
(dir.h)
fnmerge
(dir.h)
fnsplit

616

(ctype.h)
(ctype.h)
(ctype.h)
(ctype.h)

These routines convert characters and strings from alpha to
different numeric representations (floating-point, integers, longs)
and vice versa, and from uppercase to lowercase and vice versa.
atof
atoi
atol
eevt
fevt
gcvt
itoa

Directory control
routines

(ctype.h)
(ctype.h)
(ctype.h)
(ctype.h)

_fullpath
geteurdir
getewd
_getdewd
getdisk
_getdrive
_makepath
mkdir
mktemp
opendir
readdir
rewinddir

(stdlib.h)
(dir.h)
(dir.h)
(direct.h)
(dir.h)
(direct.h)
(stdlib.h)
(dir.h)
(dir.h)
(dirent.h)
(dirent.h)
(dirent.h)

Borland C++ Library Reference

(dir.h)
(stdlib.h)
(dir.h)

rmdir
_searchenv
search path

Diagnostic
routines

setdisk
_splitpath

(dir.h)
(stdlib.h)

These routines provide built-in troubleshooting capability.
assert
matherr
_matherrl
perror

(assert.h)
(math.h)
(math.h)
(errno.h)

Graphics routines
These routines let you create onscreen graphics with text.
arc
bar
bar3d
circle
cleardevice
clearviewport
closegraph
detectgraph
drawpoly
ellipse
fillellipse

fill poly
floodfill
getarccoords
getaspectratio
getbkcolor
getcolor
getdefaultpalette
getdrivername
getfill pattern
getfillsettings
getgraphmode
getimage
getJ inesetti ng s
getmaxcolor
getmaxmode
getmaxx
getmaxy
getmodename
getmoderange
getpalette

Appendix A, Run-time library cross-reference

(graphics.h)
(graphics.h)
(graphics.h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics.h)
(graphics.h)
(graphics.h)
(graphics.h)
(graphics.h)
(graphics.h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics.h)
(gra p hics.h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics.h)
(graphics.h)
(gra p hics.h)
(graphics.h)
(graphics.h)
(graphics. h)

getpalettesize
getpixel
gettextsettings
getviewsettings
getx
gety
graphdefaults
grapherrormsg
_graphfreemem
_graphgetmem
graphresult
imagesize
initgraph
installuserdriver
installuserfont
line
Iinerel
Iineto
moverel
moveto
outtext
outtextxy
pieslice
putimage
putpixel
rectangle
reg isterbg id river
registerbgifont
restorecrtmode
sector
setactivepage

(graphics.h)
(graphics.h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics.h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics.h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics. h)
(graphics.h)
(gra p hies. h)
(graphics. h)
(graphics.h)
(graphics.h)
(graphics.h)
(graphics.h)

617

setallpalette
setaspectratio
setbkcolor
setcolor
setcursortype
setfi II pattern
setfillstyle
setgraphbufsize
setgraphmode
setlinestyle

(graphics. h)
(graphics. h)
(graphics. h)
(graphics.h)
(conio.h)
(graphics. h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics. h)

setpalette
setrgbpalette
settextjustify
settextstyle
setusercharsize
setviewport
setvisualpage
setwritemode
textheight
textwidth

(graphics. h)
(graphics. h)
(graphics.h)
(graphics. h)
(graphics.h)
(graphics. h)
(graphics. h)
(graphics. h)
(graphics. h)
(graphics.h)

Inline routines
These routines have inline versions. The compiler will generate
code for the inline versions when you use #pragma intrinsic or if
you specify program optimization. See the User's Guide, Appendix
A, "The Optimizer" for more details.
fabs
memchr
memcmp
memcpy
- rotl
- rotr
stpcpy
strcat

Input/output
routines

strcmp
strcpy
strlen
strncat
strncmp
strncpy
strnset
strset

(string.h)
(string.h)
(string.h)
(string. h)
(string.h)
(string.h)
(string.h)
(string.h)

These routines provide stream-level and DOS-level I/O
capability.
access
cgets
- chmod
chmod
chsize
clearerr
- close
close
cprintf
cputs
- creat
creat
creatnew
creattemp
cscanf
- dos_close

618

(math.h)
(mem.h)
(mem.h)
(mem.h)
(stdlib.h)
(stdlib.h)
(string.h)
(string.h)

(io.h)
(conio.h)
(io.h)
(io.h)
(io.h)
(stdio.h)
(io.h)
(io.h)
(conio.h)
(conio.h)
(io.h)
(io.h)
(io.h)
(io.h)
(conio.h)
(dos.h)

(dos.h)
(dos.h)
_dos_getfileattr (dos.h)
(dos.h)
_dos_getftime
(dos.h)
_dos_open
(dos.h)
- dos_read
(dos.h)
dos_setfileattr
(dos.h)
- dos_setftime
(dos.h)
- dos_write
(io.h)
dup
(io.h)
dup2
(io.h)
eof
(stdio.h)
fclose
(stdio.h)
fcloseall
(stdio.h)
fdopen
(stdio.h)
feof
- dos_creat
- dos_creatnew

Borland C++ Library Reference

ferror
fflush
fgetc
fgetchar
fgetpos
fgets
filelength
fileno
flushall
fopen
fprintf
fputc
fputchar
fputs
fread
freopen
fscanf
fseek
fsetpos
_fsopen
fstat
ftell
fwrite
getc
getch
getchar
getche
getftime
getpass
gets
getw
ioctl
isatty
kbhit
lock
locking
Iseek
_open
open
perror

(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(io.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(sys \stat.h)
(stdio.h)
(stdio.h)
(stdio.h)
(conio.h)
(stdio.h)
(conio.h)
(io.h)
(conio.h)
(stdio.h)
(stdio.h)
(io.h)
(io.h)
(conio.h)
(io.h)
(io.h)
(io.h)
(io.h)
(io.h)
(stdio.h)

printf
putc
putch
putchar
puts
putw
read
read
remove
rename
rewind
rmtmp
scanf
setbuf
setcu rsortype
setftime
setmode
setvbuf
sopen
sprintf
sscanf
stat
- strerror
strerror
tell
tempnam
tmpfile
tmpnam
umask
ungetc
ungetch
unlock
utime
vfprintf
vfscanf
vprintf
vscanf
vsprintf
vsscanf
- write

(stdio.h)
(stdio.h)
(conio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(io.h)
(io.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(conio.h)
(io.h)
(io.h)
(stdio.h)
(io.h)
(stdio.h)
(stdio.h)
(sys \stat.h)
(string. h, stdio.h)
(stdio.h)
(io.h)
(stdio.h)
(stdio.h)
(stdio.h)
(io.h)
(stdio.h)
(conio.h)
(io.h)
(utime.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(stdio.h)
(io.h)
(io.h)

Interface routines
(DOS, 8086, BIOS) These routines provide DOS, BIOS and machine-specific
capabilities.
absread
abswrite
bdos

Appendix A, Run-time library cross-reference

(dos.h)
(dos.h)
(dos.h)

bdosptr
bioscom
- bios_disk

(dos.h)
(bios.h)
(bios.h)

619

620

Borland c++ Library Reference

strcpy
strcspn
strdup
strerror
stricmp
strcmpi
strlen
strlwr
strncat
strncmp
strncmpi
strncpy
strnicmp

(string.h)
(string.h)
(string. h)
(string. h)
(string.h)
(string.h)
(string.h)
(string.h)
(string.h)
(string.h)
(string. h)
(string.h)
(string.h)

strnset
strpbrk
strrchr
strrev
strset
strspn
strstr
strtok
strupr
strxfrm
wcstombs
wctomb

(string. h)
(string. h)
(string.h)
(string.h) .
(string.h)
(string.h)
(string.h)
(string.h)
(string.h)
(string.h)
(stdlib.h)
(stdlib.h)

Math routines
These routines perform mathematical calculations and
conversions.
abs
acos
acosl
arg
asin
asinl
atan
atanl
atan2
atan21
atof
atoi
atol
- atold
bcd
cabs
cabsl
ceil
ceill
- clear87
complex
conj
control87
cos
cos I
cosh
coshl
div
ecvt
exp

(complex. h, stdlib.h)
(complex.h, math.h)
(math.h)
(complex.h)
(complex. h, math.h)
(math.h)
(complex.h, math.h)
(math.h)
(complex.h, math.h)
(math.h)
(stdlib.h, math.h)
(stdlib.h)
(stdlib.h)
(math.h)
(bcd.h)
(math.h)
(math.h)
(math.h)
(math.h)
(float.h)
(complex. h)
(complex.h)
(float.h)
(complex. h, math. h)
(math.h)
(complex. h, math. h)
(math. h)
(math.h)
(stdlib.h)
(complex.h, math.h)

Appendix A, Run-time library cross-reference

expl
fabs
fabsl
fcvt
floor
floorl
fmod
fmodl
_fpreset
frexp
frexpl
gcvt
hypot
hypotl
imag
itoa
labs
Idexp
Idexpl
Idiv
log
logl
log10
log101
- Irotl
- Irotr
Itoa
matherr
- matherrl
modf

(math.h)
(math.h)
(math. h)
(stdlib.h)
(math.h)
(math.h)
(math.h)
(math.h)
(float.h)
(math.h)
(math.h)
(stdlib.h)
(math.h)
(math. h)
(complex. h)
(stdlib.h)
(stdlib.h)
(math.h)
(math. h)
(math.h)
(complex. h, math.h)
(math.h)
(complex. h, math. h)
(math.h)
(stdlib.h)
(stdlib.h)
(stdlib.h)
(math.h)
(math.h)
(math.h)

621

These routines provide dynamic memory allocation in the smalldata and large-data models.
(malloc.h)
(dos.h)
(bios.h)
(alloc.h)
(alloc.h,
stdlib.h)
corel eft
(alloc.h,
stdlib.h)
(dos.h)
- dos_allocmem
(dos.h)
- dos_freemem
(dos.h)
dos_setblock
(alloc.h)
farcalloc
(alloc.h)
farcoreleft
(alloc.h)
farfree
(alloc.h)
farheapcheck
(alloc.h)
farheapcheckfree
farheapchecknode (alloc.h)
alloca
allocmem
- bios_memsize
brk
calloc

Miscellaneous
routines

heapcheck
heapcheckfree
heapchecknode
heapwalk
malloc
realloc
sbrk
setblock
seCnew_handler

(alloc.h)
(alloc.h)
(alloc.h)
(alloc.h)
(alloc.h,
stdlib.h)
(alloc.h)
(alloc.h)
(alloc.h)
(alloc.h)
(alloc.h,
stdlib.h)
(alloc.h,
stdlib.h)
(alloc.h)
(dos.h)
(new. h)

These routines provide nonlocal goto capabilities, sound effects,
and locale.
delay
localeconv
longjmp
nosound

622

farheapfillfree
farheapwalk
farmalloc
farrealloc
free

(dos.h)
(locale.h)
(setjmp.h)
(dos.h)

setjmp
setlocale
sound

(setjmp.h)
(locale.h)
(dos.h)

Borland C++ Library Reference

Process control
routines

These routines invoke and terminate new processes from within
another.
abort
_c_exit
- cexit
execl
execle
execlp
execlpe
execv

Text window
display routines

(process.h)
(process.h)
(process. h)
(process.h)
(process.h)
(process.h)
(process.h)
(process. h)

(process. h)
(process.h)
(process. h)
(process. h)
(process. h)
(process. h)
(signal.h)
(signal.h)

spawnl
spawnle
spawnlp
spawnlpe
spawnv
spawnve
spawnvp
spawnvpe

(process. h)
(process.h)
(process. h)
(process.h)
(process. h)
(process.h)
(process.h)
(process.h)

These routines output text to the screen.
clreol
clrscr
delline
gettext
gettextinfo
gotoxy
highvideo
insline
lowvideo
movetext

Time and date
routines

execve
execvp
execvpe
- exit
exit
getpid
raise
signal

(conio.h)
(conio.h)
(conio.h)
(conio.h)
(ronio.h)
(conio.h)
(conio.h)
(conio.h)
(conio.h)
(conio.h)

normvideo
puttext
setcursortype
textattr
textbackground
textcolor
textmode
wherex
wherey
window

(conio.h)
(conio.h)
(conio.h)
(conio.h)
(ronio.h)
(conio.h)
(conio.h)
(conio.h)
(conio.h)
(conio.h)

These are time conversion and time manipulation routines.
asctime
_bios_timeofday
ctime
difftime
_dos_getdate
_dos_gettime
- dos_setdate
- dos_settime
dostounix
ftime
getdate

Appendix A, Run-time library cross-reference

(time.h)
(bios.h)
(time.h)
(time.h)
(dos.h)
(dos.h)
(dos.h)
(dos.h)
(dos.h)
(sys \ timeb.h)
(dos.h)

gettime
gmtime
localtime
mktime
setdate
settime
stime
strftime
time
tzset
unixtodos

(dos.h)
(time.h)
(time.h)
(time.h)
(dos.h)
(dos.h)
(time.h)
(time.h)
(time.h)
(time.h)
(dos.h)

623

Variable
argument list
routines

These routines are for use when accessing variable argument lists
(such as with vprintf, etc).
va_arg (stdarg.h)
va_end (stdarg.h)
va_start (stdarg.h)

624

Borland C++ Library Reference

N

_8087 (global variable) 599
8086 processor
interrupt vectors 123, 124,261
interrupts 307, 308, 311
80x87 coprocessors See numeric coprocessors
80x86 processors
functions (list) 619
_atold (function) 27
_close (function) 82
_disable (function) 108
_dos_freemem (function) 191
_dos~etdate (function) 219
_dos_keep (function) 325
_dos_open (function) 375
_dos_setdate (function) 219
_dos_setdrive (function) 118
_dos_setfileattr (function) 119
_dos_setftime (function) 120
_dos_setttime (function) 121
_enable (function) 108
_fsopen (function) 198
_fullpath (function) 205
_HEAPEMPTY 291
_HEAPEND 290,291
_HEAPOK 290, 291
_matherrl (function) 352
_write (function) 595
Oxll BIOS interrupt 44, 45
Ox12 BIOS interrupt 51, 52
Ox13 BIOS interrupt 41
Ox16 BIOS interrupt 47, 49
Oxl7 BIOS interrupt 52, 53
Oxl9 DOS function 118, 224
Ox31 DOS function 325
Ox40 DOS function 125
Ox21 DOS interrupt 309, 310
Ox23 DOS interrupt 102,284
Ox24 DOS interrupt 278, 281
Ox25 DOS interrupt 12

Index

E

D

x

Ox26 DOS interrupt 14
Ox27 DOS system call 419
Ox28 DOS system call 420
Ox29 DOS system call 387
Ox33 DOS system call 214, 467
Ox44 DOS system call 313
Ox48 DOS system call 18
Ox59 DOS system call 113
Ox62 DOS system call 254
OxlA BIOS interrupt 57, 58
Ox5B DOS function 112
Ox4E DOS function 114
Ox4E DOS system call 172
Ox3F DOS function 424

,A
abnormal program termination 417
abort (function) 11
abs (function) 11
absolute disk sectors 12, 14
absolute value See also values
complex numbers 62
square 373
floating-point numbers 145
integers 11
long 328
absread (function) 12
abswrite (function) 14
access
DOS system calls 34, 35
files See files, access
flags 378, 510
memory (DMA) 43, 44, 46
modes
changing 72, 74, 119
program
signal types 417
invalid 417

625

read/write 74,201
files 15, 97, 378, 510
permission 378
access (function) 14
access permission mask 575
acos (function) 15
acosl (function) 15
active page 500
setting 457
adapters
graphics 105
monochrome 20, 392
address segment, of far pointer 184, 365
addresses
memory See memory, addresses
passed to __emit__ 135
alloc.h (header file) 613
alloca (function) 16
allocating memory See memory allocation
allocmem (function) 18
alphabetic ASCII codes, checking for 315
alphanumeric ASCII codes, checking for 314
angles (complex numbers) 21
arc (function) 19
coordinates 209
arc cosine 15
arc sine 23
arc tangent 25, 26
arcs, elliptical 133
arg (function) 21
_argc (global variable) 600
argc (argument to main) 3
ARGS.EXE 4
argument list, variable 582
conversion specifications and 398
arguments
command line, passing to main 3, 600
wildcards and 5
variable number of
functions (list) 624
_argv (global variable) 600
argv (argument to main) 3
arrays
of character, attribute information 600
searching 60, 330
of time zone names 609

626

ASCII codes
alphabetic 315
lowercase 319
uppercase 322
alphanumeric 314
control or delete 317
converting
characters to 569
date and time to 22
digits
o to 9318
hexadecimal 323
functions
list 616
integer value classification See macros,
character classification
low 316
lowercase alphabetic 319
printing characters 319, 320
punctuation characters 321
uppercase alphabetic 322
whitespace 321
asctime (function) 22
asin (function) 23
asinl (function) 23
aspect ratio
correcting 461
getting 210
assert (function) 24
assert.h (header file) 613
assertion 24
assignment suppression
format specifiers 444, 445, 449, 450
AT&T 6300 PC
detecting presence of 105
atan2 (function) 26
atan (function) 25
atan21 (function) 26
atanl (function) 25
atexit (function) 26
atof (function) 27
atoi (function) 29
atol (function) 30
attribute bits 378, 511
attribute word 73, 100, 112
attributes
characters, arrays of 600

Borland C++ Library Reference

files See files, attributes
text 558, 559, 560
autodetection (graphics drivers) 104,225,296
303
'
AX register
hardware error handlers and 278

B
background color See colors and palettes
banker's rounding 34
bar (function) 30
bar3d (function) 32
bars
three-dimensional 32
two-dimensional 30
base 10 logarithm 341
baud rate 37,55
BCD (binary coded decimal) numbers 33, 428
bcd (function) 33
.
bcd.h (header file) 613
bdos (function) 34
bdosptr (function) 35
beeps 374, 512
BGI See Borland Graphics Interface (BGl)
BGIOBJ (graphics converter) 296
stroked fonts and 493
binary coded decimal floating-point numbers
See BCD (binary coded decimal) numbers
binary files See also files
_fsopen and 199
creat and 97
creattemp and 99
fdopen and 160
fopen and 183
freopen and 193
opening 160, 183, 193, 199
and translating 604
setting 484
temporary
naming 556, 568
opening 567
binary mode See binary files
binary search 60
BIOS

functions (list) 619
interrupts See also interrupts
Ox11 44,45

Index

Ox12 51, 52
Ox1341
Ox16 47, 49
Ox1752,53
Ox1A 57, 58
timer 57, 58
_bios_disk (function) 38
_bios_equiplist (function) 45
bios.h (header file) 613
_bios_keybrd (function) 49
_bios_memsize (function) 51
_bios_printer (function) 53
_bios_serialcom (function) 55
_bios_timeofday (function) 58
bioscom (function) 36
biosdisk (function) 41
biosequip (function) 44
bioskey (function) 47
biosmemory (function) 51
biosprint (function) 52
bios time (function) 57
bit images
saving 236
storage requirements 294
writing to screen 410
bit-mapped fonts 493
bit mask 201
bit rotation
long integer 344, 345
unsigned integer 441, 442
bits
attribute 95, 100, 112,378,511
status (communications) 37, 56
stop (communications) 37, 55
blink-enable bit 558
block operations See editing, block operations
blocks, memory See memory blocks
Borland C++
functions
licensing 612
Borland Graphics Interface (BGl)
fonts 432
new 305
device driver table 303
graphics drivers and 276, 295,431

627

BP register
hard ware error handlers and 278
break value 60, 443
brk (function) '59
bsearch (function) 60
buffers
file 496
graphics, internal 475
keyboard, pushing character to 577
overlays
default size 607
streams and 466, 496
clearing 177
flushing 157
writing 177
system-allocated, freeing 157
bytes
copying 368
reading from hardware ports 299,301
returning from memory 389
status (disk drives) 40, 42
storing in memory 394
swapping 552

c
C++
binary coded decimal 33, 428
complex numbers See complex numbers
memory allocation 606
exit (functions) 65
cabs (function) 62
cabsl (function) 62
calendar format (time) 366
calloc (function) 63
carry flag 307, 308, 309, 310
ceil (function) 65
ceill (function) 65
exit (functions) 66
CGA See Color Graphics Adapter (CGA)
cgets (function) 67
_chain_intr (function) 69
channels (device) 313
characters
alphabetic 315
alphanumeric 314
array, global variable 600

628

attributes 558, 559, 560
blinking 558
classifying See macros, character
classification
color, setting 558, 560
control or delete 317
converting to ASCII 569
device 317
digits (0 to 9) 318
displaying 400, 407, 446
floating-point numbers and 27
format specifiers See format specifiers,
characters
functions (list) 616
hexadecimal digits 323
intensity
high 291
low 343
normal 374
low ASCII 316
lowercase 570
checking for 319
converting to 569, 570
magnification, user-defined 495
manipulating
header file 613
newline 413
printing 319, 320
punctuation 321
pushing
to input stream 576
to keyboard buffer 577
reading 446
from console 67
from keyboard 214, 216
from streams 164,213,215
stdin 165
scanning in strings 529, 541, 542
segment subset 544
searching
in block 358
in string 524
size 493, 562, 565
uppercase
checking for 322
converting to 571, 572
whitespace 321

Borland C++ Library Reference

writing
to screen 407
to streams 188, 406, 407
chdir (function) 70
_chdrive (function) 71
child process 137,513, See also processes
child processes
functions (list) 623
header file 614
_chmod (function) 72
chmod (function) 74
.CHR files 305, 493
chsize (function) 75
circle (function) 76
circles, drawing 76
_clear87 (function) 77
cleardevice (function) 78
clearerr (function) 79
clearing
screens 78, 86, 477
to end of line 85
clearviewport (function) 80
clock (function) 82
close (function) 82
closedir (function) 83
closegraph (function) 84
closing files See files, closing
clreol (function) 85
clrscr (function) 86
Color /Graphics Adapter (CGA) See also
graphics; screens
colors See colors and palettes
detecting presence of 105
palettes 459, See also colors and palettes
problems 20, 392
colors and palettes 270, 297, 458, See also
graphics
background color 212, 462
setting 270, 462
text 558, 559
CGA 459
changing 458, 486
color table 459, 462, 487
default 221
definition structure 221
drawing 216, 392, 468, 469
setting 270

Index

EGA 459
fill colors 169, 175
information on 231
pie slices 392, 455
setting 473
fill patterns 169, 170, 175
defining 230, 232
by user 472, 473
information on 231
pie slices 392, 455
predefined 232
setting to default 270
fill style 270
filling graphics 175
IBM 8514 488
information on 248
returning 221
maximum value 240
pixels 252, 412
problems with 20,392
rectangle 430
setting 468, 488
background 462
character 558, 560
drawing 270
size of 250
VGA 459, 488
COMMAND.COM 553
command line
arguments, passing to main 600
errors See errors
command-line compiler
Pascal calling conventions, option (-p) 7
communica tions
parity 37, 55
ports 36, 55
checking for 44, 46, 317
protocol settings 37, 55
RS-232 36, 55
stop bits 37, 55
compact memory model See memory models
comparing
strings See strings, comparing
two values 354, 363
comparison function, user-defined 416
compile-time limitations
header file 614

629

compiler, command-line See command-line
compiler
complex (function) 86
complex.h (header file) 613
complex numbers See also numbers;
trigonometric functions
absolute value 62
square of 373
angles 21
conjugate of 87
constructor for 86
functions (list) 621
header file 613
imaginary portion 293
polar function 394
real portion 428
COMSPEC environment variable 553
concatenated strings 524, 536
conditions, testing 24
conio.h (header file) 613
conj (function) 87
conjugate (complex numbers) 87
console See also hardware
checking for 317
header file 613
output flag 601
reading and formatting
characters 67
input 100
constants
DOS
header file 613
open function
header file 613
symbolic
header file 615
UNIX compatible
header file 615
constrea.h (header file) 613
constructor (complex numbers) 86
_control87 (function) 88
control-break
handler 102
interrupt 284
returning 214
setting 467
software signal 417

630

control characters, checking for 317
control word, floating point 88
conversion
binary coded decimal 33, 428
da te and time 22
DOS to UNIX format 126
to string 101
to calendar format 366
to Greenwich mean time 268
to structure 335
UNIX to DOS format 578
double
strings to 546
to integer and fraction 367
to mantissa and exponent 194
floating point
strings to 27
to string 132, 158, 207
format specifiers 399, 400, 403
integer
to ASCII 569
strings to 29
to string 323
long double
strings to 546
long integer
strings to 30, 548, 550
to string 348, 574
lowercase to uppercase 551, 571, 572
specifications (printf) 398
'
strings
date and time to 101
to double 546
to floating point 27
integers to 323
to integer 29
to long double 546
to long integer 30, 548, 550
to unsigned long integer 550
unsigned long integer
strings to 550
to string 574
uppercase to lowercase 535, 569, 570
conversions
date and time
header file 615
functions (list) 616

Borland C++ Library Reference

header file 615
coordinates
arc, returning 209
current position 266, 267,499
cursor position 269, 593, 594
screens
maximum 243, 244
text mode 255
x-coordinate 243, 266
y-coordinate 244, 267
coprocessors See numeric coprocessors
coreleft (function) 89
co routines
overlays and 342, 479
task states and 342, 479
correction factor of aspect ratio 461
cos (function) 90
cosh (function) 91
coshl (function) 91
cosine 90
hyperbolic 91
inverse 16
cosl (function) 90
country (function) 92
country-dependent data 92, 334, 483
CP See current position (graphics)
cprintf (function) 93
format specifiers 398
cputs (function) 94
creat (function) 96
_creat (function) 95
_dos_creat (function) 95
creatnew (function) 98
creattemp (function) 99
cscanf (function) 100
format specifiers 443
ctime (function) 101
ctrlbrk (function) 102
_ctype (global variable) 600
ctype.h (header file) 613
currency symbols 92, 334, 483
current drive number 224
current position (graphics) 270
coordinates 266, 267, 499
justified text and 490
lines and 331, 332, 333
moving 369, 372

Index

cursor
appearance, selecting 470
position in text window 269
returning 593, 594

D
data
conversion See conversion
country-dependent, supporting 92, 334, 483
moving 368
reading from streams 189, 195, 586, 591
stdin 443, 588
returning from current environment 227
security 251
writing to current environment 408
data bits (communications) 37, 55
data segment 64, 351, 605
allocation 59
changing 442
data types
defining
header file 614
time_t
header file 615
date
functions (list) 623
date and time conversions See conversion, date
and time
dates See also time
file 120, 233
global variable 600
international formats 92
system 22, 101, 204, 268, 335
converting from DOS to UNIX 126
converting from UNIX to DOS 578
getting 219
setting 219, 522
daylight (global variable) 600
setting value of 572
daylight saving time See also time zones
adjustments 102,600
setting 572
de_exterror 113
deallocating memory See memory, freeing
debugging
macros
header file 613

631

delay (function) 103
deletion
characters, checking for 317
directories 439
file 434, 579
line 85, 104
delline (function) 104
detectgraph (function) 104
detection
graphics adapter 105, 225
graphics drivers 296
device See also hardware
channels 313
character 317
drivers See also graphics drivers
BGI303
DOS 314
vendor-added 303
errors 278, 282
type checking 316
DI register
hardware error handlers and 278
difftime (function) 107
dir.h (header file) 613
direct.h (header file) 613
direct memory access (DMA)
checking for presence of 43, 44, 46
directories
creating 363
current 138,514
changing 70
returning 218, 220
deleting 439
functions (list) 616
h.eader file 613
path See paths
searching 83,114,116,171,174,379,427,
438,452,453
directory stream
closing 83
opening 379
reading 427
rewinding 438
directvideo (global variable) 601
dirent.h (header file) 613
disable (function) 108
disk access errors See errors

632

disk drives See also hardware
checking for presence of 44, 46
current number 118, 224
functions 41
I/O operations 41
setting 71
status byte 40, 42
disk operating system See DOS
disk sectors
reading 12, 39, 41
writing 14,40,41
disk transfer address (DTA)
DOS 418
returning 226
setting 471
random blocks and 418
disks
errors 278, 282, See also errors
operations 41, 42
space available 117, 223
writing to, verification 262, 498
div (function) 110
division, integers 110, 329
DMA See direct memory access (DMA)
DOS
commands 553
date and time 219
converting to UNIX format 126
converting UNIX to 578
setting 259, 522
device drivers 314
disk transfer address See disk transfer
address (DTA)
environment
adding data to 408
returning data from 227
variables 138,514
accessing 601
error codes 602, 603
error information, extended 113
file attributes 72,95, 100, 112, 119
search 114, 172
shared 376
file-sharing mechanisms See files, sharing
functions
Ox19 118,224
Ox31325

Borland C++ Library Reference

Ox40 125
Ox5B 112
Ox4E 114
Ox3F 424
functions (list) 619
header file 613
interrupts
Ox21 309,310
Ox23 102, 278, 284
Ox24 278, 281
Ox25 12
Ox26 14
functions 123, 124,261
handlers 278, 282
interface 309, 310
path, searching for file in 452, 453
search algorithm 137
system calls 279, 282, 423
Ox27419
0x28420

Ox29387
Ox33 214,467
Ox44313
Ox48 18
Ox59 113
Ox62254
Ox4E 172
accessing 34, 35
memory models and 34, 35
verify flag 262, 498
version numbers 606, 609
_dos_close (function) 111
_dos_creatnew (function) 112
_dos_find first (function) 114
_dosjindnext (function) 116
_dos~etdiskfree (function) 117
_dos~etdrive (function) 118
_dos_getfileattr (function) 119
_dos~etftime (function) 120
_dos~ettime (function) 121
_dos~etvect (function) 123
dos.h (header file) 613
_dos_setvect (function) 124
_dos_write (function) 125
_doserrno (global variable) 602
dosexterr (function) 113
dostounix (function) 126

Index

double (data type) See floating point, double
drawing color See colors and palettes
draw poly (function) 127
drivers, graphics See graphics drivers
drives See disk drives
DTA See disk transfer address (DTA)
dup2 (function) 130
dup (function) 129
dynamic memory allocation 63, 190,351,429

E
echoing to screen 214, 216
ecvt (function) 132
editing
block operations
copying 357, 360, 361,369
searching for character 358
EGA See Enhanced Graphics Adapter (EGA)
elapsed time See time
ellipse (function) 133
ellipses, drawing and filling 169
elliptical arcs 133
elliptical pie slices 454
__ emit__ (function) 134
EMS See memory, expanded and extended
enable (function) 108
encryption 251
end of file
checking 136, 161, 426
resetting 79
end of line, clearing to 85
Enhanced Graphics Adapter (EGA) See also
graphics; screens
colors See colors and palettes
detecting presence of 105
palette See graphics, palettes
env (argument to main) 3
environ (global variable) 4, 601
environment See Programmer's Platform
DOS
header file 614
variables 601
COMSPEC 553
PATH 138,514
environment, DOS See DOS
eof (function) 136
equations, polynomial 395

633

errno (global variable) 602
errno.h (header file) 613
error handlers
hard ware 278, 281, 284, 285
math, user-modifiable 352
errors
codes See errors, messages
detection, on stream 161, 162
DOS
extended information 113
mnemonics 602, 603
indicators, resetting 79
locked file 337, 338
messages
graphics, returning 271
graphics drivers 276
pointer to, returning 271, 531, 532
printing 391,602
mnemonics for codes 613
read/write 162
European date formats 92
even parity (communications) 37, 55
exception handlers, numeric coprocessors 78,
522
exceptions, floating point 88
exec ... (functions) See processes
execl (function) 137
execle (function) 137
execlp (function) 137
execlpe (function) 137
execution, suspending 103, 509, See also
programs, stopping
execv (function) 137
execve (function) 137
execvp (function) 137
execvpe (function) 137
exit codes 11, See also programs, stopping
_exit (function) 142
exit (functions) 26, 143
exit status 143,325
exp (function) 144
expanded and extended memory See memory,
expanded and extended
expl (function) 144
exponents
calculating 144,396,397
double 194, 328

634

extended error information 113
extended error information, DOS 113

F
fabs (function) 145
fabsl (function) 145
far heap See also heap
allocating memory from 146, 155
checking 149
nodes 151
free blocks 149, 152
memory in
freeing 148
measure of unused 147
reallocating 156
pointers 146, 155, 156
walking through 154
far pointers See pointers, far
farcalloc (function) 146
farcoreleft (function) 147
tiny memory model and 147
farfree (function) 148
small and medium memory models and 148
far heap check (function) 149
farheapcheckfree (function) 149
farheapchecknode (function) 151
farheapfillfree (function) 152
farheapwalk (function) 154
farmalloc (function) 155
tiny memory model and 155
farrealloc (function) 156
tiny memory model and 156
FAT See file allocation table (FAT)
fatal errors See errors
FCB See file control block (FCB)
fclose (function) 157
fcloseall (function) 157
fcntl.h (header file) 613
fcvt (function) 158
fdopen (function) 159
feof (function) 161
ferror (function) 162
fflush (function) 162
fgetc (function) 164
fgetchar (function) 165
fgetpos (function) 165
fgets (function) 166

Borland c++ Library Reference

fields
input 446, 450
random record 419, 420
figures, flood-filling See colors and palettes,
filling
file allocation table (FAT) 228,229
file control block (FCB) 418, 420
file handles See files, handles
file modes See also text, modes
binary See binary files
changing 72, 74, 119
default 95, 100, 112
global variables 604
setting 484, 604
text 160, 183, 193, 199
translation 97, 99, 604
file permissions 575
file-sharing mechanisms· See files, sharing
filelength (function) 167
fileno (function) 168
files
access 14, See also file modes
flags 378, 510
permission 74
read/write See access, read/write
accessibility, determining 14
ARGS.EXE 4

attribute bits 378,510
attribute word 73
attributes 97
access mode 72, 119
file sharing 376
searching directories and 114, 172
setting 95, 100, 112
binary See binary files
buffers 496
line 497
.CHR 305, 493
closing 82, 111, 157, 193
COMMAND.COM 553
control block 418, 420
creating See files, new
date 120,233
deleting 434, 579
end of
checking 136, 161, 426
resetting 79

Index

graphics driver 296
handles 82, 111, 378
duplicating 129, 130
linking to streams 159
returning 168
header 10
information on, returning 200
locking 337, 338, 580
modes See file modes
names
parsing 387
unique 365, 556, 568
new 95, 96, 98, 99, 112
open, statistics on 200
opening 375, 377, 378
for update 160, 183, 193, 199
in binary mode 567
shared 198, 510
streams and 182, 193, 198
overwriting 97
pointers See pointers, file
reading 97, 423, 425
and formatting input from 195,443,586,
588,591
characters from 164, 213
data from 189
header file 613
integers from 264
strings from 166
renaming 435
replacing 193
rewriting 95, 96, 112
scratch 556, 568
opening 567
security 251
sequential See text files
sharing
attributes 376
header file 614
locks 337, 338, 580
opening shared files 198, 510
permission 199, 511
size 75
returning 167
statistics 200
temporary 556, 568
opening 567

635

removing 440
text See text files
time 120, 233
unlocking 580
WILDARGS.OBJ 5, 6
writing 125,206,595,597
attributes 97
characters to 188
formatted output to 187,398,584,587
header file 613
strings to 189
fill colors See colors and palettes, fill colors
fill patterns See colors and palettes, fill patterns
fill style (graphics) 270
fillellipse (function) 169
filling a figure See graphics, filling
fillpoly (function) 170
findfirst (function) 171
findnext (function) 174
flags
carry 307, 308, 309, 310
console output 601
DOS verify 262, 498
format specifiers 399,401
read/write 378, 510
video output 601
float.h (header file) 613
floating point
absolute value of 145
binary coded decimal 33, 428
characters and 27
control word 88
conversion See conversion, floating point
displaying 400, 448
double
conversion See conversion, double
exponents 328
exceptions 88
format specifiers 400, 446, 448
functions (list) 621
header file 613
infinity 88
math package 185
modes 88
precision 88
reading 446
software signal 417

636

status word 77, 522
floodfill (function) 175
floor (function) 176
floor! (function) 176
flushall (function) 177
flushing streams 162, 177
_fmemccpy (function) 357
_fmemchr (function) 358
_fmemcmp (function) 358
_fmemcpy (function) 360
_fmemicmp (function) 360
_fmemset (function) 362
fmod (function) 179
_fmode (global variable) 604
fmodl (function) 179
fnmerge (function) 179
fnsplit (function) 181
fonts 492, See also graphics
bit mapped 493
character size 493, 562, 565
characteristics 492
gothic 492
graphics text 270, 492
information on 257
height 562
ID numbers 305
linked-in 433
multiple 383, 493
new 305
sans-serif 492
settings 492
small 492
stroked 492, 493
fine tuning 495
linked-in code 432
maximum number 305
multiple 493
text 384
triplex 492
width 565
fopen (function) 182
foreground color See colors and palettes
format specifiers
assignment suppression 444, 445, 449, 450
characters 400, 446
type 444, 445

Borland C++ Library Reference

conventions
display 400
reading 447
conversion type 399, 400, 403
cprintf 398
cscanf 443
flags 399, 401
alternate forms 401
floating-point 400, 446, 448
fprintf 398
fscanf 443
inappropriate character in 450
input fields and 446, 450
integers 400, 446
modifiers
argument-type 444, 445, 449
input-size 399, 403
size 444, 445, 449
pointers 400, 446
precision 399, 402, 403
printf 398
range facility shortcut 447
scanf 443
sprintf 398,518
sscanf 443
strings 400, 446
vfprintf 398
vfscanf 443
vprintf 398
vscanf 443
vsprintf 398
vsscanf 443
width
printf 399, 402
scanf 444, 445, 449, 450
format strings
input 443
output 398
formatting See also format specifiers
console input 100
cprintf 93
cscanf 100
fprintf 187
fscanf 195
output 93
printf 398
scanf 443

Index

sprintf 518
sscanf 520
stdin See stdin
streams See input; output
strings 518, 590
time 532
vfprintf 584
vfscanf 586
vprintf 587
vscanf 588
vsprintf 590
vsscanf 591
FP_OFF (function) 184
FP_SEG (function) 184
_fpreset (function) 185
fprintf (function) 187
format specifiers 398
fputc (function) 188
fputchar (function) 188
fputs (function) 189
frame base pointers as task state 342, 479
fread (function) 189
free (function) 190
free blocks See memory blocks
freeing memory See memory, freeing
freemem (function) 191
freopen (function) 193
frexp (function) 194
frexpl (function) 194
fscanf (function) 195
format specifiers 443
fseek (function) 196
fsetpos (function) 197
_fsopen (function) 198
fstat (function) 200
_fstrcat (function) 524
_fstrchr (function) 524
_fstrcspn (function) 529
_fstrdup (function) 530
fstream.h (header file) 613
_fstricmp (function) 534
fstrlen (function) 535
_fstrlwr (function) 535
_fstrnbrk (function) 541
_fstrncat (function) 536
_fstrncmp (function) 537
._fstrncpy (function) 539

637

_fstrincmp (function) 539
_fstrnset (function) 540
_fstrrchr (function) 542
_fstrrev (function) 543
jstrset (function) 543
_fstrspn (function) 544
_fstrstr (function) 545
_fstrtok (function) 547
_fstrupr (function) 551
ftell (function) 203
ftime (function) 204
_fullpath (function) 205
functions See also specific function name
8086619
bcd
header file 613
BIOS 619
header file 613
Borland C++ .
licensing 612
child processes 623
header file 614
classification 616
comparison, user-defined 416
complex numbers 621
header file 613
console
header file 613
conversion 616
date and time 623
header file 615
diagnostic 617
directories 616
header file 613
DOS 619
file sharing
header file 614
floating point
header file 613
fstream
header file 613
generic
header file 613
goto 622
header file 614
graphics 617
header file 613

638

integer 621
international
header file 614
information 622
I/O 618
header file 613
iomanip
header file 614
iostream
header file 614
listed by topic 616-624
locale 622
mathematical 621
header file 614
memory 620
allocating and checking 622
header file 614
process control 623
signals
header file 614
sound 622
stdiostr
header file 615
strings 620
strstrea
header file 615
trigonometric See trigonometric functions
variable argument lists 624
windows 623
fwrite (function) 206

G
game port 44, 46
gcvt (function) 207
generic.h (header file) 613
geninterrupt (function) 208
getarccoords (function) 209
getaspectratio (function) 210
getbkcolor (function) 212
getc (function) 213
getcbrk (function) 214
getch (function) 214
getchar (function) 215
getche (function) 216
getcolor (function) 216
getcurdir (function) 218
getcwd (function) 218

Borland C++ Library Reference

getdate (function) 219
_getdcwd (function) 220
getdefaultpalette (function) 221
getdfree (function) 223
getdisk (function) 224
_getdrive (function) 224
getdrivername (function) 225
getdta (function) 226
memory models and 226
getenv (function) 227
getfat (function) 228
getfatd (function) 229
getfillpattern (function) 230
getfillsettings (function) 231
getftime (function) 233
getgraphmode (function) 235
getimage (function) 236
getlinesettings (function) 238
getmaxcolor (function) 240
getmaxmode (function) 242
getmaxx (function) 243
getmaxy (function) 244
getmodename (function) 245
getmoderange (function) 247
getpalette (function) 248
getpalettesize (function) 250
getpass (function) 251
getpid (function) 251
getpixel (function) 252
getpsp (function) 254
gets (function) 254
gettext (function) 255
gettextinfo (function) 256
gettextsettings (function) 257
gettime (function) 259
getvect (function) 260
getverify (function) 262
getviewsettings (function) 263
getw (function) 264
getx (function) 266
gety (function) 267
global variables 599, See also variables
_8087599
_argc 600
_argv 600
arrays
character 600

Index

command-line arguments 600
_ctype 600
daylight 600
setting value of 572
directvideo 601
DOS environment 601
_doserrno 602
environ 4, 601
errno 602
file mode 604
_fmode 604
heap size 605
_heaplen 605
main function and 600
memory models and 605
_new_handler 606
numeric coprocessors and 599
_osmajor 606
_osminor 606
_ovrbuffer 607
printing error messages 602
program segment prefix (PSP) 607
_psp 607
.
stack size 608
_stklen 608
sys_errlist 602
sys_nerr 602
time zones 600, 609
setting value of 572
timezone 609
setting value of 572
tzname 609
setting value of 572
_version 609
video output flag 601
GMT See Greenwich mean time (GMT)
gmtime (function) 268
gothic fonts 492
goto, nonlocal 102,342,478
goto statements
functions (list) 622
header file 614
gotoxy (function) 269
graphdefaults (function) 270
grapherrormsg (function) 271
~raphfreemem (function) 272
_graphgetmem (function) 274

639

graphics See also colors and palettes; text
active page 500
setting 457
adapters 105
problems with 20, 392
arcs 19
coordinates of 209
elliptical 133
aspect ratio
correcting 461
ge~ting

210

bars 30, 32
bit images See bi t images
buffer, internal 475
circles, drawing 76
coordinates See coordinates
current position See current position
(graphics)
default settings 221, 270
ellipses 169
error messages 271
filling See colors and palettes
fonts See fonts
functions
list 617
functions, justifying text for 490
header file 613
I/O 499
library, memory management of 272
lines See lines
memory
allocation of memory from 274
freeing 272
.
mode See graphics drivers, modes
pie slices 392, 454
pixels, color 252, 412
polygons 127, 170
rectangle 430
screens, clearing 78
settings, default 221,270
system
closing down 84
initializing 295
text fonts See fonts
viewport 270
clearing 80
displaying strings in 383,384

640

informa tion 263
setting for output 499
visual page 500
graphics drivers See also device drivers
BGl and 276, 295, 431
device driver table 303
colors See colors and palettes
current 225
detecting 104, 225, 296, 303
error messages 276
file 296
initializing 296
loading 295, 431
modes 298, 436
maximum number for current driver 242
names 245
overriding 104
range 247
returning 235
setting 477
switching 477
text 255, 256
new 303
palettes See graphics, palettes
registering 431
vendor added 303
graphics.h (header file) 613
graphresult (function) 276
Greenwich mean time (GMT) 102, 108,204
converting to 268
time zones and 572
timezone (global variable) 609

H
handlers 505
error See error handlers
exception 78, 522
interrupt 102
DOS278,282
signal See signal handlers
handles, file See files, handles
_harderr (function) 281
harderr (function) 278
hardresume (function) 278
_hardresume (function) 284
hardretn (function) 278
_hardretn (function) 285

Borland C++ Library Reference

hardware
checking
device type 316
for presence of 44, 45, 317
checking for presence of 44, 46
disk drives See disk drives
error handlers 278, 281, 284, 285
I/O, controlling 313
interrupts 44, 45
keyboard See keyboard
ports 299, 301
printer 52, 53
reading from 300, 301
writing to 381, 382
header files 613-615
described 612
floating point 613
prototypes and 612
reading and writing 613
sharing 614
header files (explained) 10
heap 89
allocating memory.from 63, 190,351,429
checking 285
far See far heap
free blocks
checking 286
filling 289
length 605
memory freeing in 190
near, size of 605
nodes 288
reallocating memory in 429
walking through 290
heapcheck (function) 285
heapcheckfree (function) 286
heapchecknode (function) 288
heapfillfree (function) 289
_heaplen (global variable) 605
heapwalk (function) 290
Hercules card See also graphics; screens
detecting presence of 105
hexadecimal digits, checking for 323
high intensity 291
highvideo (function) 291
huge memory model See memory models
hyperbolic cosine 91

Index

hyperbolic sine 508
hyperbolic tangent 554
hypot (function) 292
hypotenuse 292
hypotl (function) 292

IBM 8514
colors, setting 488
detecting presence of 105
IBM 3270 pc, detecting presence of 105
10

font numbers 305
process 251
illegal instruction, software signal 417
imag (function) 293
imagesize (function) 294
imaginary numbers See complex numbers
indicator
end-of-file 79, 136, 161,426
error 79
infinity, floating point 88
initgraph (function) 295
initializing
file pointers 437
graphics system 295
memory 362, 483
random number generator 422, 519
strings 540, 543
inline optimization 618
inp (function) 299
inport (function) 300
inportb (function) 301
input See also I/O
console, reading and formatting 100
fields 446
format specifiers and 450
from streams 195, 586, 591
formatting 195,443,586,588,591
pushing characters onto 576
stdin 443, 588
terminating from streams 450
input ports See ports, I/O
inpw (function) 301
insline (function) 302
installuserdriver (function) 303
installuserfont (function) 305

641

int86 (function) 307
int86x (function) 308
intdos (function) 309
intdosx (function) 310
integers
absolute value 11
ASCII and See ASCII codes
conversion See conversion, integer
displaying 400
division 110
long integers 329
format specifiers 400, 446
functions (list) 621
long
absolute value of 328
conversion See conversion, long integer
division 329
rotating 344, 345
ranges
header file 614
reading 264, 446
rotating 344, 441, 442
storing in memory 393
unsigned long, conversion See conversion,
unsigned long integer
writing to stream 414
integrated environment
wildcard expansion and 6
intensity
high 291
low 343
normal 374
internal graphics buffer 475
international
country-dependent data 92
setting 334, 483
date formats 92
international information
functions (list) 622
header file 614
interrupts
8086307, 308, 311
BIOS See BIOS, interrupts
chaining 69
control-break 214, 278, 284,467
controlling 108, 208
disabling 108

642

DOS See DOS, interrupts
DOS interface See also DOS, interrupts
enabling 108
handlers 69
DOS 102,278,282
signal handlers and 505
non-maskable 108
software 208, 307, 312
interface 308, 311
signal 417
system equipment 44, 45
vectors 102
8086 123, 124,261
getting 260
. setting 124, 260
intr (function) 311
invalid access to storage 417
inverse cosine 16
inverse sine 23
inverse tangent 25, 26
io.h (header file) 613
ioctl (function) 313
I/O See also input; output
buffers 466
characters, writing 406, 407
controlling 313
disk 41
files See files, reading; files, writing
functions (list) 618
graphics 499
integers, writing 414
keyboard 214, 216
checking for keystrokes 324
low level
header file 613
ports
hard ware 299, 300, 301
writing to 381, 382
screen 93
writing to 94, .407
serial 36, 55
streams 160, 183, 193, 199, 576, See also
streams, reading; streams, writing
strings See strings, reading; strings, writing
iomanip.h (header file) 614
iostream.h (header file) 614
isalnum (function) 314

Borland C++ Library Reference

is alpha (function) 315
isascii (function) 316
isa tty (function) 316
iscntrl (function) 317
isdigit (function) 318
isgraph (function) 319
islower (function) 319
isprint (function) 320
ispunct (function) 321
isspace (function) 321
isupper (function) 322
isxdigit (function) 323
itoa (function) 323

J
Japanese date formats 92
justifying text for graphics functions 490

K
kbhit (function) 324
keep (function) 325
keyboard
buffer, pushing characters back into 577
I/O 214, 216
checking for 324
operations 47, 49
reading characters from 214, 216
keystrokes, checking for 324

L
labs (function) 328
large memory model See memory models
ldexp (function) 328
ldexpl (function) 328
ldiv (function) 329
length
of files 75, 167
of strings 535
lfind (function) 330
libraries
entry headings 9
files (list) 611
graphics, memory management and 272
limits.h (header file) 614
line (function) 331
line-buffered files 497

Index

line styles See graphics, lines
linear searches 330, 346
linerel (function) 332
lines See also graphics
blank, inserting 302
clearing to end of 85
deleting 85, 104
drawing
between points 331
from current position 333
mode 501
relative to current position 332
pattern of 238
rectangles and 430
style of 238, 480
thickness of 238, 480
lineto (function) 333
linked-in fonts 433
linked-in graphics drivers code 431
literal values, inserting into code 134
local standard time 102, 108, 204, 268, 336, See
also time zones
locale
current 334
functions (list) 622
selecting 483
locale.h (header file) 614
localeconv(function) 334
localtime (function) 335
lock (function) 337
locking (function) 338
locking.h (header file) 614
locks, file-sharing 337, 338, 580
log 10 (function) 341
log (function) 340
log 101 (function) 341
logarithm
base 10 341
natural 340
logl (function) 340
long integers See integers, long
longjmp (function) 342
header file 614
low intensity 343
lowercase
characters 569, 570
checking for 319

643

conversions 551, 571, 572
strings 535
lowvideo (function) 343
LPTl and LPT2 See printers, ports
_lrotI (function) 344
lrotr (function) 345
Isearch (function) 346
lseek (function) 347
ltaa (function) 348

M
machine language instructions
inse~ted into object code 134
macros
argument lists
header file 614
assert 24, 613
case conversion 569, 571
character classification 317, 321
case 314, 315, 319, 322
integers 314, 316, 318, 323
printable characters 319,320
character conversion
header file 613
characters 407
ASCII conversion 569
comparing two values 354, 363
debugging
assert
header file 613
defining
header file 614
directory manipulation
header file 613
far pointer 365
file deletion 434
input ports 299, 301
output ports 381
peek 388
peekb 390
poke 393
pokeb 394
toascii 569
variable argument list 582
main (function) 3-7
arguments passed to 3, 600
example 4

644

wildcards 5
compiled with Pascal calling conventions 7
declared as C type 7
global variables and 600
value returned by 7
_makepath (function) 349
malloc (function) 351
malloc.h (header file) 614
mantissa 194,367
math
functions
list 621
math coprocessors See numeric coprocessors
math error handler, user-modifiable 352
math.h (header file) 614
math package, floating-point 185
matherr (function) 352
max (function) 354
maximum color value 240
mblen (function) 355
mbstowcs (function) 356
mbtowc(function) 356
MCGA, detecting presence of 105
medium memory model See memory models
mem.h (header file) 614
memccpy (function) 357
memchr (function) 358
memcmp (function) 358
memcpy (function) 360
memicmp (function) 360
memmove (function) 361
memory See also memory allocation
access (DMA) 43, 44, 46
access error See errors
addresses
returning byte from 389
returning word from 388
storing byte at 394
storing integer at 393
allocation
functions (list) 622
bit images 294
saving to 236
blocks See memory blocks
checking 622
copying 357, 360, 361, 369
in small and medium memory models 368

Borland C++ Library Reference

direct access (DMA) 43,44,46
expanded and extended 386
freeing
in DOS memory 191
in far heap 148
in graphics memory 272
in heap 190
in small and medium memory models 148
functions (list) 620
header file 613, 614
initializing 362, 483
measure of See memory allocation
models See memory models
random access See RAM
reallocating See memory allocation
screen segment, copying to 255
size 45, 46
determining 51
memory allocation 18, See also memory
data segment 59
changing 442
dynamic 63, 190,351,429
far heap See far heap
freeing 148, 191
graphics memory 272, 274
heap See heap
memory models and 63, 148, 155
_new_handler and 606
reallocating 156
set_new_handler and 606
unused 89, 147
memory allocation errors 485
memory blocks
adjusting size of 156, 464
in heap 429
file control 418, 420
free 149, 286
filling 152, 289
initializing 362, 483
random
reading 418
writing 420
searching 358
memory.h (header file) 614
memory management functions 614
memory models
disk transfer address and 226

Index

DOS system calls and 34, 35
functions
list 622
libraries 611
math files for 611
memory allocation and 64, 148, 155
moving data and 368
program segment prefix and 605, 608
size of near heap 605
stack size 608
tiny, restrictions 147, 155, 156
memset (function) 362
microprocessors 506
midnight, number of seconds since 57, 58
min (function) 363
MK_FP (function) 364
mkdir (function) 363
mktemp (function) 365
mktime (function) 366
mnemonics, error code 613
mnemonics, error codes 602,603
modes
access See access modes
files See file modes
floating point, rounding 88
graphics See graphics drivers, modes
screen See screens, modes
text See text, modes
modf (function) 367
modfl (function) 367
modifiers, format specifiers See format
specifiers, modifiers
modulo 179
monochrome adapters 105, See also graphics
graphics problems 20, 392
monochrome EGA See Enhanced Graphics
Adapter (EGA)
movedata (function) 368
moverel (function) 369
movetext (function) 371
m9veto (function) 372
movmem (function) 369
multibyte character 355
multibyte character to wchar_t code 356
multibyte string to a wchar_t array 356
multiple tasks 342, 479

645

N
natural logarithm 340
near heap 605
new files 95, 96, 98, 99, 112, See also files,
opening
new.h (header file) 614
_new_handler (global variable) 606
newline character 413
NMI108
no parity (communications) 37, 55
nodes, checking on heap 288
non-maskable interrupt 108
nonlocal goto 102,342,478
norm (function) 373
normal intensity 374
normvideo (function) 374
no sound (function) 374
number of drives available 224
numbers See also complex numbers; floating
point; integers
ASCII

checking for 318
BCD 33, 428
complex See complex numbers
functions (list) 621
pseudorandom 418
random 418, 422
generating 519
rounding 65, 176
turning strings into 27
numeric coprocessors
checking for presence of 45, 46
control word 88
exception handler 78, 522
global variables 599
problems with 186
status word 77,522

o
object code
machine language instructions and 134
odd parity (communications) 37, 55
offset, of far pointer 184, 365
open (function) 375, 377
header file 613
_open (function) 375

646

opendir (function) 379
opening files See files, opening
operating mode of screen See screens, modes
_osmajor (global variable) 606
_osminor (global variable) 606
outp (function) 381
outport (function) 381
outportb (function) 381
output See also I/O
characters, writing 407
displaying 187, 398, 587
flag 601
flushing 162
formatting 93
ports See ports, I/O
to streams
formatting 187,398,587
outpw (function) 382
outtext (function) 383
outtextxy (function) 384
overlays
buffers
default size 607
expanded and extended memory and 386
overlays, coroutines and 342,479
overwriting files 97
_ovrbuffer (global variable) 607
_OvrInitEms (function) 386
_OvrlnitExt (function) 386

p
-p option (Pascal calling conventions)
main function and 7 .
page
active 457
numbers, visual 500
palettes See colors and palettes
parameter values for locking function 614
parent process 137, 513, See also processes
parity (communications) 37, 55
parsfnm (function) 387
parsing file names 387
Pascal calling conventions
compiling main with 7
passwords 251
PATH environment variable 137, 138,514

Borland C++ Library Reference

paths
directory 452, 453
DOS 452, 453
finding 218
names
converting 205
creating 179, 349
splitting 181,516
patterns, fill See colors and palettes, fill patterns
pause (suspended execution) 103, 509
PC speaker 374, 512
peek (function) 388
peekb (function) 389
permissions, file access See files, access
perror (function) 391, 602
PIO (process 10) 251
pie slices 392
elliptical 454
pieslice (function) 392
pixels, graphics color 252, 412
pointers
to error messages 271, 531, 532
far 146, 155, 156
address segment 184, 365
creating 364
offset of 184, 365
file
initializing 437
moving 347
obtaining 165
resetting 196, 424, 426
returning 203
current position of 555
setting 197,378,510
format specifiers 400, 446
frame base 342, 479
stack 342, 479
poke (function) 393
pokeb (function) 394
polar (function) 394
poly (function) 395
polygons
drawing 127, 170
filling 170
polyl (function) 395
polynomial equation 395

Index

ports
checking for presence of 44,·46
communications 36, 44, 46, 55, 317
hardware See hardware, ports
I/O 300, 301, 381, 382
macros 299, 301, 381
writing to 381, 382
POSIX directory operations 613
powlO (function) 397
pow (function) 396
powlOl (function) 397
powers
calculating ten to 397
calculating values to 396
powl (function) 396
precision
floating point 88
format specifiers 399, 402, 403
printable characters, checking for 319, 320
printers See also hardware
checking for 44, 46,317
ports 52, 53
printing directly 52, 53
printf (function) 398
conversion specifications 398
format specifiers 398
printing, error messages 391, 602
process control
functions (list) 623
process.h (header file) 614
process 10 251
processes
child 137,513
exec. .. (functions)
suffixes 137
parent 137,513
stopping 11
profilers 607
program segment prefix 254
program segment prefix (PSP) 254
current program 607
memory models and 605, 608
programs
loading and running 137
process IO 251
RAM resident 325
signal types 417

647

stopping 11,26, 102
exit status 65, 66, 142, 143,325
request for 417
suspended execution 103, 509
TSR 69, 325
protocol settings (communications) 37, 55
prototypes
graphics functions
header file 613
header files and 612
pseudorandom numbers 418
PSP See program segment prefix (PSP)
_psp (global variable) 607
punctuation characters, checking for 321
putc (function) 406
putch (function) 407
putchar (function) 407
putenv (function) 408
putimage (function) 410
putpixel (function) 412
puts (function) 413
puttext (function) 414
putw (function) 414

Q
qsort (function) 415
quicksort 415
quotient 110, 329

R
raise (function) 417
header file 614
RAM See also memory
resident program 325
size 45, 46, 51, 52
unused 89
rand (function) 418
randbrd (function) 418
randbwr (function) 420
random (function) 422
random access memory See RAM
random block read 418
random block write 420
random number generator 418, 422
initializing 422, 519
random numbers 418, 422

648

random record field 419, 420
randomize (function) 422
range facility shortcut 447
Jead (function) 423
read (function) 425
read access See access, read/write
read error 162
read/write flags 378, 510
readdir (function) 427
real (function) 428
real numbers See floating point
realloc (function) 429
reallocating memory See memory allocation
records
random fields 419, 420
sequential 330
rectangle (function) 430
register variables, as task states 342, 479
registerbgidriver (function) 431
registerbgifont (function) 432
registers 278
segment, reading 456
REGPACK structure 312
remainder 110, 179, 329
remove (function) 434
rename (function) 435
request for program termination 417, See also
programs, stopping
restorecrtmode (function) 436
restoring screen 414,436
rewind (function) 437
rewinddir (function) 438
rmdir (function) 439
rmtmp (function) 440
rotation, bit
long integer 344,345
unsigned integer 441, 442
_rot! (function) 441
Jotr (function) 442
rounding 65, 176
banker's 34
modes, floating point 88
RS-232 communications 36, 55
run-time library
functions by category 616
source code, licensing 612

Borland C++ Library Reference

5
S_IREAD 575
S_IWRITE 575
sans-serif font 492
sbrk (function) 442
scanf (function) 443
format specifiers 443
termination 450
scanf (functions) termination conditions 450
scratch files See also files
naming 556, 568
opening 567
screens
aspect ratio
correcting 461
getting 210
bit images See bit images
clearing 78, 86, 477
coordinates, maximum 243, 244
copying
text from 371
displaying strings 94
echoing to 214, 216
formatting output to 93
graphics See graphics
graphics drivers See graphics drivers
modes
restoring 413, 436
text See text, modes
saving 255
segment, copying to memory 255
writing characters to 407
scrolling 610
search.h (header file) 614
search key 346
_searchenv (function) 452
searches
appending and 346
binary 60
block, for characters 358
DOS
algorithms 137
path, for file 452, 453
header file 615
linear 330, 346
string
for character 524

Index

for tokens 547
searchpath (function) 453
sector (function) 454
sectors, disk See disks, sectors
security, passwords 251
seed number 520, See also random numbers
segment prefix, program 254, 605, 607, 608
segments See also data segment
far pointer 184, 365
registers, reading 456
scanning for characters in strings 544
screen, copying to memory 255
segread (function) 456
sequential files See text files
sequential records 330
serial communications, I/O 36, 55, See also
communications
set_new_handler (function) 485
setactivepage (function) 457
setallpalette (function) 458
setaspectratio (function) 461
setbkcolor (function) 462
setblock (function) 464
setbuf (function) 466
setcbrk (function) 467
setcolor (function) 468
setcursortype (function) 470
setda te (function) 219
setdisk (function) 224
setdta (function) 471
setfillpattern (function) 472
setfillstyle (function) 473
setgraphbufsize (function) 475
setgraphmode (function) 477
setjmp (function) 478
header file 614
setjmp.h (header file) 614
setlinestyle (function) 480
setlocale (function) 483
setmem (function) 483
setmode (function) 484
set_new_handler 606
setpalette (function) 486
setrgbpalette (function) 488
settextjustify (function) 490
settextstyle (function) 492
settime (function) 259

649

setting file read/write permission 575
settings, graphics, default 221, 270
setusercharsize (function) 495
setvbuf (function) 496
setvect (function) 260
setverify (function) 498
setviewport (function) 499
setvisualpage (function) 500
setwritemode (function) 501
share.h (header file) 614
shared files See files, sharing
signal (function) 503
header file 614
signal.h (header file) 614
signals
handlers 417, 503
interrupt handlers and 505
returning from 506
user-specified 503
program 417
software See software signals
sin (function) 507
sine 507
hyperbolic 508
inverse 23
sinh (function) 508
sinhl (function) 508
sinl (function) 507
size
color palette 250
file 75, 167
memory 45, 46, 51
stack 608
sleep (function) 509
small fonts 492
small memory model See memory models
software interrupts See interrupts, software
software signals 417
sopen (function) 510
sorts, quick 415
sound (function) 512
sounds
functions (list) 622
turning off 374
turning on 512

650

source code
. run-time library
licensing 612
SP register
hardware error handlers and 278
space on disk, finding 117, 223
spawn ... (functions) See processes
suffixes 514
spawnl (function) 513
spawnle (function) 513
spawnlp (function) 513
spawnlpe (function) 513
spawnv (function) 513
spawnve (function) 513
spawnvp (function) 513
spawnvpe (function) 513
speaker
turning off 374
turning on 512
_splitpath (function) 516
sprintf (function) 518
format specifiers 398, 518
sqrt (function) 518
sqrtl (functioI!). 518
square root 518
srand (function) 519
sscanf (function) 520
format specifiers 443
stack 64, 89, 351
length 608
pointer, as task states 342,479
size, global variable 608
standard time 102, 108, 204, 268, See also time
zones
stat structure 201
_status87 (function) 522
status bits (communications) 37, 56
status byte 42
status word
floating point 77
floating-point 522
numeric coprocessors 77, 522
stdargs.h (header file) 614
stdaux 158, See also streams
stddef.h (header file) 614
stderr 158, 193, See also streams
stderr (header file) 614

Borland C++ Library Reference

stdin 158, 193, See also streams
buffers and 466
reading
characters from 165,215
input from 443, 588
strings from 254
stdin (header file) 614
. stdio.h (header file) 614
stdiostr.h (header file) 615
stdlib.h (header file) 615
stdout 158, 193, See also streams
buffers and 466
writing
characters to 188,407
formatted output to 398, 587
strings to 413
stdout (header file) 614
stdprn 158, See also streams
stdprn (header file) 614
stime (function) 522
_stklen (global variable) 608
stop bits (communications) 37, 55
storage, invalid access 417
stpcpy (function) 523
strcat (function) 524
strchr (function) 524
strcmp (function) 525
strcmpi (function) 526
strcoll (function) 527
strcpy (function) 528
strcspn (function) 529
_strdate (function) 529
strdup (function) 530
streams
closing 157, 193
error and end-of-file indicators 79, 161, 162
flushing 162, 177
formatting input from 195,586,591
stdin 443, 588
header file 614
I/O 160, 183, 193, 199
pushing character onto 576
linking file handles to 159
opening 182, 193, 198
pointers See also pointers
file 196, 197
initializing 437

Index

reading
characters from 164,213
data from 189
inputfrom 195,586,591
stdin 443
.
integers from 264
strings from 166
replacing 193
stdaux 158
stderr 158, 193
stdin See stdin
stdout See stdout
stdprn 158
terminated input 450
unbuffered 466, 496
writing 177, 206
characters to 188,406,407
formatted output to 187, 398, 584
stdout 587
integers to 414
strings to 189, 413
streams, buffered See buffers, streams and
_strerror (function) 531
strerror (function) 532
strftime (function) 532
stricmp (function) 534
string.h (header file) 615
strings
appending 524
parts of 536
changing 551
comparing 358, 525, 527
ignoring case 360, 526, 534
parts of 537
ignoring case 538, 539
concatenated 524, 536
converting See conversion, strings
copying 523, 528
new location 530
truncating or padding 539
displaying 94, 383, 384, 400
duplicating 530
format See format strings
format specifiers 400, 446, See also format
specifiers
formatting 518, 532, 590
functions (list) 620

651

header file 615
height, returning 562
initializing 540, 543
length, calculating 535
lowercase 535 .
reading 446
and formatting 520
from console 67
from streams 166, 254
reversing 543
searching
for character 524
for character in set 541
for characters not in set 529
for last occurrence of character 542
for segment in set 544
for substring 545
for tokens 547
transforming 551
uppercase 551
width, returning 565
writing
to current environment 408
formatted output to 518, 590
to stdout 413
to streams 189
to the screen 94
strlen (function) 535
strlwr (function) 535
strncat (function) 536
strncmp (function) 537
strncmpi (function) 538
strncpy (function) 539
strnicmp (function) 539
strnset (function) 540
stroked fonts See fonts, stroked
strpbrk (function) 541
strrchr (function) 542
strrev (function) 543
strset (function) 543
strspn (function) 544
strstr (function) 545
strstrea.h (header file) 615
_strtime (function) 545
strtod (function) 546
strtok (function) 547
strtol (function) 548

652

_strtold (function) 546
strtoul (function) 550
struct DOSERROR 113
struct heapinfo 290
structures
graphics palette definition 221
REGPACK312
stat 201
strupr (function) 551
strxfrm (function) 551
substrings, scanning for 545
suffixes
exec ... 137
spawn ... 514
support for variable-argument funtions 615
suspended execution, program 103, 509
swab (function) 552
swapping bytes 552
syntax errors See errors
sys_errlist (global variable) 602
sys_nerr (global variable) 602
sys \stat.h (header file) 615
sys\types.h (header file) 615
system
buffers 157
commands, issuing 553
date See dates
DOS calls See DOS, system calls
equipment interrupt 44, 45, See also
hardware
error messages 391, 602, See also errors
graphics 84, 295
time See time
system (function) 553

T
tables, searching 60, 346
tan (function) 554
tangent 554
hyperbolic 554
inverse 25, 26
tanh (function) 554
tanhl (function) 554
tanl (function) 554
task states
defined 342, 479
register variables 342, 479

Borland C++ Library Reference

tasks, multiple 342, 479
tell (function) 555
template (file names) 365
tempnam (function) 556
temporary files See also files
naming 556, 568
opening 567
removing 440
terminals See also hardware
checking for 317
terminate and stay resident programs 325
termina ting
input from streams 450
program execution See programs, stopping
software signals 417
termination function 26
testing conditions 24
text See also file modes; graphics; text files
attributes 558, 559, 560
background color, setting 558, 559
characteristics 492
colors 560, See also colors and palettes
copying See also editing, block operations
from one screen rectangle to another 371
to memory 255
to screen 414
fonts See fonts
intensity
high 291
low 343
normal 374
justifying 490
modes (screens) 414, See also file modes
character color 558, 560
coordinates 255
copying to memory 255
video information 256
screens See screens
strings, displaying 383, 384
window See windows, text
text (screens)
modes 563, 594
text files See also files; text
_fsopen and 199
creat and 97
creattemp and 99
fdopen and 160

Index

fopen and 183
freopen and 193
_dos_read and 424
_read and 423
reading 426
setting 484
mode 160, 183, 193, 199, 604
textattr (function) 558
textbackground (function) 559
textcolor (function) 560
textheight (function) 562
textmode (function) 563
textwidth (function) 565
three-dimensional bars 32
time See also dates; time zones
BIOS timer 57, 58
delays in program execution 103, 509
difference between two 107
elapsed 82, 107
returning 566
file 120, 233
forma tting 532
functions (list) 623
global variables 572, 600, 609
system 22, 101, 204, 268
converting from DOS to UNIX 126
converting from UNIX to DOS 578
local 335
returning 121, 259
setting 121,259,522
time (function) 566
time and date conversion See conversion, date
and time
time.h (header file) 615
time zones 204, 268, See also daylight saving
time; time
arrays 609
differences between 108
global variables 600, 609
Greenwich mean time See Greenwich mean
time (GMT)
local See local standard time
setting 102, 572
timer, reading and setting 57, 58
timezone (global variable) 609
setting value of 572
tiny-memory model See memory models

653

tmpfile (function) 567
tmpnam (function) 568
toascii (function) 569
tokens, searching for in string 547
_tolower (function) 569
to lower (function) 570
_toupper (function) 571
toupper (function) 572
translation mode 97,99,604
triangles, hypotenuse 292
trigonometric"functions See also complex
numbers
arc cosine 15
arc sine 23
arc tangent 25, 26
cosine 90
hyperbolic 91
inverse 15
hyperbolic tangent 554
sine 507
hyperbolic 508
inverse 23
tangent 554
hyperbolic 554
inverse 25, 26
triplex font 492
TSR programs 69, 325
Turbo Profiler 607
two-dimensional bars 30
type checking, device 316
tzname (global variable) 609
setting value of 572
tzset (function) 57~

u

u.s. date formats 92
ultoa (function) 574
umask (function) 575
unbuffered streams 466, 496
ungetc (function) 576
ungetch (function) 577
UNIX

constants
header file 615
date and time
converting DOS to 126
converting to DOS format 578

654

unixtodos (function) 578
unlink (function) 579
unlock (function) 580
unsigned integers See integers
unsigned long integers See integers
uppercase
characters 322, 571, 572
checking for 322
conversions 535, 569, 570
strings 551
user-defined
comparison function 416
fill pattern 472, 473, See also graphics, fill
patterns
user hook 352
user-loaded graphics driver code 431
user-modifiable math error handlers 352
user-specified signal handlers 503
utime (function) 581
utime.h (header file) 615

v
va_arg (function) 582
va_arg (variable argument macro) 583
va_end (function) 582
va_list (variable argument macro) 583
va_start (function) 582
va_start (variable argument macro) 583
values See also absolute value
break 60, 442
calculating powers to 396, 397
comparing 354, 363
literal 134
values.h (header file) 615
varargs.h (header file) 615
variables
argument list 582
environment 138,514,601
COMSPEC 553
global See global variables
register 342, 479
variable argument list
conversion specifications and 398
vectors, interrupt See interrupts
vendor-added device driver 303
verify flag (DOS) 262,498
verify the heap 290

Borland C++ Library Reference

version numbers, DOS 606, 609
vfprintf (function) 584
format specifiers 398
variable argument list 582
vfscanf (function) 586
format specifiers 443
variable argument list 582
VGA See Video Graphics Array Adapter (VGA)
video See also hardware
checking for 317
information, text mode 256
mode See also graphics drivers, modes;
screens, modes
checking 45, 46
output flag 601
Video Graphics Array Adapter (VGA) See also
graphics; screens
color palettes 459, See also graphics, color
palette
colors See colors and palettes
detecting presence of 105
viewport See graphics, viewport
visual graphics page 500
vprintf (function) 587
format specifiers 398
variable argument list 582
vscanf (function) 588
format specifiers 443
variable argument list 582
vsprintf (function) 590
format specifiers 398
variable argument list 582
vsscanf (function) 591
format specifiers 443
variable argument list 582

w
warning beeps 374, 512
warnings See errors

Index

wcstombs (function) 592
wctomb (function) 593
wherex (function) 593
wherey (function) 594
whitespace, checking for 321
width
specifier See format specifiers, width
string, returning 565
WILDARGS.OBJ 5
wildcards
expansion 5
by default 6
from the IDE 6
window (function) 594
windows
functions (list) 623
scrolling 610
text
cursor position 269, 593, 594
defining 594
deleting lines in 85, 104
inserting blank lines in 302
words See also status word
floating-point control 88
reading from hard ware ports 300, 301
returning from memory 388
writing to hardware ports 381, 382
working directory See directories, current
write (function) 597
write access See access, read/write
write error 162, See also errors

x
x aspect factor 210
x-coordinate 243, 266, See also coordinates

y
y aspect factor 210
y-coordinate 244, 267, See also coordinates

655

3.1

B o R L A N D
Corporate Headquarters: 1800 Green Hills Road, P.O. Box 660001 , Scotts Valley, CA 95067-(X)Ol, (408) 438-5300. Officas in: Australia,
Belgium, ('",nada, Denmark, France, Germany, Hong Kong, Italy, Japan, Korea, Malaysia, Nethertands, New Zeaiand, Singapore, Spain,
Sweden, Taiwan and Untted Kingdom. Part #14MN-BCP04-31 • BOR 3857



Source Exif Data:
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.3
Linearized                      : No
XMP Toolkit                     : Adobe XMP Core 4.2.1-c043 52.372728, 2009/01/18-15:56:37
Producer                        : Adobe Acrobat 9.12 Paper Capture Plug-in
Modify Date                     : 2009:07:09 15:55:03-07:00
Create Date                     : 2009:07:09 15:55:03-07:00
Metadata Date                   : 2009:07:09 15:55:03-07:00
Format                          : application/pdf
Document ID                     : uuid:28311ce4-0ecf-4dd1-b1e8-981afff9b44f
Instance ID                     : uuid:872b2e7e-ee3c-448d-9261-a47592bc84ce
Page Layout                     : SinglePage
Page Mode                       : UseNone
Page Count                      : 671
EXIF Metadata provided by EXIF.tools

Navigation menu