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 .
Page Count: 671
Download | |
Open PDF In Browser | View 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