Sie sind auf Seite 1von 335
LIBRARY REFERENCE RUNTIME LIBRARY I GLOBAL VARIABLES Wi CROSS-REFERENCE BORLAND Borlana’ C++ Version 3.0 Library Reference BORLAND INTERNATIONAL INC, 1800 GREEN HLS ROAD 0, BOX sc001, SCOMS VALIEW.CA #0087 O20) RI Copyright © 1991 by Borland intemational. Allights reserved. All Borlond producis uly ladernarks oF tegistered trademarks of Boriand Intemational, Inc. Other brand and product names are trademars or registered frademarks of thel respective holders. Windows, as used! in this manual, refers fo Microsoft's imple- mentation of a windows system. 1098765432 Introduction Class and member function documentation Chapter 1 The main function ‘Axguments to main ‘An example program. Wildcard arguments. ‘An example program Using -p (Pascal calling conventions) The value main returns Chapter 2 The run-time library How to use function entries abort abs .. absread abswrite acos, acosl alloca allocmem, dos_allocmem. amg. asctime asin, asinl assert atan,atanl atan?, atan2l atexit atof, _atold atoi atol bat... bar3d 2. bed bdos bdosptr . ioscom bios disk Biosdisk biosequip .. “bios equiplist bioskey bios keybrd Biosmemory _bios_memsize biosprint bios printer bios_serialcom biostime bios_timeofday rk search cabs, cabs] calloc ceil, ceill _c exit “exit egets chain_intr chdir _chdrive “chmod chmod chsize circle -clear87 leardeviee clearer clearviewport clock close, close creat, dos. creat SSRRLISVSSRISRRLR creat creatnew creattemp scant 100 time 101 tribe 102 delay 108 delline 108 detectgraph 104 difitime : 107 disable, disable, enable, enable ...... 108 div 110 _dos_close Mm “dos creatnew 12 dosexterr 13 14 116 17 118 119 = + 120 “dos_gettime, dos settime == ii “doo getvect SOT aa “dos_setvect : 14 “dos write ostounix ellipse «.... a 139 emit veeneee TBM eof 136 exec, execle, exeelp, execlpe, execv, execve, excvp,exeepe sess 137 Lexit ss. = 142 exit... — 13 exp, expl mer fabs, fabs! 145 farcalloe 146 farcorelett 7 farfree - M8 farheapeheck ... a farheapeheckfree . 149 farheapchecknode 151 farheapfilliree farheapwalk . farmalloc . farrealloc felose . _fmemset fee Jmod, fmodl fe le) fnmerge : 9 insplit. 181 fopen S182 FP_OFF, FP_SEG 184 _fpreset is iprintt . fpute : " fputchar .... 188, {puts «2... = 189 freemem, _dos_freemem 191 freopen - frexp, frexpl tat, stat 200 fst 203 fell 203, fiime ~ 208 _fullpath Dias 208 2 206, 207 208 209 write get geninterrupt ... getarccoonds getaspectratio ... . 210 zgetbkcolor : ete getcbrk etch getchar .. getche .. getcolor -. getcurdir getewd Betdat,_dos getdate, do, sedate, setdate getdewd on sgetdefaultpalette 2221 getdfree 223 esti, sti. (erage Heineman. erate ee Sear eeatd sealpicn -. etigs Setting seine ee aa seainstings Scmosclor Ecinnmode femarx Semary Eemodenane Semedennge Sepa Sebel sees i eel oe pe oes etoile Setonatings Sore mites Soe ete Evenly Eeviowsatings SURRRSRRENRERS "eraphireemem | “graphgetmem gophresult harder, hardresume, hardretn harderr “harcresume - “hardretn .. hreapcheck heapcheckfree . heapchecknode heapiilfree . heapwalk highvideo | hypot, hypot! imag .. imagesize initgraph inp inport inportb inpw .. insline | instaluserdriver installoserfont intB into intdos intdose intr ioctl isalnum isalpha | isascii isatty . ‘sented isdigit |. isgraph - islower | isprint ispunct isspace isupper isxdigit itoa kbhit keep, _dos keep labs Idexp, Idexpl 281 284 285 285, 286 288 Idiv find ‘ line BLL BI linerel 332 lineto ...- localeconv localtime . lock ... locking. log, log Jogi0, logit longimp. lowvideo trot! “rote Isearch - Iseek toa _makepath ‘malloc .. matherr,_matherrl mblen mbstowes mbtowe .. memecpy,_fmemecpy ‘memchr, _fmemehr ‘mememp, _fmememp memcpy, fmemepy . memiemp,_fmemicmp iemunove ee 361 329 memset, _fmemset + 362 min 363 mkdir 363, Mi FP = 364 mktemp + 365 mktime S366 ‘modf, modi » 367 movedata movmem, ‘moverel movetext moveto . norm normvideo 374 nosound ..2.2...- 374 open, dos open 375 open : 37 opendir 379 utp : 381 coutport, outport + 381 rand. randbrd | randbwr . random randomize ..... read, dos_read read readdir . real realloc rectangle rogisterbgidriver registerbgifont remove renames... restorecrtmode rewind rewinddir rmdir rmimp « rot “rotr Sbrk « seanf ~searchenv Searchpath, sector... segread - selactivepage setallpalette setaspectratio setbkcolor ...... setblock, _dos_setblock setbuh setebrk. setcolor _setcursortype Setdta .. setfillpattern setfilstyle setgraphbufsize . selgraphmode .. setjmp ... sellinestyle sellocale . setmem setmode . set_new_ha setpalette setrgbpalette .. settextjustify settextstyle » setusercharsize ae ae ERRRRGRRRED ye 496 setverify setviewport setvisualpage . setwritemode signal sin, sin] sinh, sinkl . spawn, spawnle, spawnlp, spavnipe, spawnv, spawnve, spawnvp, and spawnvpe . _splitpath sprintf sqrt, sqrtl srand sscanf status8? stime .. stpepy - streat,_fstreat strehr, _fstrchr stremp strempi stroll strepy strespn,_fstrespn. _strdate ad srdup « _strerror . e Strerror : 532 strftime . : 532 striemp,_fstriemp.......... » 534 strien,_ftrlen 535, stein, fatrlove : +335 stmneat,_fstmneat ....... 536 strnemp, fstenemp = 37) stmempi stmepy, fstrepy .... stmiemp, fstrmicmp .. = a) stmset,_fStrnset . stipbrk,_fstrpbrk. strrchs,_fstrrehr strrev,_fstrrev strset, fstrset strspn,_fstrspn strsty,_fstrstr strtime strtod,_strtold .- strtok, fstrtok stztol strtoul strupr,_fstrupr stexfrm : swab system fan, tant tanh, tankl tell tempnam textattr textbackground .. textcolor textheight textmode textwidth time ‘tmpfile tmpnam toascii tolower tolower _toupper toupper set ultoa umask . uungetc .. uungerch unixtodos unlink unlock |. utime va_arg, va_end, va_start viprinté vfscanf 545 — vprintf vscanf vsprintf vsscanf westombs wetomb .. wherex wherey . window _write write Chapter 3 Global variables 5087 Taree cary “type daylight directvideo ero, _dosermo, sys ertist, sys_nerx “finode heaplen “new handler .- osmajor, -osminor “ovrbutfer Psp ken timezone taname “wseroll Appendix A Run-time library cross- reference 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 Index 609 610 21: detectgraph constants 2.2: Graphics drivers information 23: Graphics drivers constants 105 106 vil 2.4: Color palettes 25: Graphics modes 2.6: Actual color table 297 Class and member function documentation Introduction 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 (ncluding 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++ 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. Certain classes and class member functions are incorporated in. Chapter 2. Here’sa list of the classes and member functions and their page numbers. The typefaces used in this manual are wed os desorbed nthe User’ ‘Gui. fog togi0 polar real in sinn sqrt tan tanh Type ‘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 smember function ‘member Function ‘member function ‘member Function ‘member funtion member Function rember function Borland C++ Library Reference (Chapter I, The main function 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 Tocation, the following points about main always apply. Arguments to main ‘Three parameters (arguments) are passed to main by the Borland C+ startup routine: arge, argo, and env. ‘argc, an integer, is the number of command-line arguments ‘passed to main, ‘margo is an array of pointers to strings (char *D. + Under 3.0 and higher versions of DOS, argof0] isthe full path name of the program being run. «+ Under versions of DOS before 3.0, argv{0] points to the null string (*). ‘+ argol1l points to the first string typed on the US command line after the program name. «+ argol2] points to the second string typed after the program + argofarge-1] points to the last argument passed to main + argolargel contains null An example program ‘men is also an array of pointers to strings. Each element of ol] holds a string of the form &sWAR=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. CADOS;C:\TOOLS; (for PATH) or YES (for 87). If you declare any of these parameters, you must declare them ‘exactly in the order given: arge, argo, eno. For example, the following are all valid declarations of main’s arguments: aia sain Gt arge) sain (it argc, char * argvi) tain(ént arge, char * argul}, char * eov()] 1 degal bet very eolikely */ The declaration soin{ist rge) is legal, bu it’s very unlikely that you would use argc in your program without also using the elements of arg. ‘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 argo are also available via the global variables _arge and Age. Here is an example that demonstrates a simple way of using these arguments passed to main, 1+ Poogran 9865.0 47 Hactude include fmt ange, char tarqy(], chat ‘env( 1) print ("The value of argo 19 td teat ange Drint£(*These are the 42 comand-Line arguments passed to” "iain: \ln'yarge) for (i= 0; 1 ¢ axger S41 ratf(* argvIsal: telat, iy argv) Print (*\athe environment string(e) on this aysten are:\ntn") for (i = 0; envtiy I= won; S64) Borland C++ Library Reference i i i | } | | | i I Wildcard ‘arguments peintg(* env[Sd]: Qe\aty 4 one(il0s ete 0 ’ ‘Suppose you run ARGS.EXE at the DOS prompt with the following command line: 2> ange firot_arg "ang 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 "arguneat 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 valve of arge is 7 ‘These are the 7 camand-line arguments passed to main: segy(0]+ ce \g0RLaNDE\ ARCS. argv(l]: first_arg axgv(2l: arg with blanks scgv(3]: 3 anit: | argv{S]: last but one aequ{6]: stop! ‘The enviroinent stringis) on this systen ar: exv(0]+ comspeo-6-\oneND.com I] PROMPTS 53 fnv{2] + Paruec:\SPRD¥T;C*\008;C:\pomLaNOe ‘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. (Command-line arguments containing wildcard characters can be expanded to al 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.OB} object file, which is included with Borland CH, (Once WILDARGS.OBf is linked into your program code, you can send wildcard arguments of the type ™." to your main function. ‘The argument will be expancled (in the argo array) toall files, (Chapter 1, The main function 5 ‘An example program Formats on THR. 290 the ‘sere Guise, ‘matching the wildcard mask. The maximum size of the argo array varies, depending on the amount of memory available in your heap. Ino 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 (..") are not expanded. ‘The following commands will compile the file ARGS.C and link it with the wildcard expansion module WILDARGS.OB, then run the resulting executable file ARGS.EXE: oc ARGS wILDARGS.082 AiGS C:\DORLANOC\TNCLIDE\Y A ct ‘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 inchade the entire path. The argument *C is not expanded as itis enclosed in quotes, In the IDE, simply specify a project file (from the project menu) that contains the following lines: wrtoanes. 083 ‘Then use the Run | Arguments option to set the command-line parameters. If you prefer the wildcard expansion to be the default, modify your standard C?.LIB library files to have WILDARGS.OB} inked ‘automatically. In order to accomplish that, remove SETARGV 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. Cand C++ libraries and WILDARGS.OB)): Lib ea caetasgy evttcarge thib © twslaaege lib ee -setargy Hwildargs tui ys wildargs Lib ch -setargy wwildarge 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 Programmers Guide), you must remember to explicitly declare main as aC type. Do this with the edecl keyword, ike this: deel nainlint exge, char * azgul), cbar * exept]} The value main returns ‘The value returned by main is the status 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) the status is 1 (Chapter 1. The main function 7 Allprogromming examples in ‘ins ehpler aren he onine ‘heb system. Tis mars you ‘ean easly copy thorn fom help ond poste them Info your fies. The run-time library This chapter contains a detailed description of each of the func- tions 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 ook up information about the free routine, you would look under free; there you would find a listing for free that sm summarizes what free does am gives the syntax for calling fr tells you which header file(s) contains the prototype for free gives a detailed description of how free is implemented and how it relates to the other memory-allocation routines lists other language compilers that include similar functions refers you to related Borland C+ functions ‘if appropriate, gives an example of how the function is used, or refers you to a function entry where there is an example ‘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. Borland C++ Library Reference Chapter 2, The run-time library 9 How to use function entries syntax. Remarks Return value See also Example 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. Di | Tis gives youthe decaraton yin or fnetion pranctersamesare | Iniclc Tee Ll nds tat ee armel onde mods cin ‘The function portability is indicated by marks in the appropriate columns. Any additional restrictions are discussed in the Remarks section, function(modifier parameterl mos available for this system available under this system compatible with Windows. EasyWin users should see ‘Appendix C, “Using EasyWin,” in the User’ Guide for information about using certain non-Windows compatible functions (like printf and scanf) 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. mix miiindows aust c mcs only ‘This section describes what function does, the parameters it takes, and any details you need to use function and the related routines listed. The value that function returns (if any) is given here. If funetion sets any global variables, their values are also listed. Routines related to function that you might want to read about are listed here. Ifa routine name contains an ellipsis (funename.... ..funcname, fune...name), it indicates that you should refer to a family of functions (for example, exec... refers to the entire family of exe functions: exec!, execle, execlp, execipe, execv, execve, exeovp, and execvpe). Jere you'll find @ anal sam possibly of related functions) .+/ progca showing the vee of function (and Borland C++ Library Reference ‘abort 5 abort Function Abnormally terminates a program. Syntax include void abort(void); E wie | wison | mare Tor ony ] a eet ama 1 Remarks abort writes a termination message (“Abnormal program termination”) on stderr, then aborts the program by a cal to_exit with exit code 3, Return value abort returns the exit code 3 to the parent process or to DOS. See also assert, atexit,exit,_exit, ralse, signal, spawn... Example ipcase Factade fae main(oie) 1 peintt Paling abort (a Bort); yetura 0; /* Mla is never reached */ , abs Function Retums the absolute value of an integer. Syntax Real version: Complex version: finelude include int abstint 2; double abs (complex 2); Fd foes [ep =] comporass [+ | o a Remarks abs returns the absolute value ofthe 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, he run-time library n abs If you want to use the abs function instead of the macro, include Fundet abs in your program, after the #include . Retum 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. Seealso cabs, complex, fabs, labs Example finciade eeelude nt aain¢vota) 1 lot number = -1234; print (*munber: ta absolute valves Ad\n", sunber, abe(aunber)) return 0; absread 2 Function Reads absolute disk sectors. Syntax #include int absread\int drive, int nsects, long lsect, void "buffer; wos | wi | wnt | war ow oy] al J Remarks 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 0x25 to read specific disk sectors drive = drive number to read (0 =A, 1 =B, ete) sects = number of sectors to read Isect = beginning logical sector number buffer = memory address where the data is to be read ‘The number of seclurs ty teat is linited tu 64K or the size of the buffer, whichever is smaller. Retumn value If itis successful, absread returns 0. (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 absurite, biosdisk Borland C++ Library Reference absread 5 Example firclude Finelude fenelade «dos. Hnelude Hotine socsres 512 nt main vote) tC unsigoed a nt iy jy sec char stet01; © drive letter: peta(eee) drive = tooper'ste(0]) ~ printt ("tater sector nunbe gots(ste)s sector + ato (ste): Af (absreadtdrive, 1, sector, abut) ! 0) | porror "Disk exer") exit (lls 1 peinte(C\aprive: te. for (i = 0; i < seosite; § AE (HL /16) = 20) | priate ("cess any tey to oo getehls printf (a): 4 rimee("o3ds *, 4 (= 07 4 € 16: Je) att ("02K *, buELS*HD) prime(nien for (= 0; 4 < 16; 300) tout) printe("tct, botli#))) flee piste (*. "1: pelate (ar retuen 0 Chapter 2, The run-time ibrary 3 abswrite abswrite Funetion Syntex Remarks Retum value See also access Writes absolute disk sectors. ffindude int abswrite(int drive, int nsects, long lect, void *buffer); : anew ys spd ser gorse pa rac Sun pos enone Be Far ene ese impoper awn oe fey drs, and FATS ast ues DO cap 25 tv speed sor drive = drive number to write to (0 = A, 1 =B, ete.) sects = number of sectors to write to Ikect = beginning logical sector number buffer = 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 buter, whichever is smaller. If itis successful, abswrite returns 0, (On error, the routine returns ~1 and sets the global variable errno to the value of the AX register returned by the system call absread, biosdisk Funetion Syntex Remarks Determines accessibility ofa file. include int access(const char "filename, int amode); Oe [wit | wes | ase [or iy access checks the file named by filename to determine ifit exists, and whether it can be read, written to, or executed. ‘The list of amode values is as follows: Botiand C++ Ubrary Reference Return value acos, acos! Function ‘Syntax. access 5 06 Check for read and write permission 04 Check for read permission 02 Check for write permission O1 Execute (ignored) 00 Check for existence of file Under DOS, all existing files have read access (amode equals 04), so 00 and (4 give the same result. In the same vein, amide 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. Ifthe 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 Path or file name not found EACCES Permission denied chmod, fstat, stat FHinelude ie int file orists {char *£ilenano); int main(voidh print *Does HOTEKIST.FIL exist: te\n" ‘ile_exists "NOTEEISTS.FIL*) 28S" : "No retucn 0; ) sexlete ener *tstenane) | retura (access(filerane, 0) = 0); ) Program output Calculates the arc cosine. Real versions: include double acos(double x); long double acosi(long double x); Complex version: include complex acos(complex 2); Chapter 2, The run-time library 6 ‘aces, acos! Reatacos Compiex acos Remarks Retum value See Also Example alloca Function 16 acos returns the are 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 acost must be in the range ~1 to 1, or else acos and acost return NAN and set the global variable errno to EDOM Domain error ‘The complex inverse cosine is defined by acos(:) =—ilog(z + i sqrt(1 -2*)) cos and acos! of a real argument between -1 and +1 returns a value in the range 0 to pi. Error handling for these routines can be modified through the functions matherr and_mathertl 3n2, complex, cos, matherr, sin, tan asin, Haclude Hinclade ath int main vote) i double result, x = 0.5 sesalt = cose)? printt("the arc cosine of Alf is $1e\0%, x, result); etarn 0; Allocates temporary stack space. ‘include void *alloca(size_t size); [aT oa [wear [ase [oo oir Borland C+ Library Reference alloca 5 Remarks alloca allocates size bytes on the stack; the allocated space is automatically freed up when the calling function exits. 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: hae “pr char ainay(1): uany(0) = 0 P= alloce(nbytest Retun value If enough stack space is available, alloca returns a pointer to the allocated. stack area. Otherwise, it returns NULL. See Also malloc Example jiociude finelade int allocmem(unsigned size, unsigned *segp); unsigned _dos_allocmem(unsigned size, unsigned *segp); allocmem and _dos_allocmem use the DOS system call Ox48 to allocate a block of free memory and return the segment address of the allocated block. size isthe 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 allocmem, if not enough room is available, no assignment is made to the word pointed to by segp. For _dos_allocmem, if not enough room is available, the size of the largest available block will be stored in the word pointed to by segp. Alllallocated blocks are paragraph-aligned. allocmem and_dos_allocmem cannot coexist with malloc. allocmem returns ~1 on success. In the event of error, llocmem returns a ‘number indicating the size in paragraphs of the largest available block. __dos_allocmem returns 0 on success, In the event of error, “dos_allocmem returns the DOS error code and sets the word pointed to Dy segp to the size in paragraphs of the largest available block. An error return from allocmem or _dos_allocmem sets the global variable “doserrno and sets the global variable errno to ENOMEM Not enough memory coreleft, freemem, malloc, setblock int main(voia f neigned int segp, may Borland C++ Llprary Reference lloemem, _dos_allocmem. H unsigned int efze = 68; /* (6416) = 2026 bytes */ int largest os allocnen, dos sctblock, and dos freemen. +/ if (_d03_allocnon(size, Drlnit (alloca. else ( persor "able to allocate block."}: ragraphe "available ie $o\e", oemp); ' if (dos setplock(size * 2, segp, éoasb) = 0) Printf ("Grew nosory block at sequent: &X\n", sesp) else { poeror("Uable to grow block. 9); Printe("Maxiaan nunber of pazagrephe’ available is tole", nasb); ' “os feeenenlcesp! 19 Use alloenen, setblock, and freemen. +/ Lf ((largest = allocmen(size, ssogp!) = -1) rinet{"alloceted nenory at sequent: tx\n", s0sp)s else | parror(Mnble to allocate B i (Maxinun qunber of paragraphs” ‘available is Sela", Largest) ' Af (largest = setblock\segp, size * 2)) =) print! ("Grex memory block at sogeent: Elo", seyp) ase { pecror("Ghable to grow block."); Peintt ("Maximon sunber of paragraphs” * available is tla", Largest]; : recoan|sgpl: 0 are Funetion Draws an are. Syntax. #include void far arc(int x, int y, int stangle, nt endangle, int radius); Chapter 2, The run-time brary 1° are: 20 Remarks Note Return value See also Example are draws a circular arc in the current drawing color centered at (x,y) with, a radius given by radius. The are travels from stangle to endangle. If stangle equals 0 and endangle equals 360, the call to are draws a complete circle. ‘The angle for arc is reckoned counterclockwise, with 0 degrees at o'clock, 90 degrees at 12 o'clock, and so on. ‘The linestyle parameter does not affect arcs, circles, ellipses, or pie slices. (Only the thickness parameter is used, Ifyou're using a CGA in high resolution mode or a monochrome graphics adapter, the examples in this book that show how to use graphics func- tions may not produce the expected results. If your system runs on a CGA ‘or monochrome adapter, pass the value 1 to those functions that alter the {ill or drawing color (setcolor, setfillstyle, and setlinestyle, for example), instead of a symbolic color constant (defined in graphics.h). None. circle, ellipse, fillelipse, getarccoords, getaspectratio, graphresult, pieslice, sector netude nelade cali. eelude fit maingvote) t request ootodetection */ driver = DETECT, quede, erzorcode; ids, iy: tangle = 5, endangle = 225; zadius = 100; 14 initialize graphics and local variables */ iniegraphisedeiver, agpode, (+ read result of Aaielalsation */ exrorcode ~ graphresult(}: if (errorcode '= gr0k) | /* an error occur ("Graphics erzor: 4s\3" prinef ("Press any key to balt!") etch Borland C+ Library Reference arg Funetion Syntax. Remarks Return value See aso are 5 idx = geemaeet) / 2: nidy = gotnary) 1 2: seteoloe(getmaxcolor()}: Pda are */ arcinida, mld, stangle, endangle, radius: 1 clean op 4 sete closegcaph()s retorn 0 Gives the angle of a number in the complex plane. include double argicomplex 2); Wes we | Winer | ST [Or nly 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 0. arg(x) returns atan2(imag(x), real(x). complex, norm, polar Hnclode nt main( void) double x= 3.1, y= 4.2 complex t = complexe tout << * has real part = * < real(a) <¢ *\ot out << * and imaginary part = * < inigic) << "ots cout << "2 has ceaplex conjugate = " char *asctime(const struct tm *tblock); asctime converts atime stored as a structure in *tblack to a 26-character string of the same form as the ctime string: un Sap 16 01:03:52 2972\0\0 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, 1, localtime, mktime, strftime, stime, time, include Helade ceeing > Haclade tine. int main (oie) i char stz[8017 (* sample Loading of tm structure */ tense = 1; /* Seconds */ cummin = 30; /* Winvtes +/ CNechowe 2 0r /4 tour 4/ = 22; 7 Day of the Month */ San / Monen +7 = 55; /* Yaar ~ does not include centory */ yf Day of the wosk +7 vtmydsy = 0; 7 Does not show in asctine */ ltuctadse = 0; J 1s Daylight SevTine J converts structure to aull terminated string + Borland C++ Library Reference asctime 5 steopy (ste, asctine(et)): print #("islat, ate); return 0 asin, asin! Function Calculates the arc sine, Syntax. Real versions include double asin(double x); ong double asinI(long double x); Complex version: ifinclude complex asin(complex x); os_[ WOR | viesor | Te | only Root asin Complex ain . Remarks asin of a real argument returns the arc sine of the input value, asin! is the long double version; it takes a long double argument and returns a long double result. Real arguments to asin and asin! must be in the range -1 to 1, or else asin and asin! return NAN and sets the global variable erro to EDOM — Domain error ‘The complex inverse sine is defined by asin(2) = -i* log(i* z+ sqrt -29) Return value asin and asin! 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 _mathertl Sa@ Also cos, alan, atan2, complex, cos, mather, sin, tan Example int main void) fl double result, x - 0.8 result priate he arc sin of #1f is 1F\n, x) result); Chapter 2, The run-time llorary 2 asin, asinl assert etuent0): Funetion syntax Remarks Retun value See also Example 24 Tests a condition and possibly aborts. include void assert(int test); assert is a macro that expands to an if statement; if fest evaluates fo zero, assert prints a message on stderr and aborts the program (by calling abort). assert prints this message: Assertion failed: test, file Filenae, line Linenua ‘The filename and linenumt listed in the message are the source file name and line number where the assert macro appears. Ifyou place the tefine NDE806 directive (“no debugging”) in the source code before the #include directive, the effect is to comment out the assert statement, None. abort Hnelude finelude servot TEN { int keys int valves hy 1* odd Stem to List, nate sure List is not moll *Y void additen(stroct TTEH *itenptr sesort(iUenptr {= MOLL: 1 ada ian to List */ ' nt main|void) Borland C++ Library Reference adaven(woLn)? return 0; Program output Assertion fi a: Stenpte t= MILL, fide C:\BC\ASSER?.C, 13 atan, atan! Function Calculates the arc tangent. Syntax. Real versions: Complex version: include #include double atan(double 2); ‘complex atan(complex 2) long double atani(long double x); otent | Reaiatan [= Complex ofan [ : Remarks _atan calculates the arc tangent of the input value, atan! is the long double version; it takes a long double argument and retums a long double result. ‘The complex inverse tangent is defined by atan(z) = -05 ilog((1 + i2)/(1~i2) Retum 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 matherr and _matherrl See Also acos, asin, atan2, complex, cos, matherr, sin, tan Example jinciude include ouble result, x = 0.5: result = atan(s) printf (The arc tangent of HE is S1f\n", x, resolth Chapter 2, The nun-fime itbrary 28 ‘atan2, atan2i roturn(0h ' atan2, atan2) Function Calculates the arc tangent of y/x. Syntax include double atan2(double y, double 2); long double atan2I(long double y, long double x); wee |] Winsor [ATE [Or ly catonar | a Remarks tan? returns the arc tangent of y/ it produces correct results even when the resulting angle is near pi/2.0r =pi/2 Ce near 0). Ifboth x and y are 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. Retum value atan2 and atan2I return a value in the range -pi to pi ‘or handling for these functions can be modified through the functions ‘matherr and _matherrl See Also acos, asin, atan, cos, matherr, sin, tan Example include eelude fmt main(void) f ouble result, x = 90.0, y = 15.05 printt ("the are tang nt ratio of WIE is 8Lf\n", (yx), result) atexit Function Registers termination function. % Borland C++ Library Reference Syntax Remarks Return value See also Example atof, atold Function atexit 5 include Int atexit(void (* fune)(void)); =T— atexit registers the function pointed to by fire as an exit function. Upon ‘normal termination of the program, exit calls (unc)0 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 om a last-in, first-out basis (that i, the last function registered is the first to be executed). atexit returns 0 on success and nonzero on failure (no space left to register the function). abort, exit, exit, spawn. elude void exit_{o1 ois} "eit fonction #1 on #2 called"); int sain void) tC 1 post exit func stenit exit J post exit function #2 */ atorit(exit_fr2); prints ("Done in main\o") retorn 0 Converts a string to a floating-point number. (Chapter 2, The run-time brary 7 attof, atold Syntax. Remarks Retun value See Also Example include double atoficonst char *s); ong double _atold(const char *s); Woe [Wk | Winer | ar [Ory atof converts a string pointed to by sto double; this function recognizes the character representation ofa floating-point number, made up of the following: ‘san optional string of tabs and spaces. ‘man optional sign. ‘ma string of digits and an optional decimal point (the digits can be on both sides of the decimal point). san optional ¢ or E followed by an optional signed integer. ‘The characters must match this generic format: {cohitespacel [ign {ddl dd] fe sign dad atof also recognizes +INF and -INF for plus and minus infinity, and 4NAN and -NAN for Not-2-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 toa Tong double. strlod and _strtold are similar to atot and _atold; they provide better error detection, and hence are preferred in some applications. 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), erm is set to ERANGE, and matherr (or _matherr) is not called. atol_atol. ecvt. fevt. gevt. scant. strtod Hota finclade int atoi(const char *s); TS] | wie [ mae oy Remarks tol converts a string pointed toby sto int atol recognizes (in the following order) san optional string of tabs and spaces man optional sign ma string of digi The characters must match this generic format fws] sn] fat} In this function, the first unrecognized character ends the conversion There are no provisions for overflow in atol (results are undefined). Refum value _atoi returns the converted value of the input string. Ifthe string cannot be converted to a number of the corresponding type (int), the retum value is, 0. See.also tof, atol, ecvt, fevt, gevt, scant, strtod Example jinciose Haclude i char "ote 1 = atol (stn) printt (string = 48 Integer = d\n", sty nls (Chapter 2, The run-time library a | atol Funetion Converts a string to a long Syntax include Tong atol(const char *s); Remarks atol converts the string pointed to by s to long. atol recognizes (in the following order) ‘man optional string of tabs and spaces ‘man optional sign ma string of digits ‘The characters must match this generic format: {ews [snl ddl In this function, the first unrecognized character ends the conversion. ‘There are no provisions for overflow in atol (results are undefined). Retun value aol returns the converted value of the input string. Ifthe string cannot be converted to a number of the corresponding type (long), atol returns 0. Seealso atof, atol, ecvt, fevt, gevt, scant, strtod, strtol,strtoul Example finctuse Hacluse ne maiatvoia) c og 2: char *Lete = "96768102 1 = atol (iste) printt (string = Ys Long = Sida", Iste, 2) return 0; bar Function Draws a two-dimensional bar. 30 Borland C++ Library Reference Syntax include include void far bar(int left, int fop, int right, int bottom); Remarks bar draws 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 0. “The upper left and lower right corners of the rectangle are given by (eft, top) and (right, bottom), respectively. The coordinates refer to pixels. Retum value None. See.also bardd, rectangle, setcolor, setfillstyle,setlinestyle Example finciose Hinclode Finelose nt main(voiah 1+ cequeat autodetection */ int mids, + snitdaliae graphs initoraphi emote, "1; /* read sosult of initialization */ ferroreose = gropheesul€ (1; exit) nidy = getmaxy() / 23 1 oop through the F411 patterns */ for (ieS0U20 FTUty A void far bar3dint lft, in op, int right, int bottom, int depth, int fofla); oe [mo | wean [ ware [ower : ! ! Remarks bard draws a three-dimensional rectangular bar, then fills it using the current fill pattern and fill color. Te three-dimensional outline ofthe bar is drawn in the current line style and color. The bar’ depth in pixels is given by depth. The topfiag parameter governs whether a three- dimensional top is put on the bar. If oplag 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 comers of the rectangle are given by (ef, {op) and (right, bottom), respectively. To calculate a typical depth for bar, take 25% ofthe width ofthe bar, like this: borSd(lett,top right button, (labtLefE)/,1)1 Retum value None. See.clso bar, rectangle, sotcolor, setflistyle, setinestyle Example fisciude ‘snclode tals. Hselose Hsctade dae sata(oid) 1 1m request sated ine giver = DETECT, quod, erroceoe fine mids, my 4 2 Borland C++ Library Reference bed Function syntax Remarks barsd (+ initialize graphics and 1 Iniegrophisedeiver, sgnode, 1+ read reult of initialseation +7 (ecrorcode U1 en exzor occurred */ oraphics error: te\n", grapherrorneg (erroreode); ress any key to halt etch exits 1 ride = getran() / 27 dy = getmanyt) 1 2 (#* terminate with an error code +/ h the €512 patterns #/ THOEM@Ty PILL, A bed bedtint x); bed bed(double x); bed bed(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 11075 to 1x 108, Chapter 2, The run-time library 33 bed Return value See also Example bdos Funetion Syntax Remarks 34 Use the function real to convert a bed number back toa float, double, or ong 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. ‘The bed equivalent of the given number. real include Glosteesn > include <4. int mainjvois) f bod a = bod(a/3,2); // a third, rounded to nearest penny Goable x = 10000.0; // ten thousend dolters cout << “share of fortune = 5 int bdos(int dosfun, unsigned dosdx, unsigned dosal); wo [oak | wow [ware [error = eee I lbdos 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 dosfen is defined in your DOS reference manuals. dosdx is the value of register DX. dosal is the value of register AL. Borland C++ Library Reference Return value “The return value of bdos is the value of AX set by the system call. Se0 azo bdosptr, gninterrupt, int, nt86x, indo, intdosx Example jincude Hines coe 1 gg carrnt drive a8 10, “8%, 1 1 1 get curcont disk 380) 3 os AP strive = boa(Ol9, 0, aa + ene ) ioe miniota) { fet 1 Program output thn catrest drive 6 bdosptr Function Accesses DOS system calls. Synfox tinclude int bdosptrtin dosfun, void “argument, unsigned dosal; Es Remarks bdosptr provides direct access to many ofthe DOS system calls. See your DOS reference manuals for details of each system call For system calls that require an integer argument, use bdo; if they require a pointer argument, ase bdosptr. In the large data models (compact, large, and huge) itis important to use bdosptr for system calls that requirea pointer asthe call argument. In the small data models, the argument parameter to bdospt specifies DX; in the large data models it gives the DSDX values tobe used by the system call Chapter 2 The run-time terary 28 bdosptr Return value See also Example bioscom Aosfun is defined in your DOS reference manuals. dosal isthe value of register AL The return value of bdosptr is the value of AX on success or ~1 on failure. On failure, the global variables errao and _daserrno are set bbdos, geninterrupt,int86, int86x, intdos, intdosx. fnclude Finelude + got cuerent dive a5 19", '8%, #7 char correst_drive(void) 1 1* got currant disk as 0, 3)... #/ curdrive = béos (0x18, 6, 0) return('W + cordriv ft main(vota printf ("The eustent drive Le tec\n", caer xn 0 Function Syntax Remarks Performs serial I/O. include int bioscom(int cmd, char abyte int port); we] wa | weer [ast [Or oar bloscom performs various RS-232 communications over the I/O port given in port A port value of 0 corresponds to COMI, 1 corresponds to COM2, and so forth. ‘The value of cmd can be one of the following: 0 Sets the communications parameters to the value in abyte. 1 Sends the character in abyfe out over the communications line 2. Receives a character from the communications line. Borland C++ Ubrary Reference bioscom 3 Returns the current status of the communications port. byte is a combination of the following bits (one value is selected from each of the groups): x02 7 data bits, 0x00 110baud 0x03 8 data bits, 0x20 150baud 0x40 300 baud 0x00 1 stop bit 0x60 600 baud 0x04 2stop bits 0x80 1200 baud 0x00 No parity OxAO 2400 baud 0x08 Odd parity OxCO 4800 baud OxI8 Even parity OxE0 9600 baud For example, a value of OxEB (0xEO 0x08 | 0x00 0x03) for abyte sets the communications port to 9600 baud, odd parity, 1 stop bit, and 8 data bits. bloscom uses the BIOS 0x14 interrupt. Retum value For all values of cmd, bloscom returns a 16-bit integer, of which the upper 8bbits 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 Timeout Bit 14 Transmit shift register empty Bit 13 Transmit holding register empty Bit 12 Break detect Bit 11 Framing error Bit 10 Parity error Bit 9 Overrun error Bit 8 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, ifa 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. Ifan error occurs, at least one of the upper bits is set to 1. Ifno upper bits are set to 1, 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: Bit7 Received line signal detect Bit6 Ring indicator Bit5 Dataset ready Bit Clear to send Bit3_ Change in receive line signal detector Bit2 Trailing edge ring detector Chapter 2, The run-time library a bioscom Bit1 Change in data set ready Bit Change in clear to send Example jinciode inclu fotine com 0 define DARA READY 04100 define TRUE Hdetize Faust 0 define SEPTINGS (0x60 | Ox12 | 0300 | 0x00) int main(voia) i int Any out, status, DOME » FRESE: bioscom(0, SSPETRES, col) prints". BIOSCOM [E80] to exit ...\0")2 hile (1008) status = bloscoa(3, 0, cOKL}; if fatatus & DHEA READY 4£ ((oat = bioscoml2, 0, CoML) « O37F) = 0} puten out) af qani oy 36 (Cin = getenO) == etB") ote = ERE bloscontl, in, com) , ' return 0 1 bios_disk Function Issues BIOS disk drive services Syntax. #include unsigned bios disk(unsigned cmd, struct diskinfo_t *dinfo); Remarks _bios_disk uses interrupt 0x13 to issue disk operations directly to the 38 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 in bios.h) has the following format: Borland C++ Library Reference k ~bios.disk steuct diskingo.t nsigned drive, hea, void far "buffer? ck, sector, sect drive is a number that specifies which disk drive is to be used: 0 for the first floppy disk drive, I for the second floppy disk drive, 2 for the third, and so on. For hard disk drives, a drive value of 0x80 specifies the first rive, 0x81 specifies the second, 0x82 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 may or may not be needed. ‘The possible values for cma (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 Retums 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 0 and, the low byte will contain the number of sectors. If an error occurred, the high byte of the return value will have one of the following values: 0x01 Bad command. 0x02 Address mark not found. 0x03 Attempt to write to write-protected disk. 0x04 Sector not found. Ox05 Reset failed (hard dish. 306 Disk changed since last operation. 0x07 ‘parameter activity a0 Birstnemory access (DMA) overrun, oe _Attempt to perform DMA across 64K boundary OXOA Bad sector detected. x0B Bad track detected. OX0C Unsupported track, Ox10 Bad CRC/ECC on disk read. Oxl] CRC/ECC corrected data error. 0x20 Controller has failed. Chapter 2, ihe sun-time lorary 9 bios disk 0x40 Seek operation failed. 0x80 Attachment failed to respond. OxAA Drive not ready (hard disk only). OxBB Undefined error occurred (hard disk only). OxCC Write fault occurred, OxED Status error. OXEF 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 bby 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, Retun value _bios_disk returns the value of the AX register set by the INT 0x13 BIOS, all See Also absread, absurite, biosdisk Example jinclude include int main void) ( struct disklafo t diate; int results static char dbvf {512 Alnto.deive = 0; /* drive number for A: */ intovhead = 0; /* disk head munber 47 dinfo.track = 0; /* track umber */ Ainto.sector = 1; /* syctor nunber */ ns = 1; / sector count */ tout; /* data buffer */ o Borland C++ Library Reference bios_disk 46 {{reoute « Oxff00) = 0) | prinef(*0isk read fram A: successful. \2") printE("iret three bytes read are Or402s 01802x Ox1022\3", oO) & Ont, abot [1] & Oxff, abuf(2] & OxE); 1 else printer retuen cannot ead drive A, status = OxtQZr\n", result biosdisk Function Issues BIOS disk drive services. Syntax #include int biosdisk(int cmd, int drive, int head, int track, int sector, int nsects, void *buffer); Remarks _biosdisk uses interrupt 0x13 to issue disk operations directly to the BIOS. drive is a number that specifies which disk drive isto be used: 0 for the first loppy disk drive, | for the second floppy disk drive, 2 for the third, and so on. For hard disk drives, a drive value of 0x80 specifies the first drive, 0x81 specifies the second, 0x82 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. nid indicates the operation to perform. Depending on the value of cmd, the other parameters may or may not be needed. Here are the possible values for cmd for the IBM PC, XT, AT, or PS/2, or any compatible system: 0 Revels dick eystem, forcing the drive controller to do a hard reset, Allother parameters are ignored. 1. Returns the status of the last disk operation. All other parameters are ignored. 2 Reacls 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 tur-time ibrary a 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 busfer. 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 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 ofthis 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 along 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. See also 13 Alternates disk reset Example 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. tee biosdisk operates below the level of files on raw sectors. It can destroy ile contents and directories on a hard disk. Retum value biosdisk retumsa status byte composed of the following bits: x00 oxo 2 Operation successful. Bad command, Borland C++ Library Reference biosdisk 0x02 Address mark not found. 0x03 Attempt to write to write-protected disk. Ox04 Sector not found. 0x05 Reset failed (hard disk. x06 Disk changed since last operation. 0x07 Drive parameter activity failed. 0x08 Direct memory access (OMA) overrun, (0x09 Attempt to perform DMA across 64K boundary. Ox0A Bad sector detected. OxOB Bad track detected, Ox0C__ Unsupported track. x10 Bad CRC/ECC on disk read. Ox11CRC/ECC corrected data error. 0x20 Controller has failed. 0x40 Seek operation failed, 0x80 Attachment failed to respond. OxAA Drive not ready (hard disk only). OxBB Undefined error occurred (hard disk only). OxCC Write fault occurred. OxE0 Status error. OxEF 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. absread, abswrite include include int min¢vose) t eetine 00 Hoot ine DRIVE eetine HE 1+ saad sector comand */ drive number for A: */ > disk bead cunber +7 79 crack umber #/ 7 sector number */ 1 geetor count +7 sot result char boffer(S12) print ("Attempting to read from drive A:\n"l; ediak (MD, DAIVE, HERD, TRACK, SBCT, Dy butter) ve Be fi attempt to read from (Chapter 2, The run-time library “3 biosdisk return 0; biosequip Function Checks equipment. Syntax #include cbios.h> int biosequip(void); | WH | Widoes | wsrt [oo oly =f ‘ Remarks blosequip uses BIOS interrupt Ox11 to return an integer describing the equipment connected to the system. Retum value 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 printer printers 1123 printers Bit13 Serial printer attached Bit12 Game I/O attached Dosen sees two Bits 11 Number of COM ports ‘pots but con be 2 pushed fo soe four ieee ‘ne BM F5/2.6an 001 = 1 port 1900p 10 eight 010 =2 ports O11 =3 ports 100 = 4 ports 101 =5 ports 110 =6 ports 111 =7 ports Bit Direct memory access (DMA) (0= 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 4 Borland C++ Library Reference biosequip 10 =3 drives 1 =4 drives, only if bit 0s 1 BIt4-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 Bit1 Floating-point coprocessor BitO Boot from disk Example inciude finclide {detine 00, PROCESSOR MASK 010002 int main void) f int ogup_ chock: {J got tho current omuipnent configuration */ tule. check = blosequip(); 1% check to see if thece Ls a coprocessor installed 4/ Af (equlp_chack & cD PROCESSOR SR) rnt#[*Thore is @ math coprocessor installed \n") print® ("No math coprocessor installed.\o"); return 0 bios_equiplist Function Checks equipment. Syntax include unsigned _bios_equiplist(void); Tos [ WH | Wintes | mG [Oy (Chapter 2. The run-time lrary 45 bios equiplist Remarks Return value OS only sees two Bots But can be pushed fo see four ‘he BM PS/2 can 1$80.up fo eight Example __blos_equiplist uses BIOS interrupt Ox11 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 1415 Numb of paral printers installed punters Ot = printer 10= 2 printers 1123 printers B19 Serial printer ata Bie 1/0 attached Bits 0-11 Nats ofCOM ports Opors oot =! Bort 510 =2 ports OL = 3 ports 100 =4 ports 101 =5 ports 110=6 ports 111 =7 ports site Diet memory aces (OMA) Machine has DMA 1 Machine doesnot have DMA; for example, PC Biis6-7 Number of disk drives O=Tarive drives drives drives only ifbit is 1 B45 Initial video mode Bis 23 Bit Floating-point coprocessor Bio Boot fom disk AHpelude jelude int bioskey(int cmd); Remarks _bloskey performs various keyboard operations using BIOS interrupt Ox16 The parameter om determines the exact operation Retum value The value returned by bloskey depends on the task it performs, determined by the value of mi: 0 Ifthe lower 8 bits are nonzero, bloskey returms the ASCII charac- ter forthe next keystroke waiting in the queue or the next key pressed at the keyboard. Ifthe lower 8 bils are 2er0, 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 Ox has 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 asa cmd value of zero, 2 Requests the current shift key status. The value is obtained by ORing the following values together: Chapter 2, The runtime library a bioskey Example Bit? 0x80——_Inserton Bité Ox. Capson BitS —020—_NumLockon Bit4 —Ox10_——SeralLockon Bit3 O08 Atpressed Bit2 —Ox0d_——Crpressed Bitl —Ox02_—= Shitpressed Hinelade Hinelude Hnelude Hdotine fica 0x01 define 17 0x02 Adotlne cre, 0x04 Mdetine ALT 0x08 sat maiatvoss) tl nt key, modi f hide (bioskey Jon 2 saturn 0 un ans on 0 returns the Rey that is waiting */ ockey (0) ction 2 to deternine Af shift keys axe used */ = biostey(2h7 Sf (aoaifiers « aici Sf (aodifiers & (22%) 8 & CTRL} Sf (andifiers « als) printe("l" /* print out the c Af Gener & O9F7)) printe("/4e"\a", key): print ("HO28\8", retare 0; Borland C++ Ubrary Reference blos_keybrd blos_keybrd Function Keyboard interface, using BIOS services directly Syntax #include tunsigned bios_keybrd(unsigned ema); : | Remarks _bios_keybrd performs various keyboard operations using BIOS interrupt ‘16. The parameter cmd determines the exact operation Return volue ‘The value retumed by_bios_Keybrd depends onthe task it performs, determined by the value of end (defined in bios: _KEYBRD_READ Ifthe ower 8 bits are nonzero,_bigs_keybrd returns the ASCII charac ter forthe next keystroke waiting in the queue or the next key pressed atthe keyboard. Ifthe lower 8 bis are zero, the upper 8 bits are the extended keyboard codes defined in the IBM PC ecinical Reference Manual NKEYBRD_READ Use this value instead of KEYBRD_READY to read the keyboard codes for enhanced Keyboards, which have additonal cursor and fanction Keys. _KEYBRD_READY ‘This tests whethera keystroke is available to be read. A return value of zero means no key is available. The return value is OxFFFF (1) if Cit {ik has been pressed, Otherwise the vale of the next keystroke is returned, as described in - KEYBRD_READ (above), The keystroke itself is kept to be etumed by the next call to_ bios. KeYbrd that has a cmd value of KEYBRD_READ or NKEYBRD_READ. _NKEYDRD_READY Use this value to check the status of enhanced keyboards, which have additional cursor and function keys. _KEYBRD_SHIFTSTATUS Request the current shift key status. The value will contain an OR of zero oF more ofthe following values: Bit? 0x60——Insrton Chapter? the un-time lexary ° -blos_keybrd Example Bit6 Bit Bitd Bit3 it 2 Bit 1 Bit 0 ox40 0x20 Ox10 0x08 Ox04 x02 ox01 NKEYBRD_SHIFISTATUS Use this value instead of KEYBRD_SHIFTSTATUS 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_SHIFTSTATUS, and additionally, any of the following bits: Bit 15 Bit it Bit 13 Bit 12 Bit 11 Bit 10, Bits Bits include ceo. include ioe. Hnelude Hdetine BGI? Ox0L Heefine LEFT 0x02 Haatine Crm O204 Neetine AAT One nt nain void) Snt bey, ooditiers: 1+ wait until a key is pressed */ 12 (bios keybrdREYBRD READY) == 0}; (+ Eotch the key thot ia walt kay = _bloe_keybra(_HBY@90 READ); Sf (roaitsers 4 t42t) 4f (nodifiers & CTL) ‘0x8000 0x4000 0x2000 ox1000 0x0800 Ox0400 0x0200 Ox0100 Right Shit pressed Reg presced tum Lock pressed Seal Lok pressed Right Atpressed Cif pressed se Left Cir pressed Borland C++ Library Reference biosmemory Af (aoditiers 6 aL2) print printe("" 1 mut) 1 print out the cbacecter read +/ Af Uisainur(key © O8F7)) rethra 0 -bios_keybrd Function Returns memory size. Syntax include int biosmemory(void); Remarks biosmemory returns the size of RAM memory using BIOS interrupt 0x12. This does not include display adapter memory, extended memory, or expanded memory. Rotum value biosmemory returns the size of RAM memory in 1K blocks, Example jinciude Hnclade int main void) nonocy size printf size = Baki", menory size return 0; foemanory(); /* returns value op to 640K */ _bios_memsize Function Returns memory size. Syntax #include unsigned _bios_memsize(void); (Chapter 2, The run-time brary 8 _bios_memsize Remarks Retun value Example biosprint arlene een __blos_memsize returns the size of RAM memory using BIOS interrupt x12. This does not include display adapter memory, extended memory, or expanded memory. _blos_memsize returns the size of RAM memory in 1K blocks. inelude int main void) C unsigned nenory_size: eoory size = _bioe mensize(); /* returns value up to 640K */ printt(aad size = Sarto", manozy aise); return Function syntax Remarks Retum value 2 Printer I/O using BIOS services directly. include int biosprint{int cmd, int abyt, int port); biosprint performs various printer functions on the printer identified by the parameter port using BIOS interrupt 0x17. ‘A port value of 0 corresponds to LPT; port value of 1 corresponds to LPT2; and so on. “The value of em can be one of the following: Prints the character i ulyle 1 _ Initializes the printer port. 2 Reads the printer status. The value of abyte can be 0 to 255. ‘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 Example bios_printer Funetion syntax Remarks biosprint BitO 0x01 Device time out Bit3 0x08 1/Ocrror Bit 0x10 Selected Bit5 0x20 Outof paper Bité 0x40 Acknowledge Bit7 0x80 Not busy include ‘includ Aixclude int min (void) i ‘detine STNUS 2 /* printer status comand */ ne PORTWIM 0 /* port sunber for LPT. */ (Blease thin off your pela poten: Status = blogprint STATUS, abyte, PORE Af (status ¢ 0x01) vice tine out.\8"); (status 6 0x08 nt £(*1/0 exror.\a"h: Af (status 6 0110) printf Selected. \n"); Af (otatas 6 00 printe (ost Af (otatus 6 Ox Printe "acknoeledge\ 4f (otatus 0x80) priate Mot basy.\0"); return 0; rege any hey to cont inueto®) paper. |) Printer I/O using BIOS services directly. include unsigned _bios_printer(int cmd, int por, int abyte); _blos_printer performs various printer functions on the printer identified by the parameter port using BIOS interrupt Ox17. Chapter 2, The run-time library o ~bios_printer Retum value Example A port value of 0 corresponds to LPT1; a port value of I corresponds to LPT2; and so on. ‘The value of cmd can be one of the following values (defined in bios.h): _PRINTER_WRITE Prints the character in abyle, The value of abyle can be 0 to 255, Initializes the printer port. The abyle argument is ignored. _PRINTER_INIT 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 x01 Device time out Bit3 0x08 1/Ocerror Bit Ox10_— Selected Bit5 0x20 Out of paper Bit 0x40. Acknowledge Bit? 0x80 Not busy Hincluae Hizcluse Haclods ioe. int nain void} unsigned status, abyte = 0; printe(*Plesee turn off your printer. Press any key to contings\o"?7 geten status = bios printer( PRINTER STATUS, PORE, abyt 4 (states & G0) peinte Device tine out. (0%); sf Istatus & 028) printf (*I/0 error-\a") Le (status 6 0310) printf ("Selected.\o"); [status & 0:20) Borland C++ Library Reference -bios_serialcom bios_serialcom Function syntax Remarks Performs serial 1/0. 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 COMI, 1 corresponds to COM2, and so forth ‘The value of end can be one ofthe following values (defined in bios.h): COMINIT Sets the communications parameters to the value in byte Sends the character in abyte out over the communications line. -COM_SEND Receives a character from the communications line. The abyte argument is ignored. -COM_RECEIVE COM STATUS Returns the current status of the communications port. The abyle argument is ignored. ‘When cmd is_COM_INIT, abyle is a OR combination of the following bits: Select only one of these: _COM_CHR7 =COM_CHR8 Select only one of these: _COM._STOPI ‘STOP 7 data bits 8 data bits 1 stop bit 2stop bits Select only one of these: COM_NOPARITY -COM_ODDPARITY ‘COM_EVENPARITY Select only one of these: _COM_110 No parity (Odd parity Even parity 10 baud Chapter 2, The run-time library 5 bios serialeom Retum value Example COM_150 150 baud =COM_300 300 baud —COM_600 600 baud COM_1200 1200 baud “Com_2400 2400 baud COM_4800 4800 baud COM_9600 9600 baud For example, a value of (_COM_9600 | _COM_ODDPARITY | COM STOP1 | _COM_CHR8 ) for abyte sets the communications port to 9600 baud, odd parity, I stop bit, and 8 data bits. _bios_serialcom uses the BIOS OxI4 interrupt. ee ee ee Soaps once ete eee gem eee re ee ee aeene te eee BIS Tinea Be Trae rp oy mel ares Bid rosiacees BU Boing Be oe He Some 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, ifa 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, a least one of the "upper bits is set to 1. Ifno upper bits are set to 1, the byte was received without error With a cmd value of COM_INIT or COM_STATUS, the return value has the upper bits set as defined, and the lower bits are defined as follows: Bit7 Received line signal detect Bite Ring indicator Bit Datesct ready Bid Cleartosend Bild Change in receive ine signal detector Bit2 Trailing edge ring detector Bit Change in datas ready BitO Changein clear to send finctade tiselude Borland C++ Ubrary Reference biostime Funetion syntax Remarks Retun value bios seriaicom faetine cont 0 foefine DATA READY Oxi00 feline TUE fefine PSE 0 feetine SEPTTAGS (_COM_1200 | _cOKCHR? | _com sToP1 | _com norRREPY) Sat man (vos) t nsignod in, ont, bios serialcon(_coaLTH, cota, SEIET¥GS); Speinte(*... _BI6S SERIALCOM [BSC] to exit ...\e\o"); for iil { statue = bios serialean| COM STATUS, cit, 0}; Lf (status « DARA READY SE ((out = bios serialcom|_COM RECEIVE, COM, 6) 6 Ox7F) = 0) pateh(ost) af genic) | 5f (Gin = gota) serialcon(_004 S880, OOM, iol 8") Reads or sets the BIOS timer. fiinclude long biostime(int cmd, long newtime); Be [WH | Weis | STC [Or oy biostime either reads or sets the BIOS timer. This isa timer counting ticks since midnight at a rate of roughly 18.2 ticks per second. blostime uses BIOS interrupt Ox1A. If cmd equals 0, blostime returns the current value of the timer. If cmd equals 1, the timer is set to the long value in newtime. When biostime reads the BIOS timer (cmd = 0), it returns the timers current value, (Chapter 2, The eur-fime rary 7 biostime Example Hinelude eos. Hineluds cine. ‘inclu rain(vold} ong bios tne elesee()s print? ("The number of clock ticks eince nidnlght Le ‘he nunber of seconds eince aidolght is:\e\3"); the runber of minutes since nidnight is:\x\n") Cprinti (Me nuber of Hours since misnight 1o:\e\n"); print (*\riaPress any key to quits"): wbLLebait (1) | bios tine = biostine[0, 01); getony 60, eprint 0", bi sotony (50, 21 eprint (SAE, biog tine / Cla T gptony (9, 315 eprint ‘otony (50, 1) intl (MAE, Bios tine (CUM TCK / 3600}: ime); KIOK 6 return 07 bios_timeofday Function syntax Remarks Reads or sets the BIOS timer. include ‘unsigned _bios_timeofday(int cmd, long *timep); bblos_timeofday either reads or sets the BIOS timer. This isa timer counting ticks since midnight ata rate of roughly 18.2 ticks per second. __blos_timeotday uses BIOS interrupt Ox1A. ‘The cmd parameter can be either of the following values: _TIME_GETCLOCK The functions stores the current BIOS timer value into the location pointed to by timep. Ifthe timer has not been read or written since midnight, the Borland Cr+ Library Reference _TIME_SETCLOCK bios fimeofday function returns 1. Otherwise, the function returns oO ‘The function sets the BIOS timer to the long value pointed to by timep. ‘The function does not return a value. Return value The_bios_timeotday returns the value in AX that was set by the BIOS timer call Example tincluse Hnciode Hineluse ft nata(vois) ' tong bios tines eleser(l? cprinte(the ember of clock ticks since midniaht ds:\r\a")s cprinté ("Me rober of eesonds aince midnight is:\r\n")s te number of minstee since nidnight a-\r\a"): the nenker of hours since aidnight is:\z\a"); cpeinte (*\rlaProse any key to uit whide(Hapi () | “bios tineofday TINE GETCLOCE, ei Gotoxg (50, 102 bios tine) gotony (50, 232 pELAtE("AE", blow time / CLK TCH)? ork Function Changes data-segment space allocation. Syntax. #include int brk(void ‘addr; Wins [ aS e [Omir (Chapter 2, The run-time rary bik Remarks _brk dynamically changes the amount of space allocated to the calling program’ heap. The change is made by resetting the program’s break ‘ule, 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 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 0. On failure, this, function returns a value of -1 and the global variable errno is set to ENOMEM _ Not enough memory See also corelett, sbrk Example include include Return value. nt main(void) 7 See also ‘changing allocation with bekO)\a") Example: har *} malloc(2}; printf "Before bekt) call: Su bytes free\a", coreleft )); 00015 After bri) call: Siu bytes feee\n", corelefe )}: bsearch Function Binary search of an array. Syntax #include void “bsearch(const void *key, const void *base, size_t nelem, size t width, int (‘femp)(const voud *, const void); Cs Remarks 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. Ino match is found, bsearch returns 0. Note that because this sa binary search, the fist matching entry is not necessarily, the first entry in the table The type sizes defined as an unsigned integer. selon gives the number of elements inthe table. swath specifies the number of bytes in each table entry. ‘The comparison routine *femp is called with two arguments: een! and len. Each argument points to an item to be compared. The comparison function compares each ofthe pointed-to items elem and "elem, and returns an integer based on the results of the comparison. For bsearch, the “emp return value is, Oif lent > Yelem2 boearch returns the address ofthe first entry in the table that matches the search key. Ifo match is found, beearch returns 0. Hind, Isearch, qsort include Hinelude typadet st (pte fonst void, const void); fetine MELINS are) (eizeot (ars) / sizeof(ere(0))) 1 62, 800, 3 int = 1128, romaezay| 45, 5 nt rumerie (const Ant *ply const int #2) retorn(tpl ~ Apragna azgoused nt lookup int key) fe ye cast of (Ant [anst void *,const void risnatch error at compile Line */ tempt = (iat +) beeareh (Ghey, numa sizeof (nt) , ) is needed to avoid a type su (eonarsay}, pemeri); return (temper f= WL); 1 nt sain(vote) Chapter 2, The run-time library 6 cabs, cabs! Function Syntax Retun value £6 eotep 512) printf("5L2 is in the table.\n"l; else peieet(VSi2 ise’t in the table.\o") return 0; Calculates the absolute value of complex number. #indlude double cabs(struct complex 2); long double cabsl(struct _complexl z); cabs is a macro that calculates the absolute value of a complex number. zz isa structure with type complex; the structure is defined in math.h as steact complex double wy ‘where x isthe real part, and y is the imaginary part. Calling cabs is equivalent to calling sqrt with the real and imaginary ‘components of as shown here: eattlean * tax bay * yh ‘cabsl is the long double version; it takes aa structure with type complex! asan argument, and returns a long double result. The structure is defined. inmathhas struct _carplend ong double x, vi h If you are using C++, use the complex type defined in complex.h, and the function abs. ‘cabs (or cabsi) returns the absolute value of 2, a double. On overflow, ‘cabs (or cabs!) returns HUGE_VAL (or LHUGE_VAL) and sets the ¢global variable errno to Borland C++ Library Reference calloc See Also Example Function ‘cabs, cabs! RANGE Result out of range Error handling for these functions can be modified through the functions ‘matherr and_mathertl. abs, complex, fabs, labs, matherr include Hnelade coat. Hifd0€ _oplusploe incTode feoait Hitdet _cplusplos / void prlst_sbstvoia) C SE CHS, vse clase complex */ complex (1-0, 2.0) double abeval nek 4.2145 Se 42er, real{z}, ioagt), absvel); folse /* Function below és for C (and not cH). */ wold prine_abs (void) oable abeval 2x20; ny = 10 saval = cabeia): rte absolute value of $.2hfi 8.216) 49 &.21¢%, 2eky 2p absvall fendi nt sala void) c print_eba() Allocates main memory. (Chapter 2, The run-time library 6 calloc syntax Remarks Return value See ako Example fiinclude void *calloc(size_t mites, size_t size); ealloc 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. Al the space between the end of the data segment and the top of the program stack is availabe for use inthe smal data models (tiny, small, and medium), except fora small margin immediately before the top of the stack. This margin is intended to allow some room or the application to grow on the stack, plus a small amount needed by DOS. In the large data models (compact, lange, 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 items xsize. The block is cleared to 0. If you want to allocate a block larger than 64K, you must use farcalloe. calloc returns a pointer to the newly allocated block. If not enough space exists for the new block or nitems or size is 0, ealloe returns mull. {farcalloc, free, malloc, realloc Hiaciude Hiacluse ‘Naclude nt main vid) har *) ealloo(l0, sizeof (cha cope stropy ste, "ello": Jello" into string */ 1 display string */ Print ("Sering is tela", ste + t000 memory */ freo(sts}: return 0; Borland C++ Library Reference cell, ceill ceil, ceill Function Rounds up. Syntax include double ceil(double x); Jong double ceili(long double x); cell naa cell . Remarks ceil finds the smallest integer not less than x. celll is the long double version; it takes a long double argument and retums a long double result. Relum value These functions return the integer found as a double (cell) or a long double (ceil) See Also floor, fmod Example include include sea. int sain void) fi double dov, up» munber = 123.54 oor bee 2 mbes); ‘original number 45.21E\a", number) yer rounded down 35.21¢\n", ova) mmnber rounded up §5.21E\n", up) return 0 ' _c_exit Function Perform exit cleanup without terminating the program, Syntax #include void _¢ _ exit(void); Chapter 2, The sun-time itbrary cexit co [or [wm = [ * a | Remarks _¢_exit performs the same cleanup as_exit, except that it does not Remarks _cexit performs the same cleanup as ext, except that it does not close files ‘erminate the calling process Interrupt vectors altered by the startup code br terminate the calling process. Buffered output (waiting to be output) is, are restored; no other cleanup is performed. ‘written, any registered “exit functions” (posted with atexit) are called, and oe interrupt vectors altered by the startup code are restored. See Also abort, atexit,_coxit,exec...,exit,_exit,_dos_keep, signal, spawn... Ss a a ext, signal, spawn. i. _— ‘See Also abort, atexit,_¢ exit, exec...,exit,_exit,_dos_keep, signal, spay include Example finciude Hines Hoetade nos <3o8.0> Fnelade 5 neta ( saint) ne £0: i char os ine 4; SE ((ta = opent™_eentct0_ FOO} < AF ( char &: printt{"onable to open ¢ exit.e for reading\a"l: 6 ((fd = opent*cexit.ct,0 MINN) < 0} ( return printf (tinabie to open _cexit.c for readiog\e"l: ) zeturn 1: Sf (eendtta,ce.) = ' rintf("Unable to read fron pen file handle 4d before _c exit, fz Af (eeadttdyge,1) 12 1) ole Printf ("Unable to reed fron open file handle Ad before cenit, fd; rintéttSuccessfully read fron open file handle 4d before _c exit\nt,f8); se print "otercopt ozo vector Before -c est = Apo", dot gece (0) rintf{*Suocessfolly read fron open file handle fd before _cexitn'y fas Fe exit (i print (nterrupe ero veotor betoce -cext = Apa, doe getvace(0))7 FE (eendtta,ces) t= 1) oexit i)? Print (nable to rod from open file handle Ad after _c exit (3): TF teesdttasee,2) t= 1) else printe ("Unable to feed fron open file handle Md after _corit\n £8); einté(*Successfully read fron open file Mantle 84 after _c exit, fl; se printf ("interrupt zero vector after exit = Afp\a", dos getvect (0) print SaccetsEoly read from open file handle td after _cext\n" fds retain 0; point (nteceape txo vector after “cexit = pia, doe getvact(0))) H return 0; 1 _cexit cgets Function Perform exit cleanup without terminating the program. ee Function Readsa string from the console. void _cexit(void); Syntax #include char tegets(char "tr; 6 Borland C++ Ubrary Reference Chapter 2, The run-time liorary o cgets Remarks Return value See also Example ‘ogets reads a string of characters from the console, storing the string (and the string length) in the location pointed to by str. ‘gets reads characters until it encounters a carriage-return lineleed (CR/LP) combination, or until the maximum allowable number of characters have been read. If egets reads a carriage return/linefeed combination, it replaces the combination with a \0 (null terminator) before storing the string, Before egets is called, set sr{0] 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 ust be at least str{0] plus 2 bytes long (On success, egets returns a pointer to str(2]. puts, fgets, getch, getche, gets Huclude include sain) 1% thece's space for #0 characts butter(0) = 8 printe("Input soos chars:"I; p= ogets butter prlote"\negete print#("be ret oe the MULL tesminator */ \rie\riat, buttertily ple buSter(O) is at $p\o", py sbusfan); the MULL terminator +/ Vistar, buffeetal, ols bufter(0}'is at tp\st, py shutter; Borland C++ Library Reference —chain_intr chain_intr Function Chains to another interrupt handler. Syntax include void chain_intr(void (interrupt far *newhandler)0); Wes [WC] Wiese | TE [or iy 7 fi L Remarks The _chain_intr functions passes control from the currently executing interrupt handler to the new interrupt handler whose addiress 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 centered again. ‘The _chain_intr function may be called only by C interrupt functions. It is usefal when writing a TSR that needs to insert itself in a chain of interrupt handlers (such as the keyboard interrup). Return value _chain_intr does not return a value. See Also _dos_getvect,_dos_setvect,_dos_keep Example ginctude finelude Hinclude Hitdet _ cplusplus ‘teeFine _ ceensss felee tena fine _cPPaRGS typedef vod interrupt [fete] (_CRPARGS); white os (24044, 0, tpragna argoused void interrupt handler? (ansigned bp, unslaned di} 1 Chapter 2, The run-time trary o _chain_intr bet beagttIn handles 2.\e\o"%; if tal =) (Or is Teta") noag(*DI is not eta": ‘pragma argsused void intornpt handler unsigned bp, unsigned ai) enable): ies ("Ts hondler 1.\e\n") if (di = 0) esg("B1 is O\e\n"); esg("Or 18 not O\z\a"): ais eag(*Chainig to handler 2.\e\n"); “hain intr (handler?) 1 void maint) s_setvect (128, (ptr) handler}; Printt about to generate interrupt 128\0"); opt, is now Oxtx\at, D1}; chdir Funetion Syntax. Remarks 70 Changes current directory. include int chair(const char *path); 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 patl argument, such as. Borland C+ Ubrary Reference Return value s Example also chdrive chair ehdic(tas\\ncr) but this changes only the current directory on that drive; it doesn’t change the active drive. Upon successful completion, chdir returns a value of 0. Otherwise, it returns a value of -1, and the global variable errno is set to ENOENT Path or file name not found getcurdir, getewd, gotdisk, mkdir, rmdir, setdisk, system finctode Hisclode Hxclode char 016, dir(MRIDTR hae new dt (018) fat main(vots) 36 (getenaie(0, old dish) ( pezzor("getcurdir(}"1; exit (Ui; pelate ("current dinectory is: \\te\e” Af (ebaie CN persor(Pehdir() "1: exc (lly XE (gotourdir(0, nex di perror("geteardir()") exit print (*Curcent dizectory £2 nov: \\is\n*, now dir}: printf (M\nchanging back to orignal disectory: \Wis\n", old diel; Af (ehdirfold aleh) | perzorite exits return 0 Function Syntax. Sets current disk drive. include int _chdrivefint drive); Chapter 2, The run-time foray n —chdrive Remarks _chdrive sets the current drive to the one associated with drive: I for A,2 Jor B, 3 for C, and so on. Retum value _chdrive returns 0 if the current drive was changed successfully; otherwise, itreturns -1 See Also _dos_setdrive,_getdrive Example Aincluse int main oid) c ls o print (“Successfully changed to drive C:\n"); else printf (*Canaot change to drive c:\e", ' _chmod Function Gets or sets DOS file attributes. Syntax. include include int chmod(const char *path, int func [, int attrib); Remarks _chmod can either fetch or set the DOS file attributes. If func is 0, the Function returns the current DOS attributes for the file. If funcis 1, the attribute is set to attrib. atin can be one of the following symbolic constants (defined in dos.h): FA RDONLY Read-only attribute FA HIDDEN Hidden file FA SYSTEM System file FA_LABEL Volume label FA_DIREC Directory FAARCH Archive 72 Borland C+ Ubrary Reference Return value See ako Example -chmod ‘Upon successful completion, _ehmod returns the file attribute word; otherwise, it returns a value of -1. In the event of an error, the global variable erm is set to one of the following: ENOENT Path or file name not found EACCES — Permission denied chmod, _creat ‘Hizclose include se fnt got_{ile_aterib(ehar +Filenane) sm mainivoid) ( char flenen128); ena) printf ("Path or file not found.\o"): cave RICGES ¢ printE(*Pennission denied. \n"); break dotaate smber: ern) tse ( Af taterib & ROOM) prince("ts 18 read-only.\n", fllesanel: £ latteib & 7008) priate (Me 18 nidden.\nt, fen)? Le (attetb « ea s1sTE) AE (autei 6 FA_LABED) peinte(*%s ie volume label. a, filename); ff (otteib & Pa ouReC) print ("he G2 a direct Sf (attrib « Pa ARCH) printi(*te 48 an archive file ye, lenaxel filename Chapter 2, The run-time library 73 chmod chmod ' return 0; ' 1% returns the attributes of a bot file +/ int get_{ile attrib(ehar *filonans) return(_chnod(filerane, 0)1; Funetion syntax. Remarks Return value See also Example 7 Changes file access mode, include int chmod(const char *path, int amode); Ta | weer [ were [or my ‘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 isthe first character of that string, amade can contain one or both of the symbolic constants $ IWRITE and S-IREAD (defined in sys\stat.h). Value of amode ‘Access permission SIWRITE SUIREAD SUIREADIS_IWRITE Permission to write Permission to read Permission to read and write Upon successfully changing the file access mode, chmod returns 0. 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 BACCES, access, _chmod, fstat, open, sopen, stat Path or file name not found Permission denied Hisclude Hacivse include do. Hinelude Hisclude Borland C++ Library Reference chmod st main(vois) 1 chsize jar filename 64]; at anode; 4: f (etat(fllenane, sstbaf) I= 0) | ‘perror ("Unable to get file information"); retin} else { priate "changing to read-writels ‘anode = §_IRERD|S_ WRITE ' Af (otwod{ilenane, anode) = 0) ( error (Unable to change file node") seturn(i); retueo(0) Function syntax Remarks (Chapter 2, The run-time foray Changes the file size. include int chsize(int handle, long size); chsize changes the size of the file associated with handle, Itcan truncate or extend the file, depending on the value of size compared to the file's original siz. The mode in which you open the file must allow writing. Ifehsize extends the fie, it will append null characters (\0). It truncates the file, all data beyond the new end-of-fle indicator is lost. % | chsize Retun value See also Example circle ‘On success, chsize returns 0. On failure, it returns ~1 and the global variable errno is set to one of the following: EACCESS Permission denied. EBADF Bad file number ENOSPC — UNIX—not DOS close, creat, creat, open ficelade cering > Hinelade Heelude nt main(vois) 1 At bande nar buf(L1) = "0123686708 (+ coeate 2 text file containing 10 bytes 4/ Randle = open *OONMY.FTL", 0. CRAY e(handle, bat, strlen (bul)|; + teuncate the 0 5 bytes in alze +7 chsize(bandle, > close the fie +/ cleve handle): urn O; Function ‘Syntax Remarks - Return value % Draws a circle of the given radius with its center at (9). include void far circle(int x, int y, int radius); circle draws a citcle in the current drawing calor will its enter at Gy) 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. None. Borland C+ Library Reference See also Example clear87 Funetion ‘Syntax are, ellipse, fllellipse, gotaspectratio, sector, setaspectratio Hnetude include etal. Hinelade inelude int main oid) jest autodetection */ nt gdriver = OSTECT, guade, exrorcede; int mide, aidy, radius = 100; (+ intetalize graphics and gdciver, ‘node J+ road result of initialization */ ecroreode = graphrestl¢ AF (erzorcode '= geOk) | /* an nte("Geaphies exeor: As\a", grape nt g{"Press any Key to belt") " ormsgerrorcode)) oe sminate with en error code */ } re = getmacet) J 2; sy = geteaxy() / 2 setoolor getsexcolor(}) 1° daw he elxele *7 elecle(nise, migy, radius); 1 clean op */ etch losege return 0; 0s Clears floating-point status word, include unsigned int _clear87 (void); [| Winton | wre [or my Chapter 2. The run-time library circle 7 l _clear87 Remarks Retum value See ako Example cleardevice Function syntax Remarks Retun value See also Example 78 _clear87 clears the floating-point status word, which is a combination of the 80x87 status word and other conditions detected by the 80x87 exception handler. ‘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. _controls7,_fpreset, _status87 Hrelude Hixclnde int main oid) c fat x: oubie y = 156-100 Printf{(*astatus 87 before error: 4x\a", _sta x= yi [* create underflow and precision Toss */ printf ("statue 87 after error: tt\a", _statws67()) “clear? Prince "status 67 after yen return 0; jar: xn", _statusb7(}) ‘Clears the graphics screen. Winlude void far cleardevice(void); BS [WR | Wawe | ere [Oey include eat. Hrelude Borland C++ Library Reference int main(void) 1 1+ request autedetection #/ int gériver = DEIGCT, gnode, errorcoder J+ initialize graphies and local variables */ initgraph(agdriver, sgnode, °"); (> read result of initialization */ extorende » graphreenlt ); AE (extorcode '~ gr0k) ( printf ("Graphics erzor: @s\n" printt("2rese any Rey to bale")? etch: exe; 1 ferrorcode 1+ teaminate with on excor code */ aide = geteaxx() / 2: aidy = goteaxy() / 2% sateolorigetmaxcolee(} 1+ foe centering serean nessages */ sottent justify (CENTER P=XT, COVTER TE 1+ output a message to the sereas */ cattextay mide, midy, "Press any key to clear the screen:) getchtl; (ait for a key */ leardevice();/* clear the screen 47 1 outpat another message */ ide, misy, “Pees any hay to quit event leseseeph(e return 0; clearerr Function Resets error indication, ‘Syntax include void clearerr(FILE *stream); Chapter 2, The run-time brary cleardevice n clearer Remarks Retum value See oko Example clearviewport Function syntax Remarks Retun value clearerr resets the named stream’s error and end-of-file indicators to 0. 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, None. 01, feof, ferror, perror, rewind Hinelude nt nein vote Prue ¥p: char chr 1+ open a file for writing +7 fp = fopen DIMM. FEL", *v") 1 force an ch = fgetortp) rinte (*\o" Af (fercortfeh) ( 1 display an error message */ peinut (Ervor reading feom DOMMY.FTL\at (+ reset the extor and 20° sndicators */ earers (fp felese return 0; Clears the current viewport findude void far clearviewport(void); ves Wnion | MSE [Oey clearviewport erases the viewport and moves the CP (current position) to home (0,0), relative to the viewport None. Borland C++ Library Reference See also Example cleardevice, getviewsettings, setviewport include fnelade lade Hiselude Pou 1 /* activates clipping in viewport */ 1* cequost autodetection */ int gdriver + DaTECT, gmade, erzorcode, tt: iF lize qraphies and local varlables */ J read sasult of initialisation */ code = grapheesut () 1 an exror occurred +/ As\o", grapherrornsgersorcode}); print ("Press any key to halt sgetent fit /* teminate with an exnor ood */ (getmaxcolor{}): height 9% massage in default outtextay(, 0," -scroen viewport */ (@, 0) in dofault viewpo 1% create @ smaller vewport */ sotviewport (50, §4, getmxx()-50, getasxy(}-50, CLIO 1 display sone messages */ outtextay 0, 0, "# <= (0, 0) in smaller viewport” futtextay 0, 2th, “Press any Key to cleat viewport: etch: 74 valt for a key */ Clearviewport (};_ /* clear the viewport */ 7 output ther nozsage */ futtextay 0, 0, "Press any key to quit") + etean mp 4 etch leseseeph() arn 0 Chapter 2, The run-time llorary clearviewpor al clock close, close clock Romarks _close and clase close the file associated with handle a file handle ‘biained from a creat, creat, ereatnew, ereattemp, dup, dup2, open, or Function Determines processor time. open cal. oe eb These functions do not write a Git character atthe end ofthe file. Ifyou Rotum value Upon sucessful completion, close and close return 0, Otherwise, these Fa re eons aot | Carat functions return a value of -1. i __ose and clase fail if handle is not the handle ofa valid, open file and Remarks clock can be used to determine the time interval between two events. the global variable errno is set to i To determine the time in seconds, the value returned by elock should be EBADF _ Bad file number divided by the value of the macro CLK_TCK. Seealso chsize, close, creat, creatnew, dup, fclose, open, sopen Return value ‘The elock function retums the processor time elapsed since the beginning es es ofthe program invocation, Ifthe processor time is not available, or its ieee eee value cannot be represented, the function returns the value—1 Finca cost See also time int mintvoid) { Example jinctude «tim.» sn bane; Tinea Henereny = maine tanale = open "00m weitethandle, bu, ee eee ee 1+ close the fe */ | olay (2000 ceesneae tnd = lost: recor print é ("The time was: $f\n", (end - start) / CLK_PCK) 1 turn 0 : closedir close, close Function Closes a directory stream. Syntox Hinclude Function Closes a file. void closedir(DIR “dirp); ‘Syntax #include int. close(int handle); es [wor] winds | mSTC | Ow only int closetint handle); oe aa [Wi] nes [mee To iy Remarks On UNIX platforms, elosedir is available on POSIX-compliant systems. we Borland C++ Library Reference Chapter 2, The run-time library 83 closedir ‘The elosedir function closes the directory stream dip, 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. Rotun vale If closediris sucessful, it retums 0, Otherwise, closed returns 1 and sets the global variable era ta EBADE —Thedirp argument doesnot point toa valid open directory s See Ato opendi, read, rewind Example See the example for opend closegraph Function Shuts down the graphics system. Syntax fnclude ‘oid far closegraphivoid; Remarks closegraph ceallocates all memory allocated bythe graphics system, then festores the screen to the mode it was in before you called Initgraph. (The fraphics system deallocates memory, sich asthe drivers, fonts, and an {hternal buffer, through a cal to graphfreemem) Retum value None. See also initgraph, setgraphbutsize Example finclude finclade
  • Hinelude Haelade nt main iris) ‘+ request autodetection */ fine gériver = OBTECE, guode, exvorcede, x) yi + initialize grephice wade */ inktgraph(4gaeiver, ignde, J+ read result of initialization */ scrorcode = graphrevlt () Af (exzorcoda != gr0b) {| /* an error occurred */ print ("Graphics error: Ws\n", grapherrornes(errorcodel] Borland C++ Library Reference clreol closegraph getch exit); 1 1° ceminate vith ap error code */ a getmaeet) J 2: y= getmasy0) / 2: 1 output a message #/ settext just fy (CENTER TEXT, CHNTER ayy "Pees a key ern); }oce the graphics systen:, losegraph}? We're now back in text node.\a"): return 0; Funetion syntax Remarks Retum value See also Example Clears to end of ine in text window. ‘Winclude 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. cirscr, delline, window include i cleser() cprint®(*The fonet Son CIRDOL clears all chacacters from the\e\n") prints (aursor pooition to the end of the Line withia the\c\n") prints ‘current text window, without moving the cursor. zo"): prints ("Press any kay to continve . . s*) gotoxy(, 4): getch (Chapter 2, The run-time library 7 i i creo! etrol(}+ poten: clrscr Function Clears the text-mode window. Syntex include void crscr(void); ES Remarks cirsor clears the curzent text window and places the cursor in the upper left-hand comer (at position 1,D. Retum value None. See also clreol, deine, window Example fisciude H epinct(vtsic\et, 107 epristtt"\e\atcce ny hey to clear screen"): gore cer(} (Othe screen tas bean closed!) seca: complex oe Function Creates complex numbers Syntax 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 0 if nag is omitted. ‘complex is the constructor for the C++ class complex, which is defined in complexch. 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 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. complex:h also overloads the operators +,~,*,/, 45,6 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, Retum value The complex number with the given real and imaginary parts. abs, acos, arg, asin, atan, atan2, conj, cos, cosh, imag, log, logt0, norm, polar, pow, real, sin, sinh, sqrt, tan, tanh, See also Example ‘iaciode Hinclode nt moin(voks) Goble x = 3.1, y= 4.25 conplex 2 = complex(ss yt cout <<" has real part = " << real(a} << "ats out << * and Snaghnasy real part = "<< inag(2) << "ats Soot <<“ has complex conjugete ~ * <£ consis) << ety retumn 0 conj Function Returns the complex conjugate of a complex number. (Chapter 2, The run-time library a 1 coal —control87 jx tincuie same bitin the floating point contol word and _onto87 st that bitin Sree ec confeompe the contol word tothe hew vale Here's a simple illustration: Original control word: 0100 0011.10.01 tae [wi] viotee [ase [oe ly mask 100 coo 0100S i Remarks con} isthe same as coaplex(veal 2), lnag[a) = ing (a coo one Retum value ‘The complex conjugate ofthe complex number. a lv unt xo 101 | seecto complex mag, real HE musk equals 0, control returns the floating-point control word Example isciuse without altering it include _Control87 does not change the Denormal bit because Borland C++ uses | int nain(void) enormal exceptions. Bee oh ene Retum value The bits in the value returned reflect the new floating-point control word. fconlax 2 = couplex(x) For a complete definition of the bits returned by _control87, see the cook cere eee De header file float. ] Gore cad ingly ean See also _clear67,_fpreset, signal,_statuss7 f Slee Sc x hs conplex cones = retusa 0: ina << conjah "a | 5 coreleft ' Function Retumns.a measure of unused RAM memony fi, cons) Syntax nthe tiny smal and medium mol : ee | Function Maniputaes the floating-point contol word Se i Synlox include a a {unsigned int newcw, unsigned int mas) nthe compac, rg, and huge adel | signed int controlB7(unsigned int eww, unsigned int mash Inthe comp arg | sae [ae | wes [a nly unsigned long coreleft(void); | femarks _control67 retrieves or changes the floating-point contol word ‘The floating point control word is an unsigned int that, bt by bit. specifies Remarks corelett returns a measure of RAM memory notin use, It gives a different certain modes in the floating-point package; namely, the precision, ‘measurement value, depending on whether the memory model is of the | infinity, and rounding modes. Changing these modes allows you to mask Small data group or the large data group. cor unmask floating-point exceptions. ntrol87 matches the bits in mask to the bits in newew. If mask bit Return value In the small data models, coreleft returns the amount of unused memory same he coresponding bi in nent conains the ne value forthe between the top the Reap andthe stack. In the age data models, coreleft returns the amount of memory between the highest allocated block and the end of available memory. |, 8 Borland C++ Ubrary Reference Chapter 2, The run-ime lexary » coreleft See also _allocmem, brk, farcorelett, malloc Example jinclude int maln(veid) i printf ("The difference between the highest prlate ("the top of the heap ie: tly bytes\a", (unsigned Long) cocelett()) return 0; cos, cos! Function Calculates the cosine of a value. Syntax Real versions: Complex version: include include double cos(double x); complex cos(complex x); long double cosi(long double x); cot |e o neatieos [=| = | = Compiexeos [= : o Remarks cos computes the cosine of the input value. The angle is specified in radians, coslis the long double version; it takes a long double argument and returns a long double result. ‘The complex cosine is defined by c0s(2) = (expti* 2) + exp(i*2))/2 Retun value 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 _mathert!), See Also acos, asin, atan, atan2, complex, mathert, sin, tan Example sinciude include int main(void) 0 Borland C++ Library Reference 08, cost result = costh): peinte The cosine of SIE As $s return 0; relly; cosh, coshl Function Calculates the hyperbolic cosine of a value. Syntax Real versions: include double cosh(double 2); long double coshi(long double x); Complex version: #include complex cosh(complex 2); Real cosh Comex cosh s Remarks cosh computes the hyperbolic cosine, (e* + €*)/2. cosh is the long double version; it takes a long double argument and returns a long double result, ‘The complex hyperbolic cosine is defined by cosh(z) = (exp) + exp(-2))/2 Retum value cosh returns the hyperbolic cosine of the argument. When the correct value would create an overflow, these functions return, the value HUGE_VAL (cosh or _LHUGE_VAL (coshi) with the appropriate sign, and the global variable erm is set to ERANGE, Error handling for these functions can be modified through the functions matherr andl_mathertl. See Also acos. asin. atan. atan2. complex. cos. matherr, sin. sinh, tan, tanh Example finciode Hnclude nt naln(vold) ouble result, = result = coshtx) (Chapter 2, The run-time Ibrory a cosh, cosh printe(*Te hyperbole cosine of ALE Js Ale\a", xy result)? return 0; ' country Function Returns country-dependent information, Syntax include struct COUNTRY *country(int xcode, struct country *ep); Remarks country specifies how certain country-dependent data (such as dates, times, and currency) will be formatted. The values set by this function depend on the DOS version being used. If ey has a value of -1, the current country is set to the value of xcode, which must be nonzero. Otherwise, the COUNTRY structure pointed to by cpis filled with the country-dependent information of the current ‘country (if xcoleis set to 0), or the country given by xcode. ‘The structure COUNTRY is defined as follows: struct country | at co. dates 1% date format +7 currency symbol */ ‘> thousands separator */ 1% docisal separator */ 18 date separator */ J tine separator */ char 02 char oo, digits significant digits in currency #/ hae 62. tine 15 tine format 47 18 case nap 4 J data separeter */ thar 62-1100) ye tiller #7 hi ‘The date format in co_date is 10 for the US. style of month, day, year 11 forthe European style of day, month, year 12 for the Japanese style of year, month, day Currency display style is given by co_currstyle as follows 2 Borland C+ Library Reference Retum value Example oprintt country © Currency symbol precedes value with no spaces between the symbol and the number, 1 Currency symbol follows value with no spaces between the number and the symbol 2 Currency symbol precedes value with a space after the symbol. 3 Currency symbol follows the number with a space before the symbol On success, country returns the pointer argument cp. On error, it returns null Hinelude Hinelude define ush 0 int main(voia) 1 country SR, scout prine®("he currency symbol for the USR se: s\n", country info.co cure! ; return 0 Function syntax Remarks See print or detas ‘on format species Return value ‘Writes formatted output to the screen. include int cprinti(const char "format, argument, Ds eprint! accepts a series of arguments, applies to each a format specifier contained in the format string pointed to by format, and outputs the formatted data directly to the current text window on the acrcon. There ‘must be the same number of format specifiers as arguments. ‘The string is written either directly to screen memory or by way of a BIOS call, depending on the value of the global variable directv. Unlike fprintf arid print, eprintf does not translate linefeed characters (\n) into carriage-return/linefeed character pairs (\r\n).. coprintf returns the number of characters output. Chapter 2, The run-time lirary 93 eprint Seeako Example cputs directoideo (global variable), fprintt, printf, putch, sprintf, vprintt include int main(void) 1 eleser( ” Lear the sereen * window(0, 10, €0, 2517 7 create a text window */ eprint® (elle workd\c\n"y; /* one text in the window */ etch: J+ wait foe a ey 47 return 0 Syntax Remarks Retumn value See ako Example Writes a string to the screen. include int cputs(const char *st7); =e re [TE == Coputs writes the null-terminated string str to the current text window. It does not append a newline character. ‘The string is written either directly to screen memory or by way of a BIOS call, depending on the value of the global variable directoideo. Unlike puts, eputs does not translate linefeed characters (\n) into carriage-return/linefeed character pairs (\r\n). puts returns the last character printed. gets, directvideo (global variable), fputs, putch, puts. include nt main(vots) t clrscrt) (+ clear the sexten */ Window(10, 20, 80, 25); 1* exeote a text vindow #/ 1 sogoutpet tone text Ln the widow */ cputs("bie Se within the windoa\r\n")7 oeten Pe wait for a key 4) return 0; Borland C++ Library Reference a -£teat, _dos_creat _creat, _dos_creat Function syntax. creat dos creat Remarks Return value Creates a new file or overwrites an existing one. a include int _creat(const char path, int attrib); unsigned _dos_creat(const char *path,int attribint *handlep); __ereat and _dos_ereat open the file specified by path. The file is always opened in binary mode. Upon successful file creation, the file pointer is set to the beginning of the file. _dos_ereat stores the file handle in the location pointed to by handiep. The file is opened for both reading and writing, If the file already exists, its size is reset to 0. (This is essentially the same as deleting the file and creating a new file with the same name.) ‘The attrib argument to creat is an ORed combination of the one or more of following constants (defined in dos.h): FA RDONLY Read-only attribute FA HIDDEN Hidden file FA_SYSTEM System file ‘The attrib argument to_dos_creat is an ORed combination of one or more of the following constants (defined in dos.h): -A.NORMAL Nonmal file ‘A-RDONLY Read-only file “A HIDDEN Hidden file TA'SYSTEM System file Upon successful completion, creat returns the new file handle, a non- negative integer; otherwise, it returns —1 Upon successful completion, _dos_creat returns 0, fan error occurs, _dos_creat returns the DOS error code. In the event of error, ereat and _dos_creat, the global variable errno is set to one of the following: ENOENT EMFILE Path or file name not found Too many open files Chapter 2, The run-time itbrary 95 creat, dos_creat EACCES: Seealso _chmod, chsize, _close, close, creat, creatnew, creattemp Example Permission denied Aneto <> snclnde Hirclude Hacluss nt maint) ( neigned counts St handles char baf{I1) = "012356789"; (+ create a 10-byte file using dos creat. */ (os erent (*DUREE.FIL*, A TORMAL, shandle} = 0} { erzor("“Unable to dos ceat DLMGY.FIL"; AE (dos_write(handle, but, stelen(buf), scout} ! pestor("Unable to\_doe vrite to DOMY.FIL") return 1 _sos_elose han (> Create another J0-byte file vsing creat. */ Sf ((handie e2.FIL, 0}7 < 0) | if (_weltetbandle, bof, st ‘persor “Unable to “write %o OOA2.FIt"|; creat Function Syntax. Creates a new file or overwrites an existing one, include int creat(const char *path, int ame); [wok [tee Taare Tee a ai fet) teen eee 96 Borland C++ Library Reference creat Remarks creat creates a new file or prepares to rewrite an existing file given by prt amede applies only to newly created files. AA file created with creat is always created in the translation mode specified by the global variable _fmode (O_TEXT or O_BINARY) If the file exists and the write attribute is set, reat truncates the file toa Tength of O bytes, leaving the file attributes unchanged. Ifthe existing file has the read-only attribute set, the creat call fails and the file remains ‘unchanged. ‘The creat call examines only the $_IWRITE bit of the access-mode word ‘amode. If that bit is 1, the file can be is written to. Ifthe bit is 0, the file is marked as read-only. All other DOS attributes are set to 0. ‘amode can be one of the following (defined in sys\stat h}: Value of amode ‘Access permission SIWRITE Permission to write SUIREAD ‘Permission to read SUIREADISIWRITE Permission to read and write wp In DOS, write permission implies read permission. Return value Upon successful completion, creat returns the new file handle, a non- negative integer; otherwise, it returns -1, In the event of error, the global variable errno is set to one of the following: ENOENT Path or file name not found EMBILE Too many open files EAC Permission denied See.alo chmod, chsize, close, creat, creatnew, creattemp, dup, dup2,_fmode (global variable), fopen, open, sopen, write Example —jinctose Haetoe Hiaclose include ‘Haclose Hinclose Hineluse ft mala vote int handle char baf{] = "012345 Chapter 2, The nun-fime ibrary 7 creat 1 croste a bisay fe for ceding and citing */ {e {inate » rest (on #8, 0) <0) scence) Soe EDO print (Error: Patho file ot found. \e ti cove METIS: pet (Ector Too many open fies.\"lz see.ako ‘case FACES: printf("Error: Permission denied. \a"); Example beste defmlt: pein f("Esorexeating fe." 7 Bess ) pata 1 J write a stciog snd WL terinstor into Ue fle + sestetande, bot, sezletbtl [+ close the #8 */ cethaa ) creatnew Function Creates anew ile Syntax include int creatmev/(const char path, nt mode); oa [oa [recon [rare [ea creattemp 7a Function Remarks crestnew is identical to_ereat with one exception. Ifthe file exists, cae creatnew returns an error and leaves the file untouched. *ynt ‘The made argument to ereatnew can be one ofthe following constants (defined in dosh FA_RDONLY Keac-only attnbute FATHIDDEN Hidden file : FA SYSTEM System file oo Return value Upon successful completion, ereat return the new file handle, a non- negative integer, otherwise, it returns 1 Inthe event of error, the global variable errs set to one ofthe following: %8 Bonand Cr+ ubrary Reference f= creatnew EEXIST File already exists ENOENT —_Pathor file name not found EMFILE Too many open files EACCES Permission denied close, creat, creat, creattemp, dup, _fmade (global variable), open Haeivse Hinelude int main void) fl nt mane char bof[i] = *0123456789" + attempt to exeate a Eile that dosn't elzeedy exist +/ Donde = exeatnev{*DOHeTL", 0); 4f handle = -11 tf ("ODM PTL alseady axists.\n") ELL, successfully exeated. a"; ‘rite(bandle, bot, stelen{euti); close bande: ' retata 0 Creates a unique file in the directory associated with the path name, include int creattemp(char ‘path, in attrib); Tate : 7. ‘fle crented with ert i aways created in the translation mode specited by te global variable. mode (©. TEXT or © BINARY. path isa path name ending with a backslash (\). A unique file name is, selected in the directory given by path. The newly created file name is stored in the path string supplied. path should be long enough to hold the Chapter 2, The run-time library 9 | ereatteme | resulting fle ame The lei nt automata deleted when the program terminates, ereattomp accept ari, a DOS attribute word, The fli always opened binary mode: Upon socesfu le eration, the file pointers set othe | iaginning ofthe fle. The leis opened for both reading and writing | ‘The attrb argument to ereattemp can be one of the following constants (defined in dos FA.RDONLY Read-only atibute | FATTIDDEN Hidden file FASYSTEM System fle Return value Upon succesful completion, the new ile handle a nonnegative intege, | returned otherwise, 1s retard In the event of error, the global variable errno is set to one of the following: ENOENT Patho file name not found | EMFILE —_Toomany open files EACCES Permission denied See.also close, creat, creat, creatnew, dup, fade (global variable), open Example —jipclude | include elude int matn(vose) i sot handle char patinane 128) coy lpathnane, WI: 1 create » unique file in the root directory */ handle ~ craattenp(pathnaze, 0} prlot£(s wos the unique File crested.\a", pathnane) lose handle otara 0; scant cc Function Scans and formats input from the console. Syntax. include int escanf(char "format, address, ...D; il 100 Borland C++ Library Reference Remarks ‘See scant for dota ‘9n format specirs ‘scant Wee [We] Winton [STE O only = [eee ~| ‘escant scans a series of input fields one character ata time, reading directly from the console. Then each field is formatted according to a format specifier passed to eseant in the format string pointed to by format. Finally, escant stores the formatted input at an address passed to it as an argument following format, and echoes the input directly to the screen. ‘There must be the same number of format specifiers and addresses as there are input fields cescant might stop scanning a particular field before it reaches the normal cend-of-field (whitespace) character, or it might terminate entirely for a number of reasons, See scanf for a discussion of possible causes, Retum value cscanf returns the number of input fields successfully scanned, converted, and stored; the return value does not include scanned fields that were not stored, Ifno fields were stored, the return value is 0. Ifeseant attempts to read at end-of-file, the return value is EOF. See.clso fecant, getche, scant, sscant Example tinclude int main void) in 1 scrsen */ ‘print 7+ prompt the vser for input */ Gheant("is", string); read the Anpat * vos road #1 inthe string entered Se: Qs", string)? 1 ctime Function Converts date and time toa string. Syntax #include char *ctime(const time_t *time); ‘Chapter 2, The run-time library 101 Remarks _ctime converts a time value pointed to by time (the value returned by the function time) into a 26-character string in the following form, terminating, with a newline character and a null character: Non Wow 21 11:50:54 1983\s\0 [All the fields have constant width. Set the global long variable timezone to the difference in seconds between GMT and local standard time (in PST, timezone is 860%60). The global variable daylight is nonzero ifand only ifthe standard US. daylight saving time conversion should be applied. Retum value ctime returns a pointer to the character string containing the date and time. The return value points to static data that is overwritten with each call to ctime. Seealto asctime, daylight (global variable), ditftime, ftime, getdate, atime, localtime, settime, time, timezone (global variable), tzset Example jineiuée include nt main(void U f= Eine ns priate (*foday's date and tine return 0; ctrlbrk pane Function Sets control-break handler, Syntox include soln, tine! void ctrlbekGint *handler\(void)); Remarks etrlbrk sets a new control-break handler function pointed to by handle. The interrupt vector 0x23 is modified to call the named function. ctrlbrk establishes a DOS interrupt handler that calls the named function; the named function is not called directly. 102 Borland C+ Library Reference Retumn value See ako Example delay til ‘The handler function can perform any number of operations and system calls. The handler does not have to return; itcan use longjmp to return to ‘an arbitrary point in the program. The handler function returns 0 to abort the current program; any other value causes the program to resume ‘execution. ctrlbrk returns nothing. getcbrk, signal Finelude Hnelude = broak (roid) printf "Control-Break pressed. Program aborting returni0); ) void natn (veld) i certbek(e break): for(i) ei 1 enys ooping... Peese to quit:\a"); Sey Function Syntax. Remarks Return value See also Example ‘Suspends execution for an interval (milliseconds). include void delay(unsigned milliseconds); tas | war | Winton [ATE | OF oly With a call to delay, the current program is suspended from execut the number of milliseconds specified by the argument milliseconds. Itis no longer necessary to make a calibration cal to delay before using it. delay is accurate to a millisecond. ‘None, nosound, sleep, sound. J+ enits a $40-H tone for $00 milliseconds */ include nt main(void) (Chapter 2, he run-time lorary 108 deloy delline Funetion Syntax Remarks Retum value See also, Example detectgraph souna(t40); delay 600) resound): retin 0: Deletes line in text window. include void delline(void); SEE] dolline deletes the Line containing the cursor and moves all lines below it ‘one line up. delline operates within the currently active text window. None. clreol, cirscr, instine, window Hnelude fat maingvose) t clreor() Cprinte(he function DELLINE delates the Line containing the\z\a") cprint®(cursor and noves all Lines below it one line vp. ria") (prints CDELLINE operates within the currently active taxt\c\a"); cprintt (window. Press any key to continue or to the 2nd Line, Ist colum */ Function 104 Determines graphics driver and graphics mode to use by checking the hardware. Borland C++ Library Reference Syntax Remarks Table21 etectoraph constants detectgraph include void far deteetgraph(int far “graphdriver, int far "graphmode); detectgraph detects your system's graphics adapter and chooses the mode that provides the highest resolution for that adapter. If no graphics hard- | ‘ware is detected, "graphariver is set to grNotDetected (-2), and graphresult returns grNotDetected (-2). * graphariver is an integer that specifies the graphics driver to be used. You can give it a value using a constant of the graphics_drivers enumeration type, defined in graphics.h and listed in the following table, ‘graphics drivers constant DETECT (0 Gequests autodetection) CGA MCGA EGA GAS EGAMONO IBMESI4 HERCMONO ATT#00 VGA PCR Numeric value *graphmode is an integer that specifies the initial graphics mode (unless *graphariver equals DETECT; in which case, “graphmode is set to the highest resolution available for the detected driver). You can give *graphmode a value using a constant of the graphics_modes enumeration type, defined in graphics.h and listed in the following table. Chapter 2, The run-time brary 105 detectgraph 106 Tobie 22 Graphics divers information Return value See.also Example Graphics: Column river graphics modes Value xrow Palette Pages Ga ‘eGaco 0 320x200 co i GACT 1320x200 Cl 1 ccacr 2 m0x20 1 Gas 3 30x20 1 GARI 4 640x200 2eolor 1 MCGA, McGAco © 320x200 co 1 MCGACI 1 320x200 C1 1 MCGAC2 2 320x200 2 1 MCGACS, 3 320x200 3 1 MCGAMED 4 640%200 color 1 MCGAHT 5 640%480 Deolor 1 EGA EGALO © 640%200 16color 4 EGAHI 1 640%350 I6color 2 GAGS BGAGILO, 2 640%200 16color 1 EGASIHT 1 640%350 ¢eolor| 1 EGAMONO EGAMONOHI = 3640x350 2eolor 1" EGAMONOHI = 3640x350 -2eolor 2 HERC HERCMONOHI 0720348 color 2 ATTHO0 ATT400C0 © 320x200 co 1 ‘ATTAOOCL 1 320x200 Cl 1 “ATT400C2 2 mox20 2 fl “ATT¢00C3, 3 320x200 1 ‘ATTANOMED 4 640x200 Zeolor 1 ‘ATTAOOH 5 640x400 Deolor 1 VGA VGALO © 640200 16color 2 VGAMED 1 640x350 16color 2 VGAHI 2 640%880 IGcolor 1 Pc3270 C3270 0 720x350 2color 1 TBMS514—IBM8514HT 0 640x480 256 color TBMB514L0 0 1024x768 256 color +. 64K on BGAMONO card 256K on EGAMONO card Note: The main reason to call detectgraph directly is to override the ‘graphics mode that detectgraph recommends to iniigraph. None, ‘graphresult,initgraph Hinetude fioclade cralsb. 2 Borland C+ Library Reference detectgraph Hinelude 1 the sams of cca dean | = he varlous carde supported */ an Bat, a GOK BOR", van TM 2270 Pe" hi nt main(voia) (+ sed to return detected hardware info. */ int gariver, gnode, erroreod (+ detect the graphics barduaze available */ etectgraph(igaeiver, sgnedel: frtoreode = graphresult AF (errorcede '= gr0k) print Graphies| inte ["Prese any key to Balt"), etch nel ph call */ eeminate with an error code */ ected 1 cetrsee0 inte ("ou have $2 video display eard.\o", deane(géelver)): any boy to halt" difftime: Function Computes the difference between two times. Syntax #include double difftime(time_t time2, time_t time); Chapter 2, The run-time Itorary 107 aitfime Remarks Retum value See also, Example difftime calculates the elapsed time in seconds, from timel to time2. difftime returns the result ofits calculation as a double, asctime, ctime, daylight (global variable), gmtime, localtime, time, timezone (global variable) fnclude include include include Ane gan (vela) t time t first, second: elesee(ls first = tine mL); 17 gots systen tine +/ delay (2000) 1+ waits 2000 milLisecs or 2 secs #/ second = tna WILL); J+ gots syston tine again */ Printf("the difference 1a: 4 seconde\a" al ftt ine second, first}: seteh() return 0 disable, _disable, enable, enable 108 Function syntax. Remarks Disables and enables interrupts. ffindude void disable(void); void disable(void); void enable(void); void enable(void); Wiion | Ste [oor ‘These macros are designed to provide a programmer with flexible hardware interrupt control. The disable and _disable macros disable interrupts. Only the NMI (non- maskable interrupt) is allowed from any external device. Borland C+ Library Reference Retum value See also Example disable, _disable, enable, enable ‘The enable and _enable macros enable interrupts, allowing any device interrupts to occur. None. getvect (+ This Se an interrupt service routine, You cannot compile this progean with ‘est Stack Overflow turned on and get an executable file that operates corzectly. */ Hacluse Apeluse ‘Hasinse define IMIR OIC. /* The clock tick interrapt ifder _eplusplos efine _coeancs fetse define _coonnes frais andler|_COPARGS| /* Af CH, need che the el terrupte ducing the handling of the intercypt */ the globel couster */ count 7+ reonable interrupts at the end of the handler */ enablet) Teall the old routine */ ldhandier(); 1 int min void) i 1% aave the old interrupt vector */ lchandler = _doe_getvect (IN); “dos setvect (100%, handles); 1+ Loop uptit the couster exceeds 20 */ vine (count < 20) print f(eount is 4d\a", count) (7+ rewot the old interrupt handler “sos_satwect (IHR, oldbandler): ” Chapter 2, The run-time Worary 109 aiv div return 0; Function Syntax Remarks Retun value See.aiso Example no Divides two integers, returning quotient and remainder. include div _t divGint numer, int denom); BEA | widows | mre [eo ooly div divides two integers and returns both the quotient and the remainder asa dio_t type, numer and denom are the numerator and denominator, respectively. The div_t type is a structure of integers defined (with typedef) in stdlib.h as follows: typodes stro quot; /* quatlent */ ren; sanalnder #/ div returns a structure whose elements are quot (the quotient) and rent (the remainder). liv Hinelade cei. include dive x nt main (void) i x= 4i7010,3); prince ("id alv 3 = aa turn 0: winder Wan", x.quet, x.ten); Program output 10 giv 3 = 3 remainder 1 Borland C+ Library Reference dos_close Function Syntax Remarks Return value See Also Example -os_close Closes. file include unsigned _dos_close(int handle); __dos_close closes the file associated with handle, handle is a file handle ‘btained from a_dos_creat,_dos_creatnew, or_dos_open call. Upon successful completion, _dos_close returns 0. Otherwise, itreturns the DOS error code and the global variable errno is set to EBADF Bad file number _dos_creat,_dos_open,_dos_read, _dos_write include
    include finelude Ine min void) char buf[12) = *0123456789%, J+ cceate a file containing 10 bytes */ Sf (doe crest *DOMKE.FIL", _A NORMAL, Shandle} '= 0} 1 perzot ("Unable to create DuRmPILM: Af (doe write(handle, bot, strlent error “Unable to write to DIWE.FII"); os_closethandio); /* close the file * Fetuta 0: Chapter 2, The run-time brary m _dos_creainew dos_creatnew Function Creates a new file Syntax. include “unsigned -dos_creatnew(const char “path, int attrib, int *handlep); or [wit | wes [ WOE [oe ly Remarks _dos_creatnew uses DOS function 0x5B to create and open the new file jath. The file is given the access permission attri, a DOS attribute word. ‘The file is always opened in binary mode, Upon successful file creation, the file handle is stored in the location pointed to by hiandlep, and the file pointer is set to the beginning of the file. The file is opened for both. reading and writing, If the file already exists, _dos._creatnew returns an error and leaves the file untouched. ‘Theattrib argument to_dos_creatnew is an OR combination of one or more of the following constants (defined in dos.h): _ANORMAL Normal file TARDONLY — Read-only file TAHIDDEN Hidden file TA'SYSTEM System file Relum value Upon successful completion, _dos_creatnew returns 0. Otherwise, it returns the DOS error code, and the global variable errno i set to one of the following: EEXIST File already exists ENOENT — Pathor file name not found EMEILE Too many open files EACCES Permission denied. See Also _dos_close,_dos_creat,_dos_gettileattr,_dos_setfileattr Example —jinciuse finelode Finelude ( wneigned counts 4st handles char buf (11) + "0123486789%; 8) ne Borland C+ Library Reference ~dos_creatnew 1 create a file containing 10 bytes */ eaten (*DIMKE.FILS, A NORA, Shandle) != 0} | eats OO FLL dos write|pandie, but, stzlenfbaf}, Scout) = 0) 4 peiror(*Duable to wzite to DIRMY.FIL"); dosexterr Function Gets extended DOS error information. Syntax #include int dosexterr(struct DOSERROR *eblép); Remarks This function fills in the DOSERROR structure pointed to by eblkp with extended error information after a DOS call has failed. The structure is defined as follows: seruct0seRRCR ( ‘nt de exterrory /* extended error */ char de elas; /* error class */ char de_action; —/* action #/ char de_locus;—/* error locus * ‘The values in this structure are obtained by way of DOS call 0x59. A de_exterror value of 0 indicates that the prior DOS call did not result in an error. Retum value dosexterr returns the value de_exterror. Example jiclude finelade int main(void) t Chapter2, Ihe run-time library ns -dos_finatirst DOSER Sat A.RDONLY — Read-only attribute fopent ecto ae",*2); TAHIDDEN — Hidden file IF (tpt pectorUaable to open fie for ceeding"; TA'SYSTEM System fle coserezs (info : TAVOLID — Volumelabel reid 2s eer ifomtles)s enon | eee 0S" Crass," Anode 1888) 3 ~A_ARCH Archive = For more detailed information about these attributes, refer to your DOS sy * reference manuals. ' Note that wr_time and wor date contain bit fields for referring tothe file's date and time. The structure of these fields was established by DOS. Both are 16-bit structures divided into thre fields _dos_findffirst wr time: Function Searches a disk directory. bits 4 Theresul of seconds divided by 2 (eg, 10here mans Syntax include Mes | Minne unsigned -dos_findfirst(const char ‘pathname int attri, Beis Hous struct find_¢ "oI; jn WS [ UK | windows | ME | Ow cay bits 0-4 Day 7 leat i bits 5-8 Month Dits9-15 Years since 1980 (eg, 9 here means 1989) Remarks _dos_findfirst begins a search ofa disk directory by using the DOS Retum value _dos_findfirst returns 0 on successfully finding a file matching the search ao pathname, When no more files can be found, or if there is some error in the pathname is a string with an optional drive specifier path, and file name of file name, the DOS error code is returned, and the global variable err is the file to be found. The file name portion can contain wildcard match setto characters (such as ? or *). Ifa matching file is found, the find_t structure So phe pointed to by fikis filled with the fle-directory information. seo AsO doe teovext format ofthe find_t structure i a follows: ae ‘The format of he find struct Example isciude strvet Hod t tpelede cdo ‘hae reseved[2Il;/* reserved by 008 #/ es 1 ateetate fund */ " i tile tine #7 \ ih file dae +7 st nd is long site 1 file sie + ab te ane chat a1 found fle sane */ eee eer y valle Gace ( a attrib isa DOS fileattribute byte used in selecting eligible files forthe peimf(" e\a", 060k one search, aftr is an OR combination of one or more ofthe following, fone ~ doe tindoxt thik constants (defined in dos.h: a _A.NORMAL — Normal file ) m4 Borland C++ Library Reference |) Chapter2, The run-time library 18 dos findtirst _dos_findnext Program output Disectory Listing of #9 WORSE 08d FINOFRST 1 Function syntax Remarks Retun value See Also Example 6 Continues _dos_findfirst search. include ‘unsigned dos findnext(struct find_t "18; vas] Wines | mote [ O eely __dos_findnext is used to fetch subsequent files that match the pathname given in dos. findfirst. folk is the same block filled in by the “dos_findtirst call. This block contains necessary information for ‘Continuing the search. One file name for each call to _dos_findnext will be returned until no more files are found in the directory matching the patiname, __dos_findnext returns 0 on successfully finding a file matching the search >atiriame, When no more files can be found, or if there is some error in the file name, the DOS error code is returned, and the global variable erro is set to ENOENT — Path or file name not found _dos_findtirst include Hinelude st nain void tv stevet indy nt done print! (DLsectory Listing of *.*\a": Sone = dos findfirst ("yA NORIBL,cEERIB) white Gone) ( printt(" s\n", ftblk.nanel (done = _ so, findnex (48t tk: Borland C++ Library Reference os findnext Program output Directory Listing of +4 PINDFRST 080 _dos_getdiskfree Function Gets disk free space. Syntax. include ‘unsigned dos_getdiskfree(unsigned char drive, struct diskfree_t*dtable); : al eee Remarks _dos_gotdlisktree accepts a drive specifier in drive (0 for default, for A, 2 Jor B, and so on) and fils in the diskteet structure pointed to by dable with disk characteristics ‘The diskfree_t structure is defined as follows: struct diskfree t 4 ‘unsigned avail clusters; /* available clusters */ unsigned totol-elusters; /* total elusters #/ unsigned nyces per sector; /* bytes per sector */ ‘unsigned sectors per_cluster;/* sectors per cluster */ d Return value _dos_getdiskfree returns 0 if successful. Otherwise, it returns a non-zero Value and and the global variable ermo is set to EINVAL _ Invalid drive specified See Also getfat, getfatd Haciode include Hinclode int main(vois) ‘ stmuct diskéree_t free (Chapter2, The run-time library 7 =a _00s_getdiskfree 1, ong avails (1% set corrent drive to c: #/ = print ("Sotting carzent drive to C:\a"): on “oa_setdrlve(3, soexce\ves /0, _dos_setdive if ( dos getdisktree(0, printf("Error in dos_getdiskfroe(} eall\n" Print ("oe sunber of logical drives is: Sala", aaxdrin return 0 , ' avail = (long) f200.avail_elusters * (long) free. bytes per sect * (long) freo.sectors_ per closter rintt ("The current drive has tld bytes available\n*, avail} dos_getfileatir, _dos_setfilecattr rte, : Function Changes file access mode Syntox #include int_dos_getfleattr(const char “pth, unsigned “ttribp); int_dos_setileatr(const char at, unsigned attrib; dos_getdrive, _dos_setdrive Function Gets and sets the current drive number. Bes [| widoes | mst [Oo ony Synlot Finca : : ' {oid “doe atnvlanignl dr tnsignd nice) Remarks _dos_getleati ices the DOS fie atributes fr thei pth. The Attributes are stored at the location pointed to by attribp. FEE _dos_setiteatr ses the DOS file attributes forthe ipa tothe value : : aunt Remarks _dos_getdrive uses DOS function 0x19 to get the current drive number. The DOS file attributes can be a OR combination of the following : symbolic constants (defined in dos. “dos_setdrve uses DOS function 0 to set the current drive. 1) dos-setdrive stores the tta numberof drives a the location pointed to ARDONLY Read-only attribute By nies, ALHIDDEN Hidden fe .e drive numbers at the location pointed to by drivep are as follows: A_SYSTEM System file | Tor A 2forD,3forGyandsoon ny mPareas “AVOUD Volume abel 3 for, SUBDIR Directory Ratu value None. Use _dos_geterve to verify thatthe current drive was changed CRARCH Archive \ successfully. TALNORMAL Normal ile (no attribute bits set) i See Abo _getew Retum value Upon sucessful completion, _dos_getileatr and_dos_setfileatt return 0, Otherwise, these functions return the DOS error code, and the global varlabie erm setto the following; ENOENT Path orfile name not found ‘Also chmod, stat 4" Get the current drive. */ Example finclude oe getaeive aah) Brisitteie earree dive Le: te Example jinclude int main (void) unsigned disk, maudrives; : | Hnclade costo ent otis int main void os ee n _dos_getiileattr, dos_settileattr ‘char tlenane(128]; tesigaed atte prin(rtaer a te nae feant (st, fUlenamel 1f [dos got lester (lena cartes) t= 01 1 i orror(Moable to obtain fle ateeibotes"): fi ' f Le attse & zooms 1 {ots euretly feucly, aabog 1 read-eie.\o, files bitrib te =A Ot Retum volue fuse ( rlotC(ts czcesly rad-cite, making st resd-only\", flerae) bs A FOO; if ( dos setflleattr(Eilenane, attrib) {= 0) See Also rarerComabie to set file ccelbates)3 return 0; — : dos_getttime, _dos_setftime | Function Gets and sets fie date and sme. \ Syntax #include \ ‘unsigned -dos_gettimetint handle, unsigned *datep, unsigned *tiep); ‘ {unsigned “dos_setitimetnt handle unsigned date tunsigned time) a \ Remarks _dos_getftime retrieves the file time and date for the disk file associated ‘with the open handle, The file must have ben previously opened using "dos-open, dos. creat, or dos creatnew. dos_gettime stores the date and time atthe locations pointed to by datep and fine. __dos_setitime sets the files new date and time values as specified by date xos_gettime, Sand time. _ [Note thatthe date and time values contain bit fields for referring tothe veten files date and time. The structure of these fields was established by DOS. Both are 16-bit structures divided into three fields. 120 Borland C++ Library Reference Chapter 2, The run-time library -Sos_getftime, _dos_seittime Date: bits 0-4 Day bits 5-8 ‘Month bits 9-15 ‘Years since 1980 (e.g, 9 here means 1989) Time: Dits 0 ‘The result of seconds divided by 2 (e.g, 10 here means 20 seconds) bits 5-10 Minutes bits 11-15 Hours _dos_getftime and _dos_setttime return 0 on success. In the event of an error return, the DOS error code is returned and the global variable errno is set to the following: EBADF Bad file number ftat, stat ude include nt maintvoid) PILE ‘stream; unsigned date, tine: AF ((stvean ~ fopen(°TES7.$89%, "W")) == MOLL) ( etdarr, "Cannot open output fie-\n"}; “os getftine(fileno|strean), sate, Stine rink (*File yoor of TEST-595: Ad\n" (date >> 9) & OTE) + 1980); date = (date 6 OxlEt) | (21 << 9) dos_setftine(Eileno[strean), dato, tine); Brintt see tite year to 2001-\8"1; foloselstrean); return 0; dos_settime Gets and sets system time, ‘include void _dos_gettime(struct dostime_t *timep); unsigned dos_settime(struct dostime_t *timep); 121 dos_settime 5 [WR | Wines [GTC [wy : : t Remarks _dos_gettime fills in the dostime_t structure pointed to by timep with the Retum value See Also Example Systems current time. _dos_settime sets the system time to the values in the dostime_t structure Pointed to by timep. ‘The dostime_t structure is defined as follows: servot dostine € unsigned ehae hours unsigned char minute: reigned chaz second unsigned char bsecond: 1 _dos_gettime does not retum a value. If_dos_settime is successful, it returns 0. Otherwise, it returns the DOS error code, and the global variable ermo is set to the following: EINVAL Invalid time dos_getdate,_dos_setdate,_dos_settime, stime, ime 1 hours 0-23 #/ [* miutes 0-59 47 1 seconds 0-59 */ I handredths of sacends 0-89 +/ Hoelade Hoelade “sto. “oa.t> int main(voie) t steuct dostine t ty os gett ina et) DrioE(the current tine is: awcond, second 2 return 0; 1 1 trarple for dos getting. */ 024: 8024.402d\o", tohour, toninate, Hnelude include nt main(void) /* Example f os_settine. +7 struct dostine_t reset; reset-hour = 177 reset.ninte + 0; reset.second = 0; eset haecond = 0; Borland C++ Ubrary Reference _dos_gettime, _dos_settime prlntt("settiag tine to 5 PM.) vos_sattine(ereset) Syston eine") _dos_getvect Function Gets interrupt vector Syntax include void interrupt*_dos_getvect(unsigned interruptna) 0; es [we | Wee | st | ony Every processor ofthe 8086 family includes a set of interrupt vectors, numbered 0 to 255, The 4-byte value in each vector is actually an address, ‘hich is the location of an interrupt function. _os_getvect reads the value of the interrupt vector given by interruptno and returns that value asa (far) pointer to an interrupt function. The value of interruptno can be from 0 to 255. Remarks Retum value _dos_getvect returns the current 4-byte value stored in the interrupt, Vector named by interruptno, See Also _dos_setvect Example actus include coe. Higdet _ cplusplus eZine — conan felse ‘refine _comesas fendit void lnterrupe get_out (_cPeaos void incersupe [toldfund) (_cPPARGE); /* sonesrope fs 1% interrupt prototype */ {nt looping + 1; int asin veld) to teminate"); 1+ save the old interrupt */ feldfune = dos getvest (5); Chapter 2, The run-time ibrary 123, oe _dos_getvect -dos_setvect ecript handles */ fifdet _eplospius ery fdcFine __copnsas . fetse 1 do nothing */ Hdetine _covancs [7 restore to original invezzipt rot ine */ feoaie sachet void interrupt ( MoldhandLex) (_cePARGS); Sat count i} | old interrupt handler (_cPPN65) | void interrupt gbt_out (_CPPARSS) ( t leopiag = 0; /# change global var to got ost of loop */ court [+ increase the global counter 4/ ’ ldbasdies(}; /* eal the old routine */ 1 _dos_setvect _ 17* save the old intecrupt vector */ Function Sets interrupt vector entry. oldhandier = getvect (M08); i Syntax #include (> soatall the nev intecrapt handler */ void dos_setvect(unsigned inlerruptno, void interrupt (sr) 0); sotvoct (TM, handle: Le 1 Loop until the cout aol ir | wnoos | wre [ore | vine (couat < 20) 7 . printf("count is td\n" the old snverrupt handler */ IMT, oldeandler); Remarks Every processor of the 8086 family includes a set of interrupt vectors, numbered 0 to 255. The 4-byte value in each vector is actually an address, ‘which isthe location of an interrupt function. ‘ _dos_setvect sets the value of the interrupt vector named by inferrupino f toa new value, isr, which isa far pointer containing the address of a new interrupt function. The address of a C routine can only be passed to is if that routine is declared to be an interrupt routine. dos_write we er eee ee Function Writes to a file you use the prototypes declared in dos.h, simply pass the address of an {interrupt function to_dos_setvect in any memory model, Syntax include { Retum value None ‘unsigned dos wrte(int handle, void far “uf, unsigned fen, unsigned *nwritten); See Also _dos_getvect | Example je ys isa tern sceceeoatin, You can YT cme eis iogan with > : fest Stack Overflow tarned 0 snd ge on eacotabe fle bleh Pll operate correctly. #1) Remarks _dos_write uses DOS function 0x40 to write len bytes from the buffer fiers cto» pointed fo by the far pointer buf tothe ile associated with handle ee : “dos_write doesnot translate a infeed character (LF) toa CR/LF pair | 7 Because all its files are binary files. fdetie DR One. the cock tek Insect #7 | \ 124 Bortond C++ Library Reference CChepter 2, he run-time library 25 | Fs Return value See Also Example dostounix Function Syntax. 126 ‘The actual number of bytes written is stored at the location pointed to by rmritten. If the number of bytes actually written is less than that requested, the condition should be considered an error and probably indicates a full disk For disk files, writing always proceeds from the current file pointer. On devices, bytes are directly sent to the device, ‘On successful completion, _dos_read returns 0. Otherwise, it returns the DOS error code and the global variable errno is set to one of the following: EACCES Permission denied EBADF Bad file number _dos_open,_dos_creat,_dos read include dos. fSnelude Hinelude st masngvosa) fi unsigned cous: at handles char butt 856008" /* create a file containing 10 bytes */ creat ("OURH.FILY, _A HOHMAL, handle) 1= 0) ( F("inable to create Dina PIL"); retaca Ly ' Af (dos ite thandle, but, strlen(ouf), scount) != 0} perroe "Unable to write to OD.PIL) return 1; dos closo handle) Fetute 0; ' close ehe file #7 Converts date and time to UNIX time format. include long dostounix(struct date “A, struct time *); Borland C++ Library Reference Remarks Retumn value See ako Exomple drawpoly Function syntax Remarks Chapter 2, The run-time itbrary 7) dostounix dostounix converts a date and time as returned from getdate and gettime into UNIX time format. d points to a date structure, and f points to a time structure containing valid DOS date and time information, ‘The date and time must not be earlier than or equal to Jan 1 1980 00:00:00, UNIX version of current date and time parameters: number of seconds since 00:00:00 on January 1, 1970 (GMT) unixtedos: cet Hixclnde Hnclode main(vold) ine, ine (tin = dostounitéd date, 64 thse) asctine(locs}) Draws the outline of a polygon. ‘include void far drawpoly(int mumpoints, int far *polypoints); awpoly draws a polygon with numpoints points, using the current line style and color. “polypoints points to a sequence of (numpoints x2) integers. Each pair of integers gives the x and y coordinates of a point on the polygon. var Return value See also i Example 128 In order to draw a closed figure with m vertices, you must pass n+ 1 return Oy Ce ean cee = dup Sn int main(void) DOS | ONIX | Windows | ANSI C | Co only epg tee asa Remarks dup creates a new file handle that has the following in common with the ni pe at i Se ope, = fervoreods « qraphrestlt ‘msame access mode (read, write, read/write) se eect See learn eee ‘hand is a file handle obtained from a_creat, creat, open, open, dup, or fame ee et ee Soe ee y{S] = maxy - 20; Exomple finclude Arampoly(5, poly): (* dvaw the polygon */ y+ clean op */ poten: losegrapa tl: void floeh(@IUE *etrean) nainivoid) f Fug char aggi) = "This 4s a testy J cceate 0 tile “7 Borland C++ Library Reference | jj. Chepter2, The rurrtime lorary 129 dup dup2 4p = fopon("00.ETL", “Hy ‘m same file pointer (that is, changing the file pointer of one changes the f (tp) 4 other) eae usame acess mode read, wnt, read/write) e ddup2 creates a new handle with the value of newhandle I the file a ta associated with newhandle is open when dup2 is calle, the file is closed. yy ehh the data to onaeee2u without elestg 18 */ newhandle and oldhandle are file handles obtained from a creat, open, dup, ‘lush (fp); or dup2 call. bento ated ss ay hey to Retum value dup2 returns 0 on successful completion, ~1 otherwise. setens \ In the eventof error, the global variable ermo is set to one ofthe following i tse ee EMFILE Too many open files | a EBADF Bad file number ) ‘See also _close, close, creat, creat, creatnew, creattemp, dup, fopen,_open, open vote tosh eras Sse) Example finclude ie eft > 1 tuys o's ude flush stream; 1 make a duplicate phandle = dept filon ude ne STOONT nt main(voia) t int fpte, oldstdot char aag{] = "Tis is a test 1 close duplicate handle to flush Dos buffer +/ lose (phandlel D> exeate a file +7 {ptr = open(*DOM.FIL", O.CREAT | 0 KONE, § TREAD | § WRITE); dup2 if pen ee eeeeeeeeeeSeSFSFSFSFSSSSFS Wcreate a duplicate handle for standaed output */ ldstdout = dup(ST0000); Function Duplicates a file handle (oldhandle) onto an existing file handle (newhandle). x sinc! 1 rodixect standard outpit to DOMH.PIL by doplicating the */ Syntax include 1% Eile handle onto the fle handle for standard output 47 int dup2intoldhandle, int newhandle); up2ctpte, sT0007): foe DmM.FIL +/ [ Ct [ (ete /* thie wll be rediractd into OOATFL */ Remarks dup2is not available on UNIX System IL ite (SOO, no elon) 7 dlup2 creates anew file handle that has the following in common with the J+ restore ovignalstandcd output bande */ original file handle: . dup2(otéstdout, stD00T) + [+ close the duplicate handle for STOUT +/ same open file or device close oldstdout 130 Borland C+ Library Reference | = Chapter 2, The run-time library 131 ‘dup2 print setatn OF rot opening fsle!08) Function syntax Retum value See also Example Converts floating-point number toa string. include char “ecvt(double value, int ndig, int *dec, int *sign); ecvt converts value toa null-terminated string of ndig digits, starting with the leftmost significant digit, and returns a pointer to the string, The position of the decimal point relative to the beginning of the string is stored indirectly through dec (a negative value for der means that the decimal lies to the left of the returned digits). There is no decimal point in the string itself. Ifthe sign of value is negative, the word pointed to by sign is nonzero; otherwise, it's 0. The low-order digit is rounded. The return value of eovt points to static data for the string of digits whose content is overwritten by each call to eovt and fevt. fevt, gevt, sprintt include mt main(voia) t har *atringi ouble value nt dec, siga, aig = 20; value = 9.876; string = ecvt value, aig, ade, ssignd: printt bev = 80 ie = Sits stingy deep atge) value = dig 155 stelag = eove (value nig foe 590) ntf("string = te doc = M4 sign = d\n", string, dec, signs value = 0.678968; /* scientific notation */ nig = 5: fering = eovt (valve ndlgy 420, <9) peint((ateing « ts dec = M4 sign = tele", string, dec, olen): Borland C+ Library Reference ellipse Function syntax. Remarks Return value See also Example Draws an elliptical are. include void far ellipse(int x, int y, int stangle, int endangle, int radius, int yradius); [as [wm Ts ellipse draws an elliptical arc in the current drawing color with its center at (xy) and the horizontal and vertical axes given by xradius and yradius, respectively. The ellipse travels from stangle to endangle. If stangle equals 0 and endangle equals 360, the cal to ellipse draws a complete ellipse, ‘The angle for ellipse is reckoned counterclockwise, with 0 degrees at 3 o'clock, 90 degrees at 12 o'clock, and so on, ‘The linestyle parameter does not affect arcs, circles, ellipses, or pie slices. Only the thickness parameter is used. None. are, circle, fillelipse, sector Sinclude Hnelade eal iat Hinclade Haelude nt main (void) c 1° woquest autodetection */ dnt gdriver = DETECT, gnode, exrorcodes Sine mid, mie int tangle = 0) endangle fmt xradias = 100, 0; 3 = 805 1+ inicialize graphice and locel variables ¢/ initgraph(tgériver, sgnode, *) 17> road roeult of Inietalization +/ fetrorcode = graphresult (17 OK) (J an ne eceurred */ Chapter 2, The eun-time ltsrary 133 ellipse getenths exit: 41% terminate with ap exzoe coe */ idx = gotnanet) / 25 andy = geteany() / 2 ort}: P* draw ellipse */ eLlipsetnids, midy, stangle, endangle, xxadius, yeadivs) 1 clean vp #7 gett elosegcaphtl return 0; Function Syntax. Description 134 Inserts literal values directly into code. include void __emit__(argument, ..) == ES TES] _emit__ is an inline function that ets you insert literal values directly Into object code as it is compiling, It is used to generate machine language instructions without using inline assembly language or an assembler, Generally the arguments of an __emit__call are single-byte machine instructions. However, because of the capabilites of this function, more complex instructions, complete with references to C variables, can be constructed. ‘You should only use this function if you are familiar with the machine ‘You must pass at least one argument to __emit__;any number can be given. The arguments to this function are not treated like any other function call arguments in the language. An argument passed to ___2mit__will not be converted in any way. ‘There are special restrictions on the form of the arguments to __emit Arguments must be in the form of expressions that can be used to initialize a static object. This means that integer and floating-point constants and the addresses of static objects can be used. The values of such expressions are written to the object code at the point of the cal, exactly as if they were being used to initialize data. The address of a ‘parameter or auto variable, plus or minus a constant offset, may also be used. For these arguments, the offset of the variable from BP is stored. ‘The number of bytes placed in the object code is determined from the type of the argument, except in the following cases: 1 Ifa signed integer constant (Le. 0x90) appears that fits within the range ‘of 0 to 255, itis treated as if it were a character. uf the address of an auto or parameter variable is used, a byte is written if the offset of the variable from BP is between -128 and 127; otherwise, a word is written. Simple bytes are written as follows: snit_ _(0300) If you want a word written, but the value you are passing is under 255, simply cast it to unsigned as follows: it _(0868, (uesigned} 7); enit__{0s88, 170); ‘Two- or four-byte address values can be forced by casting an address to void near * or vold far *, respectively. language of the 60x86 processor family. You can use this function to place Return value None. arbitrary byte inthe instruction code ofa fonction if any ofthese es Con ee are incorrect, the program misbehaves and can easily crash your machine. one Borland C++ does not attempt to analyze your calls for correctness in any dnt maintvoid) way If you encode instructions tat change machine regiters or mernay, - Borland C++ will mot be aware oft and might not propetly preserve OO eee | registers, ast would in many cass with nine asembly language or it monn (ms example, it recognizes the usage of SI and DI registers in inline 2 instruction), You are completely on your own wth this function Borland C++ Library Reference = Chapter 2, The run-time library 6 eof eof 136 Function Remarks Retum value See also Example Checks for end-of file. include {nt eof(int handle); eof determines whether the file associated with handle has reached end- of file. If the current position is end-of fie, eof returns the value 1; otherwise, it returns 0. A return value of -1 indicates an error; the global variable errno isset to EBADF Bad filenumber clearerr, feof, ferror, perror netude inelade include finelude Sine main (vote) t LUE *tonp file nt handles char neal] sis As » vest, chy 1% create a unique temporary file */ if (Temp file = empeile()) == ROLL) ( error "OPENING FILE:"); exit 1% got handle associated with handle = fleno(tenp_ file) 1% weice some sata to the tite +/ writetbandle, meg, stelen(aoe)); J+ sock to the beginning of the file */ Jecek handle, Ol, SEEK SET); Borland C+ Library Reference ) white (eof handled) 1+ close and ranove felosettenp_fllel; urn 0; 3 temporary file +7 execl, execle, execlp, execipe, execv, execve, execvp, execvpe Function syntax Loads and runs other programs. include int execl(char ‘path, char *arg0 “argi, int execle(char *path, char *arg0, *argl, int execlp(char *path, char *arg0,*argl, int execlpe(char *path, char "arg0, argl, _ Yargn, NULL); , argu, NULL, char eno); | "arg, NULL); _ "argn, NULL, char *en0); int execv(char *path, char “argol); int execve(char ‘path, char *argu(}, char **env); int execvp(char *path, char *argul)); int execvpe(char “path, char "argol], char *env); 3a [aioe [are Te £ I “The functions in the exec... family load and run (execute) other programs, known as child processes. When an exec... call succeeds, the child process overlays the parent process. There must be sufficient memory available for loading and executing the child process. ti is the file name of the called child process. The exec... functions search for path using the standard DOS search algorithm: ‘af no explicit extension is given, the functions search for the file as ‘given. Ifthe file is not found, they add COM and search again. If that ‘search is not successful, they add .EXE and search one last time. 121 an explicit extension or a period is given, the functions search far the file exactly as given. ‘The suffixes |, vp, and e added to the exec... “family name” specify that the named function operate with certain capabilities. p_ The function searches for the file in those directories specified by the DOS PATH environment variable (without the p suffix, the function searches only the current working directory). Ifthe path parameter Chapter 2, The run-time irary 137 ‘execl, execle, execip, execipe, execv, execve, execvp, execvpe does not contain an explicit directory, the function searches first the ‘current directory, then the directories set with the DOS PATH environment variable. 1 The argument pointers (arg0, agi, .., argn) are passed as separate arguments. Typically, the I suffix is used when you know in advance the number of arguments to be passed. v- The argument pointers (argu{0} .., agin) are passed as an array of pointers. Typically, the v suffix is used when a variable number of arguments is to be passed, @ The argument env can be passed to the child process, letting you alter the environment for the child process. Without the e suffix, child ‘Processes inherit the environment of the parent process. Each function in the exec... family must have one of the two argument- specifying suffixes (either | or v). The path search and environment inheritance suffixes (p and e) are optional. For example, mexecl is an exec... function that takes separate arguments, searches only the root or current directory for the child, and passes on the parents environment to the child. mexecype is an exec... function that takes an array of argument pointers, incorporates PATH in its search for the child process, and accepts the env argument for altering the child’s environment, ‘The exec... functions must pass at least one argument to the child process (arg0 or argo[0); this argument is, by convention, a copy of path. (Using a different value for this Oth argument won’t produce an error.) Under DOS 3.x, pat is available for the child process; under earlier versions of DOS, the child process cannot use the passed value of the Oth argument (arg0 or argof0). ‘When the I suffix is used, arg0 usually points to path, and argl, ....argn ppoint to character strings that form the new list of arguments. A ‘mandatory null following argn marks the end of the list. ‘When the e suffix is used, you pass alist of new environment settings through the argument env. This environment argument is an array of character pointers. Each element points to a null-terminated character string of the form enoar = value 138 Borland C++ Ubrary Reference it Return value See also Examples ach function has ‘execl, execle, execlp, execipe, execv, execve, execvp, execvpe ‘where enrvoar is the name of an environment variable, and value is the string value to which envoar is set. The last element in eno is null. When env is null, the child inherits the parents’ environment settings. ‘The combined length of arg0 + argl +... + argn (or of argol0] + argof1] +argnin), including space characters that separate the arguments, must be less than 128 bytes, Null terminators are not counted. ‘When an exec... function call is made, any open files remain open in the child process. If successful, the exec... functions do not return. On error, the exec... functions return -1, and the global variable errno is set to one of the following: E2BIG Arg list too long, EACCES Permission denied EMFILE Too many open files ENOENT Path or file name not found ENOEXEC Exec format error ENOMEM _ Not enough core abort atexit,_ exit, exlt,_fpreset, searchpath, spawn..., system include Hinclade nt main(int arge, char *aegvt)) at gatene "PATE forts = 0; 4 Cages 444) grlbd): Nao", i, angela return 0; dude iis own example Sgro Hacluse fmt nain{int exge, shar Fargvl)) fl nt 1eop: printf (*s ronieg...\n\o", argv10)): S€ {ange == 1) (_/* chock for only one command-line paraneter */ printf(ts calling Staalé again...\a") argvl0)): veel arge[0}, argv(0], “ONE, "EHO", MTHREE®, ULL) peezor("3x@0:"); Chapter 2, The run-time library 139 ceclp, execipe, execv, execve, execvp, execvpe xecle, execip, execipe, execy, execve, execvp, execvpe execl, execk exis 1 return 0: einte(*s called with axgomacs:\ot, axgr0)): : for (oop * 1; loop < azger loop uts(orgr(loopli;, /* display alt comand-Line paraneters */ Anelude : Ainelode cero. 2> fnt main(int arge, char argv], char **on0p) cae process.» ( Helis sot ts Hinelude printé(*Coamand Line argunents:\a"t: Hnclade for (0) 4 < argc; ++i) foclade print e(*(t2a) Aaa, axge(iDs prlnte('about to exse child with argl arg? ...\a"): fxeclpe *CHLLD.2N6", “CHILD.EYG", *azgl*, "arg2", MOLL, emrpl; perror exec ere0:") int mip(int arge, char Vargv{l, har tenv()} t in ts — ‘char *new ene{] = ( "TESTING, MULL}: ; 7 felieets mnags nr et Te aren I) ehh on om comand parame +/ prise ealing geld apnea sept Hele ceric. Sisley, tt, STE ity nex a tinlee talon Peete tint cern : . ‘void main{int arge, char targv[}) c print (%omand Lise azgunness\ for (0; Lcarge; is4) printt ("bs called with arguents:\a", sxgv{01)s for (loop = 1; loop < 9x50; loop+t) puts(argllesp]i?— /* display alt command-line parameters +/ 1% display the facet envLeonnent parameter */ prints (*[¥24) + telat, Ly axgvlilds print "valve of env{0): ts\n"yenr(0}}: print "out to exec child with argh arg2 «..\0")s return 0 fexecu("CHILD.BHE", argv) 1 error "exec exroe"): exit (is Hnelude Hinclade cecio. Hclude cers. include nt main(int age, char *argvlly char *enep) eee 5 ‘snclade cersno.b> int 4; void main(int arge, char tarqv(], char **enp) print (*couand Line argumenter\n"): t for (ied) 1 < arger #41) iat printed} ts\e", iy argelin: printf ("Command Line arguneats:\a")z print ("about to exec Shulé with orgl ang2 «..\a4)7 for (0; Large; #71) execlpe "CHILD 2X8", *camLD.exE", "arg", vazg2*, NULL, empl: peint#(*[2d) : Sela", 4, argv}: pexzor exec error": printf("aboot to exec calla vith arg] Ao") exit (is fexecve(°CHTLD.FHE", argv, enyp); perzor("exec error") 140 Borland C++ Library Reference CChapter2, The runtime lrary 141 execl, execle, execip, execipe, execv, execve, execvp, execvpe ~exit exit): ' Hactude void _exit(int status); Borland C++ Library Reference ext Remarks _exit terminates execution without closing any files, flushing any output, ‘or calling any exit functions. ‘The calling process uses slalus as the exit status of the process. Typically a value of 0 is used to indicate a normal exit, and a nonzero value indlicates Rotum value None. q Soe.also abort, atexit, exec.. Example jinclude Hnclade cetdio.> void done(void); int main void) tC : 4 void done C printe(eo\a")? ' exit Function Terminates program, Syntax #include void exitfint status); Remarks exit terminates the calling process. Before termination, all files are closed, buffered output (waiting to be output) is written, and any registered “exit functions” (posted with atexit) are called. status is provided for the calling process as the exit status of the process. Typically a value of 0 is used to indicate a normal exit, and a nonzero value indicates some error. It is set with one of the following, EXIT_SUCCESS Normal program termination. Chapter 2. The run-time library 143 } exit EXIT_FAILURE Abnormal program termination: signal to operating system that program has terminated with an error. Retum valve None Seealso abort, atexit exec... _exit, Keep signal, spawn. Example pctude fineled Hiselade cai > fot minivose) { int states prieté(oner either 1 oF 2A" estes = oes frit (eatin 107); [+ ate 08 ere ved $/ feutn (Sots Thi Line in mv reached */ ' expl ae Function Calculates the exponential eto the x. Syntax Real versions: Complex version: +#include ‘include double exp(double »); complex exp(complex.0; Jong double expl(ong double 2); ox! foatoxp Complexe : Remarks exp calculates the exponential function e* expl isthe long double version; it takes a long double argument and returns a long double result. The complex exponential function is defined by expla + = expCo (costy) + isin(y)) Retum value exp returns e. Sometimes the arguments passed to these functions produce results that overflow or are incalculable. When the correct value overflows, exp Borland C++ Library Reference See Also Example exp, exp returns the value HUGE_VAL and expl returns LHUGE_VAL. Results of excessively large magnitude will cause the global variable erro to be sel to ERANGE Result out of range (On underflow, these functions return 0.0, and the global variable erm is not changed. Error handling for these functions can be modified through the functions matherr and _mathertl {rexp, Idexp, log, log10, matherr, pow, powt0, sqrt Hioclude fnclade coat int main(voie) fl double result, pts); £(0¥e! ralsed to the pover of Af (e * #21) = Aen", x, x, result) return 0 , fabs! fabs Funetion syntax Remarks Retum value See also, Example Returns the absolute value of a floating-point number. ‘include double fabs(double 2); long double fabsi(long double 2); fabs calculates the absolute value of x,a double, fabs! is the long double version: it takes a long double argument and remmns a lang, deutle result fabs and fabs! return the absolute value of x abs, cabs, labs include Int main(vose) t Chapter 2, The run-time irary 45 fobs, fabs! farcalloc float nanber = 1234.05 printe("ouber: ¥€ absolute value: Af\n", munber, fabs(munber retorn 6; Function syntax Remarks Return value See aso Example 14% Allocates memory from the far heap. include void far *farcalloc(unsigned long nunits, unsigned long units2); = [at [ee a {farcalloc allocates memory from the far heap for an array containing ‘units elements, each unitsz bytes long, For allocating from the far heap, note that ‘wall available RAM can be allocated. mblocks larger than 64K can be allocated. 1 far pointers (or huge pointers if blocks are larger than 64K) are used to access the allocated blocks. In the compact, large, and huge memory models, farealloc is similar, ‘though not identical, to ealloc. It takes unsigned long parameters, while cealloc takes unsigned parameters. ‘A tiny model program cannot make use of farealloc. farcalloc returns a pointer to the newly allocated block, or null if not ‘enough space exists for the new block calloc, farcoreleft,fartree, farmalioc, malloc Haciuse include <1l00.1> include int main(voia) char far Afpte, Sate = "allot 1 allocate nenary for the far pointer */ {ptr = (char far #) farcalloc.0, siz 1 copy “Bello* into allocated memory */ Borland C++ Library Reference farcatloc 1 Wote: sovedata 1s used because you might be in a snall date model, in vied case a normal string copy routine can not be used since it assumes the pointer size {+ near. */ novedata(fO SEG(cte}, FP_OFF(ste, Fe su pte), FEOF? pte), stilea(ste) 1 display string (note the F modifier) +/ print (Far string is: 88s\n", fer); 1° G90 the mony */ fartree( ots): retarn 0; farcoreleft Function Returns a measure of unused memory in far heap. Syntax #include unsigned long farcoreleft(void); us | ir | widow | ast [or oy Remarks farcoreleft returns a measure of the amount of unused memory in the far heap beyond the highest allocated block. ‘A tiny model program cannot make use of farcoreleft. Retum value _farcoreleft returns the total amount of space left in the far heap, between, the highest allocated block and the end of available memory. See also corelett,farcalloc, farmalioc Example finclode Hinclode nt main vole) print ("The ditterence betveen the hichest allocated block in the far\s Drinte(*eap and the top of the far heap is: Hu bytet\a", fercocelefe()) return 0; ,, Chapter 2, The run-time rary va forttee farfree Funetion Frees a block from far heap. syntax include void farfree(void far * block); Bs | WK] Windows | mse =a Remarks farfree releases a block of memory previously allocated from the far heap. A ny model program cannot make use of farfree. In the small and medium memory models, blocks allocated by farmalloc ‘cannot be freed with normal free, and blocks allocated with malloc cannot bbe freed with farfree. In these models, the two heaps are completely distinct. Return value None, Seealso farcalloc, farmalloc Example sincivse Hinelude Hiaclude ceteing. > inclu costo nt main (void) ar "pte, tate = "Bello"; + allocate aanory for the far pointer */ fpte = (ohar far *) farcalloc(1O, sizeof char): J+ copy *Hello* into allocated nenory */ 7+ Note: aovedata is used because you night be in a snall data nodel, in whict cage a nome string copy routine can't be used since Lt eesuses the pointer size is near. */ ovasata(F2 SEb(ote), FP_0FF\ Festa peel, FEOF ay 1 aisplay string (note the ¥ modifier) */ printf (ar string is: A@s\n", fer): 1° f290 the memory #7 farfree fpte}2 return 0; 48 Borland C++ Library Reference farheapcheck | fatheapcheck Function Checks and verifies the far heap. Syntax include int farheapcheck(void); Remarks _farheapcheck walks through the far heap and examines each block, checking its pointers, size, and other critical attributes. Retum value The return value is less than zero for an error and greater than zero for success. HEAPEMPTY is returned if there is no heap (value 1). HEAPOK is returned if the heap is verified (value 2). HEAPCORRUPT is returned if the heap has been corrupted (value ~1), See also _heapcheck Example include fetine min pas 10 faefine MNLBYIES 16 nt sain (void) char far tareay( MIN PTRS 17 rayl i] = (char far *) famalloe( We BITES ); fort = 0; i< mom ptns; i= 2) fertose( arrayl 31) envconnver tf tarheapeheck ) petit “anop to covtopted\" 1: retary ' farheapcheckfree Funetion Checks the free blocks on the far heap for a constant value. Chapter 2, The run-time itsrary 149 fatheapchecktree ‘syntax. Retun value See ako Exomple include int farheapcheckfree(unsigned int fillvalue); Tes [oe | wiedes | Te [Oo oly The return value is less than zero for an error and greater than zero for _HEAPEMPTY is returned if there is no heap (value 1), “HEAPOK is returned if the heap is accurate (value 2) THEAPCORRUPT is returned if the heap has been corrupted (value -1). TBADVALUE is returned ifa value other than the fill value was found (value-3). farheaptiliiree, heapchecktree ie Finelude dotine Mees 10 define MIMCBYTES 16 hae far ‘array NOM FTES]; int Ay 5y 30s t= 0; 1 < NOMLPTRS: S94) if ((orvayll] ~ fehar far *) fazmalloc WM BYTES)) printi(o menory for allocation\a return 1 1 for (i= 0; 4 < mMLpTRS; 4 + 2) tartree(arraylilh aay 4 sf tfarheaptini treet} < 01 1 inet ("Bap corrupted. 8": 1 foe = Ly $< MUM_PTR5; A + 2) for = 0; j < RM BITES) 54) seraylil(3) = OF ree » forbespcheckfree (2): sf (02 < 0) switoh(res) ( cage _BEAPCORRURE Borland C#+ Library Reference fatheapchecktiee printt (asp corrupted.) printE("ad value in fsee space. nth: return 1; etal printf {"inknown eesoe.\o8) ) printf (est return 0; , setal. farheapchecknode Function syntax. Remarks Retum value Seo also Example Checks and verifies a single node on the far heap. include int farheapchecknode(void *node); Ifa node has been freed and farheapchecknode is called with a pointer to the freed block, fatheapchecknode can return _BADNODB rather than the expected _FREFENTRY. This is because adjacent free blocks on the heap are merged, and the block in question no longer exists. ‘The return value is less than zero for an error and greater than zero for -HEAPEMPTY is returned if there is no heap (value 1), ~HEAPCORRUPT is returned if the heap has been corrupted (value ~1) —BADNODE is returned if the node could not be found (value ~2). FREEENTRY is returned if the node is a free block (value 3). “USEDENTRY is returned if the node is a used block (value 4). heapchecknode include include alloc. {define MIN praS_10 define MICBYIES 16 int main (void) | Chapter 2, the run-time library 151 farheapchecknode farheapfillfree Funetion syntax Return value 182 char far tercoy{ MOM PORS 15 fort §= 0; 4 < mMLPIES: S44 ) ‘array { J = (ehar far *) farmalloc{ MOLBYRES ); fost $= 0; 4 < RM PIRS: 5 22) fartreol acrayl i] fort = 0; 1 MMPTRS; Ste) lat ("ede 123 *, 1) fwitoh( farhoapehecknode( azzayl 1) Db ( case ERODE: printé ("ho heap. 8" J break case _HEADCORUET: HintE (*eap coerupt. An") Dreaks case BODE! Hint ("Bod node. An" J; Deeaks nee _FREZENTRY: ‘rin ("Pree entey.\a 9: breaks 200 _USEDRNGRY prints ("Used entey.\2" }: breaks cegseit: printf ("Uskaown return code." breaks Fills the free blocks on the far heap with a constant value. include int farheapfilfreo(unsigned int fillvaln ‘The return value is less than zero for an error and greater than zero for _HEAPEMPTY is returned if there is no heap (value 1). Borland C++ Library Reference farheapfitires _HEAPOK is returned if the heap is accurate (value 2). _HEAPCORRUPT is returned if the heap has been corrupted (value ~1). Seeaiso farheapcheckfree, heapfilfree Example finctude Hnclude include define wm pres 10 define MN BYTES 16 int main(voi) i char far ‘array [NOM P75); int iy jy ress for (k= 0; $< MOM FIRS; SH) Lf (lareayli) = fehar far *) fazmalloc 0M BYTES)) =~ HULL (| print (Wo nemry for allocation\s"}; return 1s , for [i= 0; 3 < MMLPIRS; 4 += 2) fcfeee(arzaylil)s fttarheaptiiiteeett) < 0) ( printt("eap corrupted. \e"); return Jz : for (i= 1; SC MMETRS: A += 2 for (3 = 0; §-< RMBITES: 5+¥) array(a] (3) = OF 05 = farheapchackfree(l): if res < 0) sviteh(zes) 1 case _EADCORROP: pelnte ("Heap cocruptod. a"); print ("Bad value in free space. \ detaate print ("Unknown exzor.\A") return ts ' print ("Test successful. or); etuen 0; 1 Chapter 2, The run-time library 183 farmatioc farheapwalk farmalloc Function farheepwalk is used to “walk” through the far heap node by node. Function Allocates from far heap. syntax include Syntox #include int farheapwalk(structfarheapinfo "hi; void far “farmalloctunsigned long nbytes; oa [war [Wee | mare [or oy oe [mm [wae are [ry * : a. = } Remarks tarheapwalk assumes the heap is correc. Use farheapeheck to verify the Remarks _farmalloc allocates a block of memory nbytes bytes long from the far heap. heap before using farheapwalk. HEAPOK is returned with the last block a ame ‘on the heap. _HEAPEND will be returned on the next call to farheapwalk. ‘or allocating from the far heap, note that fatheapwalk receives a pointer to a structure of type henpinfo (defined in bt coe Lae gan be. — a alloch). For the firs call to farheapwalk, sot the hi-pt field to null. —DLDUrUrUr™LC—s farneapwaik returns with hiptr containing the address of the frst block. 1 far pointers are used to access the allocated blocks. Inisize holds the size ofthe block in bytes. hi.n_use isa flag that’ set if the Inthe compact, large, and huge memory models, farmaloc is similar block is currently in use though not identical to malloc. It takes unsigned long parameters, while Retum value _HEAPEMPTY is returned if there is no heap (value 1). malloc takes unsigned parameters. "HEAPOK is returned ifthe heapinfo block contains valid data (value 2. ‘A tiny model program cannot make use of farmalloc. XD is returned i ‘of the heap has been reached (value 5 “HEAPEND is returned if the end of the heap has been reached ( ». Retum value farmalloc returns a pointer to the newly allocated block, or null if not $20 iso heapwalk ‘enough space exists for the new block. oy ere See cso farcalloc,farcorelet,fartree, farrealloc, malloc Hinelude atte > Exomple fetine MM prRS 14 Hocleée caller. {eetine MOLBETS 16 Hnetede nt nain( void ) Hinelade fi fat main(vote) seract Sacheopiato bs har for saerayl WOW PHS [1 char for septs, Pate © “WoL inet: 1 allocate neory for the far pointer */ fost 4+ 0; 4 < WM PRS; St) sehr far *) farmlloe (20 rapt {| = (bar far *) tarnsloc( SOM 385) (+ copy Mlle" into allocited mnocy +! i= 0; L¢MMLPMIS: § t= 2) 1° sovecta ised becanse ve righ be 1n a stall data mode, in wich cae a taeteee(aeeayt 1) sora fe can not be weed since St asumes he poloter size states\at 97 areata print Nandi Ble fareapuaTk( AL) == _AERROK) DEIBee( Wa Sola, hi.sive, cit gee 2 aaed! = MEee® }2 eyesore pelcetrrar sting Sot Ws\e",fptz)s 184 ' Borland C++ Lbrary Reference | Chapter 2, the run-time lirary 155 farteatioe farmalloc 1% fa00 the menoty +1 farteee(aeptel: faee(iptes setum 0 stor 0 H ) fclose farrealloc Function Closes a stream. Function Adjusts allocated block in far heap. i re i Syntax. #include int felose(FILE *stream); ‘oid far *farealloc(void far “oldblock, unsigned long myles); : ee we | WH | viewer | WATE [oe oy Remarks {close closes the named stream. All buffers associated with the stream are Remarks tarrealloc adjusts the size of the allocated block to nhytes, copying the flushed before closing. Systemallocated buffers are freed upon closing. contents to a new location, if necessary. Buffers assigned with setbuf or setvbut are not automatically freed. (But if errr setvbut is passed null forthe buffer pointer, it will free it upon close.) ee Retum value felose returns 0 on success It returns EOF if any errors were detected. blocks larger than 64K can be allocated ‘See also close, fcloseall,tdopen, tush, tlushall, fopen,freopen 1 far pointers are used to access the allocated blocks. eo A tiny model program cannot make use of farrealoc. close Retum value _farrealloc returns the address ofthe reallocated block, which might be nt main void) different than the address of the original block. If the block cannot be Ue realloca returns null lee es char buf{21] = *O123486788%7 Seecdlso farmalloc,realloc be ning 10 bytes #7 Example fioclude a ee eee fveste(sbof,stelen(ba, 25 fp ft main oo feclosetfels/* “ fl i char far Mpte: se char far Mevpte eint# ("Unable to open filef\atz = (char far *) fermaldoc(t6); i peinte(*Pizse address: pln", ft: (We use a second pointer, neupt arzeallect returning WILL, oor original pointer is not set to HULL. #/ fcloseall Function Closes open streams. 186 Borland C+ Library Reference | 4 Chapter2, The ruretime library 187 fcloseall Syntox. Remarks Return value See also Example fovt Function syntax 158 include int floseall(void); ta [WR | wien | mare fcloseall closes all open streams except stdin, stdout, stdpen, stderr, and stdaux, {closeall returns the total number of streams it closed. It returns EOF if any errors were detected. {close, fdopen, flushall,fopen, freopen include int nain(voia) nt streams closed 1+ open two streams */ fopen("DIANY.ONE", *¥"); fopen(*omae THO", "¥)? 1+ close the open streans */ streang_closed + fcloseall{): if Istroans_closed = porzor(*Brcor) J+ taaue an exror message */ else [print result of feloseall() function */ printf("éd streans wore closed.\e", steeans closed); return 0 Converts a floating-point number toa string. include char *fevt(double oulue, int ndig, int “dec, int *sign); Borland C++ Library Reference Remarks Retun value See also Example fdopen Function syntax. tovt fevt converts value to a null-terminated string digits, starting with the leftmost significant digit, with ndig digits to the right of the decimal point. {fevt then returns a pointer to the string, The position of the decimal point relative to the beginning of the string is stored indirectly through dec (a negative value for dec means to the left of the returned digits). There is no decimal point in the string itself. Ifthe sign of wulue is negative, the word pointed to by sign is nonzero; otherwise, itis 0. ‘The correct digit has been rounded for the number of digits to the right of the decimal point specified by nig. ‘The return value of fevt points to static data whose content is overwritten bby each call to fevt and eevt. ecvt, govt, sprintt finelude cota. include int main(void) fi char sate: double int dec, siga, sdlg = 8 1% a regular number */ un = 9.876; ou, ig, toc, ésigals ring’ Ms decimal place = 4d sign = td\o", atx, dee, stem): 1 a negative ausber +) tn = 123.457 = fevt teu, ndig, sec, asia: priate (string ~ 410s dacinal place = 4d sign = td\ot, ste, dec, sign): J selentifie notation */ ‘umn = 0.67857 Str = fevt nan, nig, Secs asignhz prince (atring = 410s declnel places ta sign = Adis, ste, dec, sign) return 0; Associates a stream with a file handle. include FILE "fdopen(int handle, char "type); (Chapter 2, The eun-fime library 159 tdopen 160 Remarks Retum value See also Example {idopen associates a stream with a file handle obtained from creat, dup, ddup2, or open. The type of stream must match the mode of the open anal. ‘The type string used in a cal to fdopen is one of the following values: + Open for reading only. w Create for writing, 2 Append; open for writing at end-of-file or create for writing ifthe file does not exist r+ Openan existing file for update (reading and writing). wt Createa new file for update. 2+ Open for append; open (or create ifthe file does not exist) for update at the end ofthe file. To specify that a given file is being opened or created in text mode, append a tto the value of the type string (r, w+t, and so on); similarly, to specify binary mode, append a b to the fype string (wb, a+b, and so on). Ifa tor bis not given in the fype string, the mode is governed by the global variable _fmode. If_fmode is set to O_BINARY, files will be opened. in binary mode. If_fmode is set to O_TEXT, they will be opened in text ‘mode. These O..... constants are defined in fenth. ‘When a file is opened for update, both input and output can be done on the resulting stream, However, output cannot be directly followed by input without an intervening feeek or rewind, and input cannot be directly followed by output without an intervening fseek, rewind, or an input that encounters end-of-file. On successful completion, fdopen returns a pointer to the newly opened stream. In the event of error, it returns null {close, fopen, freopen, open include include finelode Hiselude ft natn(voia) t Borland C+ Library Reference feof Function Syntax. Remarks Retum value fdopen int handle; 1 open a le +f Tandle = epen("OMet.PIL", 0, ¢REAT, § 1REXD (+ now turn the handle into a stzean */ str0am = fopen handle, if {oteean = 0) Print ("Edepen failed\o") lee { ‘peinté(atvean, Mello v Felose(strean) 1 return 0; Detects end-of file on a stream, include int feof(FILE “stream; feof is a macro that tests the given stream for an end-of-ile indicator. (Once the indicator is set, read operations on the file return the indicator until rewind is called, or the file is closed. The end-of-fle indicator is reset with each input operation. feof returns nonzero if an end-of-file indicator was detected on the last input operation on the named stream, and O if end-of-file has not been, reached. err, eof, ferror, perror main 90 FILE tstrean; ferom = fopen(*DON.FILY, *e"); /* open a foctetstzeam; — /* ceod a character trom th if (foot(stream) —/* check for HOF #/ print®(*ie have reached end-of-file\n" Le for ceasing */ Chapter 2, The eun-fime library 161 ftelove(stseam); return 0 1+ cloae the fie +7 ferror Function Detects errors on stream. Syntax include int ferror(FILE *stream); Remarks ferror is a macro that tests the given stream for a read or write error. If the stream’s error indicator has been set, it remains set until clearerr or rewind is called, or until the stream is closed. Rotum value ferror returns nonzero if an error was detected on the named stream, See also clearerr, eof, feof, fopen, gets, perror Example jinclude naln(vold} 1+ opan a file for uniting */ ‘crea * fopen (‘Da 1% force an error condition by attempting to read */ (void) gate stream Sf (tortor (steean) ( 2} alsplay an exc peinte Error rea 1° test foe error on the stzean */ essage */ ig ron DOM E1D\n"] 5 (> seaot the error and BOP indicators */ return 0; fflush Function Flushes a stream. 162 Borland C++ Library Reference flush Syntax include int flush(FILE stream); of aes | aeons tr Remarks Ifthe given stream has buffered output, tflush writes the output for stream to the associated file. ‘The stream remains open after fflush has executed. tflush has no effect on an unbuffered stream, Rotum value flush returns 0 on success, It returns EOF if any errors were detected. See.also fclose, flushall, setbuf, setvbut Example jieclude Hinelude Hnelade do.0> void flush(PILE vstzean); fl PTtz *streen char asgl} = "This is a test; sain void) P create 2 file */ stsaan = fopen ONE F704, “Wy 18 write some data to the file */ furiteinag, stzlentaeg), 1, stzean); any boy to flush ou PrL:"): petals (J Cush the date to ome flushistzeam ; print ("\ile was flushed, Bese ony key to quits geen: return 0; , without closing it #/ void flush FTLE #2tzean) { nt duphandle (+ stash the stzean’s internal bat losh(strean) bande +f ean}: 1 nako a duplicate 6 upbende = dup (fi len Chapter 2, The run-time library 163 ffiush 1+ close the duplicate tandle to flush the 00S butter lose (duphandle} ” 1 fgetc Function Gets character from stream, Syntex include in figete(FILE "stream; Remarks Agote reurs the next character on the named input stream, Retum value On success, fgete returns the character read, after converting it to an int without sign extension. On end-offile or eror, it returns EOF See alto tgetchar, pute, etc, getch, getchar, getche, ungete, ungetch Example finiudo nt min(voial char string|] = "This is a test, ch 1" opan a file for vant */ ‘toca = fen CU. F012, "0" foie(stcog, strletariagh 1, tee) 1» sak to the bnginming of the file *7 fcekotvey SEBS)! o ean}; /* end a char fron the file */ ; ; shite (ch t= Br 1 168 fortanc C++ Ubrary Reference fgetchar fgetchar Funetion ‘Syntax. Remarks Retum value See also Example fgetpos Funetion ‘Syntax Gets character from stdin, include int fgetchar(void), ‘fgetchar returns the next character from stdin. Itis defined as fgete(stdin). ‘On success, fgetchar returns the character read, after converting it to an int without sign extension. On end-of-file or error, it returns EOF, {getc, fputchar, getchar include : *); 1+ z0ad the character fron stdin */ ch = fyetenar): vos read */ haracter read io: "Bo"\n", eb); Js display wi priate Gets the current file pointer. include int fgetpos(FILE “Stren, fpos_t *pos); aa] cles Chapter 2, The sun-time library 165 fgetpos Remarks Return value See also Example {getpos stores the position of the file pointer associated with the given stream in the location pointed to by pos. The exact value is a magic cookie; in other words, itis irrelevant to your purposes. The type fpvs_t is defined in stdio.h as typedef long fpos_ts. On success, fgetpos returns 0. On failure, it returns a nonzero value and sets the global variable erro to EBADF or EINVAL. seek, fsetpos,ftell, tell include Hirelude Sot aaa (vold) ' IIE *3¢ 20am: far stringl] = "This is a test; £ Eileposs 1° open a file for vpdate */ open("OIRMY.FIL, "w), J write a stcing into the file 47 fweite(steing, strlen|string), 1, stream); (+ report the file pointer position */ sgetpos(oteesn, stLLego printf (the file peinter Se at byte Wd\e', £ilepos) rea, return 0 fgets Function Syntax. Remarks Gets a string from a stream. include char *igets(char*s, int, FILE *stream); fgets reads charactors from strezm into the string s. The function stops reading when it reads either n ~ 1 characters or a newline character, whichever comes first. fgets retains the newline character at the end of . Annull byte is appended to s to mark the end of the string. Borland C++ Library Reference Return value See also Example filelength foots (On success, fgets returns the string pointed to by s;it returns null on end- offile or error. gets, fputs, gots inelude ctsing i> include i char stringl} = "This is a test*; hae mag(20]7 1% open a file for epdate * sezean = fopen(°DI@Y FIL", "Wt"; furitetsteing, strlea(string), 1, steean); T+ eaok to the start o 1 fscek(stzean, 0, SEEK SET) (+ cead a string fren the file */ gets(nsg, strlea(steing) #2, stzean); 1° display toe stetig */ Function Syntox. Remarks Return value See also Gets file size in bytes. #include long filelength(int handle); Ge [WH | Wine [OSE [Or or as filelength returns the length (in bytes) of the file associated with handle On success flelength returns a long value, the file length in bytes. On error, it returns -1 and the global variable errno is set to EBADF Bad file number fopen, Iseek, open (Chapter 2, The run-time library 167 filelength flleno Example sinciude bee) coe en kel Aieelade co. (+ chtain the file handle associated with the stcean*/ eee handle = tilenolstee elude cyst > (+ alepay the handle nutes */ {telus Sse void far fillellipse(in x, int y, int xradius, in yradius); ' [eos [i] winaes| mate [ee oy Le fileno omarks DiWs an ellipse using (xy) a8 a center point and xradius and yradius as the horizontal and vertical axes, and fils it with the current fil color and Function Gets fle handle. alae Symtox include etum value None. int fileno(FILE *stream); See.aiso arc, circle, elipse, plslice (ee ee er Too] Example iecade craps.» [eestlee cao | Fioclade talib Hinctude tatoo Remarks fleno isa macro that returns the file handle for the given stream. If stream Hinelade hhas more than one handle, flleno returns the handle assigned to the a stream when it was frst opened. ' Retu value fileno returns the integer fie handle associated with strea. Earle ery flso tdopen, fopen,treopen wide dy, 7 $00 alto tdopen, fopen, freon ste tation = ot, rade = tr Example {* initialize graphics and local variables */ Initgeeptegécvery dome, "1; {+ read result of initialization */ fr sto trorcode = gapbeilt( fot handles if (errorcode != grtk} | /* an error occurred */ 1 eceate a file */ prinet(raphies erro Saas, graherroragetor 168 Borland C++ Library Reference fer 2, Me run-time Horory te filetipse lowest fillpoly Function Draws an fills a polygon. Syntax #include void far fillpoGint numponts, int far *polypoints; Remarks filpoly draws the outline ofa polygon with munponts points in the current line style and color (just as drawpoly does), then fills the polygon using the current fill pattern and fill color. polypints points toa sequence of (numpoints x2) integers. Each pair of Integers gives the x and y coordinates ofa point on the polygon. Retum value None. See.ako drawpoly,floodiill, graphresult, satfilstyle Example pocinde Finelets talib finclude Ceonie ine inti) 170 Borland C++ Ubrary Reference pelt ("Press any hey to halt"); 1+ ceaminate with on oreo aid = getmoent) / 2 nny = getmany() 25 17> toep vhoogh the £311 patterns */ foe (= BARTY FULL, 4 < OSER ATUL 44) ( 1 sot £501 pattern +7 setfillstyleG, getmancolor(); J+ deay 4 filles altipse */ paoinids, wy, xxadiu getentls ’ 1% clean op */ filpoty 17> soqust avtodetection +/ dnt gariver = DETECE, gnode, ecrorcode; int i, name, marys 1 oor polygon ateay */ int polyle); J soktialize graphics and local variables *7 initgraph égdriver, 6gnode, ""): 1% read rasult of initialization */ errorcode = graphcesult Lf terzotcode = qk) ( /* an exror occurred */ print ("Graphics excor: 4s\a", grapoerrormegerrorcods)) printt (ress any hey to halt"); > veminate with an error cade */ ) van > getmaee(: roxy = getmaxy() yO) = 20; J sree poly} © mony f 2: polg[2]} = maex - 20; /* second vertex */ palyl3) = 20 polyld} = mate ~ St; / third vertex */ palg(S} = maxy - 20; polyl6] = maxx / 2; / fourth, £12tpoly automatically */ poly(7] = maxy / 2 /¥ closes’ he polygon */ ugh the £411 patterns */ Fly $ include Int findlfirst(const char *pathname, struct folk "blk, int attrib); findtirst begins a search of a disk directory by using the DOS system call, OnE. pathname is a string with an optional drive specifier, path, and file name of the ile to be found. The file name portion can contain wildcard match characters (such as ? of *). Ifa matching file is found, the ffblk structure is filled with the file-directory information. ‘The format of the structure fbIkis as follows: stevct lk ( char {€ reserved[21]: [+ reserved by Dns */ char ff attrib; at fda ong #2 fsize char ff_pane 13)2 1° found File sane 8/ f attrib is a DOS file-attribute byte used in selecting eligible files for the search. attrib can be one of the following constants defined in dos.h: FA RDONLY Read-only attribute FA HIDDEN Hidden file FA SYSTEM — System file FALLABEL Volume label FA.DIREC Directory FALARCH Archive For more detailed information about these attributes, refer to your DOS reference manuals. Note that ff ftime and ff flate contain bit fields for referring to the current date and time. The structure of these fields was established by MS-DOS, Both are 16-bit structures divided into three fields. 1 time: bitsOt04 The result of seconds divided by 2 (eg., 10 here means 20 seconds) bits5t010 Minutes Borland C++ Library Reference Return value See also Example bits 11 to15 — Heurs 1 tdate: its 0-4 Day bits 58 Month, bits 9-15 Years since 1980 (e.g., 9 here means 1989) structure to ff ftime, and ff fate. See getttime or setttime for examples. {indfirst returns 0 on successfully finding a file matching the search pathname. When no more files can be found, or if there is some error in the file name, 1 is returned, and the global variable errno is set to ‘The structure ftime declared in io.h uses time and date bit fields similar in. a ENOENT — Pathor file name not found and doserno is set to one of the following: ENOENT — Pathor file name not found ENMFILE No rrore files findnext Hneluse Hinclode nt nain void) server folk fle: sat domes print ("Directory Lsting of *.*\0 one » finafirst(**.°,sffb1t 0) while (done) print(* te\n", ifblk.fE eane) done = findnex (422018); return 0; Program output FIRDERSE.C FINOERST.OBF| 2, The run-time itbrary 173 findnext findinext 174 Function syntax Remarks Return value See also Example Continues findflrst search. include int findnext(struct folk *ff00; ‘ =| I findnext is used to fetch subsequent files that match the pathname given in findfirst. fblk is the same block filled in by the tindffirst call. This block contains necessary information for continuing the search. One file name for each call to findnext will be returned until no more files are found in the directory matching the pathname findnext returns 0 on successfully finding a file matching the search pathname, When no more files can be found, or if there is some error in the file name, 1 is returned, and the global variable erro is set to ENOENT ‘and doserno is set to one of the following: Path or file name not found ENOENT Pathor file ENMEILE No more files, findtirst Finelude Hoelade nt main oid) c prioté (Directory Isting of #.*\x"); fone = finest (*8. 9" 4Efb1K, 017 white (done rinre(® telat, f@blk. EF panels Shoe = Hndnent E014) 7 1 retuen 0 Borland C++ Library Reference floodfill Function Syntox Remarks - Retumn value See ako Example findnext Program output Disectory Listing of *.* FIWDFaST.c PIQDFRST BE Flood-ills a bounded region. include void far floodfill(int x, int y, int border); flood fills an enclosed area on bitmap devices. (xy) is a “seed point” within the enclosed area to be filled. The area bounded by the color border is flooded with the current fll pattern and fil color. Ifthe seed point is. within an enclosed area, the inside will be filled. I the seed is outside the enclosed area, the exterior will be filled. Use fillpoly instead of floodfill whenever possible so that you can maintain code compatibility with future versions. {loodfill does not work with the IBM-8514 driver. Ifan error occurs while flooding a region, graphresult returns a value of 7. drawpoly,fillpoly, graphresult, setcolor, setillstyle Hinctode Hinelude include Hinelude St maingvoia) 1 le giriver = DETECT, gnode, exrorcde, int max, may * spitialize graphics and local variables #7 Lniegeaphisgdeiver, sgnose, ™): J vend result of Snitsalizetion * 1apter 2, The run-time library 178 ectorcode = grapbresult IE (ozeorcoda '= gx0k) ( _/* an error occurred */ print ("Graphice error: s\n", grapherromnsg(errorcode)) any Kay to balk) 1+ teminste with an ercor code */ page = getnan() any = getmaxy 2 (+ sect drawing color */ setcalor(getnaxcolor 1))2 J+ gelect $51 color */ setfillstyle (S0LI0 PILL, getnaxcelor )) [+ draw a border around the screen */ rectangle(®, 0, max, sanf); 1 dra oonm circles *) etna (3, maxy 12, $05 etnaax / 2, 20, 100): eran 20,"naxy-50, 75) circle 20, maxj-20, 25) P+ wait for 8 ey */ etch) /* F411 So bounded region */ focdfil1(2, 2, getmaxcolor 0) J+ clean wp */ floor, floor! Funelion Rounds dawn, Syntox include double floor(double 3); ong double floori(iong double x); tor ca We Borland C++ Ubrary Reference Remarks Retumn value See alo Example flushall Function Syntax. Remarks Return value See also Example floor, floort floor finds the largest integer not greater than x. {loot! is the long dovble version; it takes a long double argument and returns a long double result floor returns the integer found as a double, floor! returns the integer found as a long double. coil, fmod Hincluse include cet int nain void) i double ber 123.54, downy opi down = floor (number up = ceil (utber) printt(ortginal mutber 310.21F\n", mune: Print (*number rounied down 810.21E\ print (*nunber rounted up $10.21¢\ retuen 0 Frushes al streams. include int flushall(void); flushall clears all bu‘fers associated with open input streams, and writes all buffers associated with open output streams to their respective files. ‘Any read operation following flushall reads new data into the buffers from the input files. Streams stay open aiter thashall executes. flushall returns an integer, the number of open input and output streams. felose, fcloseal, lush Anelude nt sain veld) (Chapter 2, he run-time library 7 flushatt 2 file */ pen("O00E FI, 1+ ftaah att pen etseane 4/ printt("hd steeans were flashed. \o", lushal (1): clove the file */ felose teens feta 0; _imemecpy See memecpy. _fmemehr See memehr. _frnememp See mememp, _fmemepy See memepy. _fmemiomp : See memiemp. _imemset See memset, ve Borland C++ Library Reference tmod, fmodl ted, imeat | Function Calculates x modulo the remainder of x/y. Syntax include double fmod(double 1, double y); Jong double fmodl(loag double x, long double y); voc |estea |e [ao [ al toa c Remarks tmod calculates x modulo y (the remainder f, where x= ay + ffor some integer a and 0 <<. mod! isthe long double version; it takes long double arguments and returns a long double result. Retum value tmod and fmodl retum the remainder f, where x =ay + f (as described). Where y =0, fmod and fmodl return 0. See also ceil, floor, modt Example iaciude Haciode cnth.t> Sot wants) out f00d06,9)1 einté (the somindor of (ELE $16) is Ele, Ys Program output he conainder of 5.0 / 2.0 8 1. fnmerge Function Builds a path from component parts Syntax include Chapter 2, he run-time Koray 179 tnmerge Remarks Return value See also Example 180 void fmenge(char *path, const char “drive, const char *dir, const char *name, const char *ext); fnmerge makes a path name from its components. The new path name is SUBDIR AE. where drive dir ame = We et = aT ‘nmerge assumes there is enough space in path for the constructed path ‘name, The maximum constructed length is MAXPATH. MAXPATH is, defined in dirh. frmerge and tnsplit are invertible; if you split a given path with fnsplit, then merge the resultant components with fnmerge, you end up with path None. {nsplit include include Finelode nt main(vois) t har sINMEATE]; char aeive[saxon): kar aie(b@XOIR); char File(t@xeri3); har exe(om getevas AOXPATH 1% got current working divectory + (+ append a trailing \ character */ we,a0r,t34@)en8); /* SpLat the string to separate elens */ sta ed 134 1% marge everything into one string +7 pats(s); 7 display resulting stzing */ return Os Borland C++ Library Reference fnsplit Function ‘syntax Remarks {nspiit ee Splits a full path name into its components. include int fnsplit(const char ‘path, char “drive, char "dir, char *name, char *ext); i fnsplit takes a file’ fuil path name (path) as a string in the form X:\DIR\SUBDIR\NAME.EXT and splits path into its four components. It then stores those components, in the strings pointed to by drive, dr, name, and ext. (All five components ‘must be passed, but any of them can be a null, which means the corre- sponding component will be parsed but not stored.) ‘The maximum sizes for these strings are given by the constants MAXDRIVE, MAXDIR, MAXPATH, MAXFILE, and MAXEXT (defined in diz), and each size includes space for the null-terminator. Chapter 2, The run-time ltsrary Constant ‘String MAXPATH path MAXDRIVE, ©), Ham intudes colon MAXDIR lis includes leading and tailing backslashes (\) Maxmt ® name MAXEXt 6% ‘xt includes leading dot () ‘neplit assumes that there is enough space to store each non-null component. When fnspllt splits put, it treats the punctuation as follows: drive includes the colon (C:, As, and so on). sdir inckudes the leading and trailing hackslashes (\BC\include\, \source\, and s0 on), ‘= name includes the file name. ‘next includes the dot preceding the extension (.C, EXE, and so on). fnmerge and tnsplit ere invertible; if you split a given path with fnsplit, then merge the resultant components with frmerge, you end up with path. 181 ‘nspiit Retum value fopen See also Example Function syntax. {nsplit returns an integer (composed of five flags, defined in dir.h) indicating which of the full path name components were present in path; these flags and the components they represent are EXTENSION Anextension FILENAME filename DIRECTORY A directory (and possibly subdirectories) DRIVE A drive specification (see dirk) WILDCARDS — Wildcards (or?) fnmerge include cots. include include nt main(void) har 4s char drive MaDeIVE) char dir MMO) ‘har fileieTIE; char ot [MREBET Sint flags; 1* got conspoc environment. paraneter #/ sy (POSPECT| naplit(sy drive, dir, Eeleyent) print ("Command processor infoc\n"): (Plage « ontve} printf("\edrives te\n" drivel Le (flage 6 OTRBCTORY} eaiectory iftriags « erezavE) printt{Meflle: te\nt, file ifttlags « exrBNsToN print ("\ertension: 48\0",ext) Ae" Opensa stream. include FILE *fopen(const char “filename, const char *mode); Borland C++ Library Reference Remarks fopen fopen opens the file named by filename and associates a stream with it fopen returns a pointer o be used to identify the stream in subsequent operations. ‘The mode string used in calls to fopen is one of the following values: ‘Mode Description 7 Open for readingonly. w Create for writing. a file by that name already exists it will be loversrritten 4 Append; open for writing at end of ile, or create for writing ifthe file ‘does not exist. + Open an existing file for update (reading and writing). w+ Create a new file‘or update (reading and writing). Ifa file by that name already exists, it wll be overwritten. ‘a+ Open for append: open for update at the end ofthe file, or create ifthe file does nat exist To specify that a given file is being opened or created in text mode, append a t to the mode siting (ri, w+, and so on). Similarly, to specify binary mode, append a 9 to the mode string (wb, a+b, and so on). fopen also allows the tor b to be inserted between the letter and the + character in the mode string; for example, r+ is equivalent to rt. Ifa orb isnot given in the mode string, the mode is governed by the global variable fade. IF_fmode is set to O_ BINARY, files are opened in binary mode. If_fmode is set to TEXT, they are opened in text mode. ‘These O..... constants are defined in fent.h, When a file is opened for update, both input and output can be done on the resulting stream. However, output cannot be followed directly by input without an intervening fseek or rewind, and input cannot be directly followed by output without an intervening fSeek, rewind, or an Input that encounters erd-of-fle. (On successful completion, fopen returns a pointer tothe newly opened stream. Inthe event of error, it returns mull. ‘creat, dup, folose, fdopen ferror, mode (global variable), fread, freopen, seek, write, open, rewind, setbut, setmode 1 progean to create backup of the AUTORXEC.BaP file */ fer 2, The runtime lirary 183 fopen Hnclude nt main(vota FLUE #in, *osts Af {in * fopea (*\\anToRMEE.aKt™, x") fpeintt stderr, "Cannot cpen input file.\s 1 4€ (lout = fopan|"\\AUTOEKBC. BAK", fein stderr, "Cannot open output file. \a"): 1 ville (Hfeoftin)) Apatc(tgete lin, cuth feos felese(out) return 0; FP_OFF, FP_SEG Function Syntax. Remarks Return value Seals Example Gets a far address offset or segment. findude unsigned FP_OFF(void far *p); unsigned FP_SEG(void far *p); The FP_OFF macro can be used to get or set the offset ofthe far pointer “p. FP_SEG isa macro that gets or sets the segment value of the far pointer ". FP_OFF returns an unsigned integer value representing an offset value. FP_SEG returns an unsigned integer representing a segment value. MK_FP, movedata, segread include os. Hinelude include ye FEOrP ¥/ (oid Borland C++ Ubrary Reference 2 e char Aste = "Spot. ct print ("The offset cf this fe nane in meaocy\ er Meplnt, FP_OFF(ste}: return 0: pe, 6 #7 seg{voia) har #68 print ("the segnent of this file in meaney\ fist Mepin", FP_sOc(Filenane)): sstumn(0); fe mg 7 Se maingvote) setoctaraph ad, 60 1f (od = HERO) seteen = (onsigned Set *} 9 FP(Ox@000, 0} lse soreen = (unsigned int *] ML FP(OxBUO0, 0} for (indy 1267 is seraen(i] = Ox0TK0 + (fa! #3), sotaen 0 fpreset Function Reinitializes floating-point math package. Syntax include void _fpreset(void); (Chapter 2, The run-time itbrary FP_OFF, FP_SEG preset Remarks _fpreset reinitializes the floating-point math package. This function is, ‘Usually used in conjunction with system or the exec... or spawn.. functions. float one 0 = 0.0 Me /* Install signal hindler for floating loot trap); printf {Generating 2 math printt (press 8 key'a'); getend: BE (set op (room one fo t90 prince *Retorned fron signel trap\o"); retucn 0: ‘ep Under DOS, ifan 80x87 coprocessor is used ina program, a child process (executed by system or by an exec... or Spawn... function) might ater the parent process’ floating-point state. If you use an 80x87, take the following precautions: ‘=Do not call system or an exec... or spawn... function while floating- point expression is being evaluated. Hl ‘=Call_fpreset to reset the floating, point state after using system, exec. | or spawn... if there is any chance that the child process performed a \ floating-point operation with the 80x87. Retunvelie None fprintt Function Writes formatted ouput toa stream. Syntax include int fprintf(FILE *streem, const char "formal, azgument, ..D; ‘Seealso _clear87,_control67, exec..., spawn...,_status87, system Example fincioce Haclose include process. Remarks sprintf accepts a series of arguments, applies to each a format specifier contained in the format string pointed to by format, and outputs the S09 print for detols formatted data to a stream. There must be the same number of format entomarspection. specifiers as arguments Return value fprintf returns the number of bytes output. In the event of error, it returns EOF. See also eprint, tscanf, print, pute, sprint Example —finciode _eplusplus wold (2fpery (it); typedee void ¢ senaif pt) 1 detine a handler for tespping floating point errors */ vod lost trapCint sis) int main(vois) ‘ "rapping floating point error," tignal 1s 82\a",346)2 press a Jey to continue\n"); bpetehil 7 Reset the 6087 chip oF enu preset; ny exteaneous garbage. */ ‘Fercetuen to the problen spot */ strean = fopen(*DIWT.FTU", "wi"; + open a file for update */ cag mp(reenter, 1)? print (atrean, "id Se SE", 4, cy £7 /* write some data to the file */ ! felose{strean); /* close tho file */ return 0; 186 Borland C++ Library Reference Chapter 2, The run-time itbrary 187 fpute fputchar fputc sa mina fpute Function Puts a character ona stream. oh sl = ts a easy Syntox include int fpute(intc, FILE *stream); vie (negli) spotehac ing)? xn 0; Remarks fputc outputs character cto the named stream. = fputs Return value On success, fpute returns the character c. On error, it returns EOF. i See ako tgete, pute Function Outputs a string on astream. Syntax. #include int fputs(const char *s, FILE *stream); Example se cot. nt maintvoie) tl char nag) = "dello worla"s ine t= 0 et fe vile tnog(tl | ele Remorks fputs copies the nullterminated string sto the given output stream; it i does not append a newline character, and the terminating mull characteris return 0; not copied. Retum value On successful completion, fputs returns a non-negative value. Otherwise, itreturns a value of EOF. fputchar Seeako fgets, gets, puts Example —fnclude Function Outputs a character on stdout. Syntax. #include int sputcharCint int main(voia) 1 176 write a string to standard ontpot */ ‘putet "Helo vorlé\e", stdout): return + THK | Windows | MSTC | Co only Remarks fputchar outputs character cto stdout. fputchar() is the same as fputetc, sidout), Return value On success, fputchar returns the character c. On error, it returns EOF, fread Function Reads data from a stream. Syntax. #include size_t fread( void *pty, size_t size, size_t n, FILE *stream); See also fgetchar, putchar Example finciode i Borland C++ Library Reference 1apter 2, The runtime library i
  • Das könnte Ihnen auch gefallen