Professional Documents
Culture Documents
All rights reserved. No part of the contents of this book may be reproduced or trans
mitted in any form or by any means without the written permission of the publisher.
Includes index.
1. C (Computer program language) 2. Microsoft C
(Computer program) 3. Macro instructions (Electronic
computers) I. Microsoft.
QA76.73.Cl5M52 1990 005.13'3 89-12240
ISBN 1-55615-225-6
2 3 4 5 6 7 8 9 HCHC 3 2 I 0
Distributed to the book trade outside the United States and Canada by Penguin
Books Ltd.
Microsoft, the Microsoft logo, MS-DOS, QuickC, and XENIX are registered trademarks
and Windows is a trademark of Microsoft Corporation.
AT&T and UNIX are registered trademarks of American Telephone and Telegraph
Company.
Hercules is a regi�tered trademark of Hercules Computer Technology.
IBM is a registered trademark of International Business Machines Corporation.
Olivetti is a registered trademark of Ing. C. Olivetti.
Contents
Introduction . . . v
About the C Run-Time Library • v
About This Book . . . vii
Other Books of Interest vii
Document Conventions ,ix
Special Offer . . . . . xi
Iii
Iv Microsoft C Run-Time Library Reference
Alp habeticFunctionReference . . . . . . . . . • • • . 76
Index . . . . . . . . . . . . . . . . . . . . . . . • • • 829
Introduction
The Microsoft® C Run-Time Library is a set of over 500 ready-to-use functions
and macros designed for use in C programs. The run-time library makes program
ming easier by providing
The C run-time library is important because it provides basic functions not pro
vided by the C language itself. These functions include input and output, memory
allocation, process control, graphics, and many others.
This book describes the Microsoft C run-time library routines included with the
Microsoft Professional Development System version 6.0. These comprise all of
the routines included with earlier versions of Microsoft C, as well as many new
routines.
NOTE Microsoft documentation uses the term "OS/2" to refer to the OS/2 systems
Microsoft Operating System/2 (MS® 0512) and IBM@ OS/2. Similarly, the term "DOS" refers
to both the MS-DOS® and IBM Personal Computer DOS operating systems. The name of a
specific operating system is used when It is necessary to note features that are unique to
that system.
v
vi Microsoft C Run-Time Library Reference
ANSI C Compatibility
The C run-time library routines are designed for compatibility with the ANSI C
standard, which Microsoft C compilers support. The major innovation of ANSI C
is to permit argument-type lists in function prototypes (declarations). Given the
information in the function prototype, the compiler can check later references to
the function to make sure that the references use the correct number and type of
arguments and the correct return value.
To take advantage ofthe compiler's type-checking ability, the include files that
accompany the C run-time library have been expanded. In addition to the defini
tions and declarations required by library routines, the include files now contain
function declarations with argument-type lists. Several new include files have
also been added. The names of these files are chosen to maximize compatibility
with the ANSI C standard and with XENIX and UNIX names.
The fonts library allows your programs to display various styles and sizes of text
in graphics images or charts. You can use font-manipulation routines with any
graphics routines that display text, including presentation graphics.
This book has two parts. Part I, "Overview," introduces the Microsoft C library.
It describes general rules for using the library and summarizes the main catego
ries of library routines. Part I contains the following chapters:
The following books cover a variety of topics that you may find useful. They are
listed only for your convenience. With the exception of its own RUblications,
Microsoft does not endorse these books or recommend them over others on the
same subject.
I
• Harbison, Samuel P., and Guy L. Steele, Jr. C: A Reference Manual, 2d ed.
Englewood Cliffs, NJ: Prentice Hall, 1987.
A comprehensive guide to the C language and the standard library.
• Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language,
2d ed. Englewood Cliffs, NJ: Prentice Hall, 1988.
The first edition of this book is the classic definition of the C language. The
second edition includes new information on the proposed ANSI C standard.
• Lafore, Robert. Microsoft C Programmingfor the IBM. Indianapolis, IN:
Howard W. Sams & Company, 1987.
The first half of this book teaches C. The second half concentrates on specif
ics of the PC environment, such as BIOS calls, memory, and video displays.
• Mark Williams Company. ANSI C: A Lexical Guide. Englewood Cliffs, NJ:
Prentice Hall, 1988.
A dictionary-style guide to the ANSI C standard.
• Plauger, P. J., and Jim Brodie. Standard C. Redmond, WA: Microsoft Press,
1989.
A quick reference guide to the ANSI C implementation by the secretary and
chairman of the ANSI-authorized C Programming Language Standards
Committee.
Introduction ix
• Plum, Thomas. Reliable Data Structures in C. Cardiff, NJ: Plum Hall, 1985 .
•
Docu111ent Convenllons
This book uses the following document conventions :
Example Description
STDIO.H Uppercase letters indicate file names, segment
names, registers, and tenns used at the
operating-system command level.
far Boldface letters indicate C keywords, operators,
language-specific characters, and library routines.
Within discussions of syntax, bold type indicates
that the text must be entered exactly as shown.
8
expression Words in italics indicate placeholders for infonna-
tion you must supply, such as a file name. Italics are
also occasionally used for emphasis in the text.
[option]) Items inside double square brackets are optional.
x Microsoft C Run-Time Library Reference
#pragma pack { 112} Braces and a vertical bar indicate a choice among
two or more items. You must choose one of these
items unless double square brackets surround the
braces.
//:include <io. h > This font is used for examples, user input, program
output, and error messages in text.
C L options' [files ...]J Three dots following an item indicate that more
items having the same form may appear.
w h i l e() A column of three dots tells you that part of the ex
{ ample program has been intentionally omitted.
CTRL+ENTER Small capital letters are used for the names of keys
on the keyboard. When you see a plus sign (+) be
tween two key names, you should hold down the
first key while pressing the second.
The carriage-return key, sometimes marked as a
bent arrow on the keyboard, is called ENTER.
"argument" Quotation marks enclose a new term the first time it
is defined in text.
"C string" Some C constructs, such as strings, require quotation
marks. Quotation marks required by the language
n II I I t t•
have the form and rather than " " and
Color Graphics The first time an acronym is used, it is often
Adapter (CGA) spelled out.
Introduction xi
If you have questions or comments about the files on the disk, send them to:
Languages User Education, Microsoft Corporation, One Microsoft Way,
Redmond, WA 98052-6399.
Overview
Overview
The first part of this book provides an overview of the run-time
library provided with the Microsoft C Professional Development
System.
This chapter provides basic information about how to use Microsoft C library
routines. It also describes some special rules, such as file- and path-name conven
tions, that apply to particular routines. You should read this chapter before you
begin to use C library routines, and you may also want to refer back to it if you
have questions about library procedures.
#include <stdio.h>
main( l
(
printf( "Microsoft C" );
The program prints Mi c r o soft C by calling the printf routine, which is part
of the standard C library. Calling a library routine normally involves two groups
of files:
Header files and library files are both included with Microsoft C. Header files are
used when compiling, and library files are used when linking.
5
6 Microsoft C Run· Time Library Reference
You include the necessary header files in your program source code with
#include directives. The description of each library routine in Part 2, "Refer
ence," tells you what header file the routine requires. Since printf requires the
STDIO.H header file, the SAMPLE.C program contains the following line:
#i n c l u d e < s t d i o . h >
This line causes the compiler to insert the contents of STDIO.H into the source
file SAMPLE.C.
After you compile the source file, you link the resulting object (.OBJ) file with
the appropriate library (.LIB) file to create an executable (.EXE) file. Your object
file contains the name of every routine that your program calls, including library
routines. If a routine is not defined in your program, the linker searches for its
code in a library file and includes that code in the �xecutable file.
Normally, the code for standard library routines is contained in the "default li
brary" that you create when installing Microsoft C. Since the linker automat
ically searches the default library, you do not need to specify that library's name
when linking your program. The following command links the example program
with the default library:
l i n k s a mpl e , , , ;
If you call a library routine that is not contained in the default library, you must
give the linker the name of the library file that contains the routine. For instance,
suppose your program uses a Microsoft C graphics routine and you did not make
GRAPHICS.LIB part of your default library when installing Microsoft C. You
would then link the program using a line like the following:
l i n k s a m p l e , , , g r a p hic s . l i b ;
For more information about libraries and linking, consult the installation docu
mentation for your compiler.
Definition Example
Macro If a library routine is implemented as a macro, the
macro definition appears in a header file. For in
stance, the toupper macro is defined in the header
file CTYPE.H.
Manifest constant Many library routines refer to constants that are de
fined in header files. For instance, the open routine
A function declaration lists the name of the function, its return type, and the num
ber and type of its arguments. For instance, below is the declaration of the pow
library function from the header file MATH.H:
double pow( double x , double y );
The example declares that pow returns a value of type double and takes two ar
guments of type double. Given this declaration, the compiler can check every ref
erence to pow in your program to ensure that the reference passes two double
arguments to pow and takes a return value of type double.
The compiler can perform type checking only for function references that appear
after the function declaration. Because of this, function declarations normally ap
pear near the beginning of the source file, prior to any use of the functions they
declare.
8 Microsoft C Run·Time Library Reference
Function declarations are especially important for functions that return a value of
some type other than int, which is the default. For example, the pow function re
turns a double value. If you do not declare such a function, the compiler treats its
return value as int, which can cause unexpected results.
It is also a good practice to provide declarations for functions that you write. If
you do not want to type the declarations by hand, you can generate them automat
ically by using the /Zg compiler option. This option causes the compiler to
generate ANSI-standard function declarations for every function defined in the
current source file. Redirect this output to a file, then insert the file near the
beginning of your source file.
Your program can contain more than one declaration of the same function, as
long as the declarations do not conflict. This is important if you have old pro
grams whose function declarations do not contain argument-type lists. For in
stance, if your program contains the declaration
c h a r *c a l l o c C >:
c h a r *c a l l o c C u n s i gn e d , u n s i gn e d ) ;
Because the two declarations are compatible, even though they are not identical,
no conflict occurs. The second declaration simply gives more information about
function arguments than the second. A conflict would arise, however, if the decla
rations gave a different number of arguments or gave arguments of different
types.
Some library functions can take a variable number of arguments. For instance,
the printf function can take one argument or several. The compiler can perform
only limited type checking on such functions, a factor that affects the following
library functions:
• In calls to cprintf, cscanf, printf, and scanf, only the first argument (the for
mat string) is type checked.
• In calls to fprintf, fscanf, sprintf, and sscanf, only the first two arguments
(the file or buffer and the format string) are type checked.
• In calls to open, only the first two arguments (the path name and the open
flag) are type checked.
• In calls to sopen, only the first three arguments (the path name, the open flag,
and the sharing mode) are type checked.
Using C Library Routines 9
• In calls to execl, execle, execlp, and execlpe, only the first two arguments
(the path name and the first argument pointer) are type checked.
• In calls to spawnl, spawnle, spawnlp, and spawnlpe, only the first three ar
guments (the mode flag, the path name, and the first argument pointer) are
type checked.
Case Sensitivity
The DOS and OS/2 operating systems are not case sensitive (they do not dis
tinguish between uppercase and lowercase letters). Thus, SAMPLE.C and
Sample.C refer to the same file in DOS and OS/2. However, the XENIX operat
ing system is case sensitive. In XENIX, SAMPLE.C and Sample.C refer to differ
ent files. To transport programs to XENIX, choose file and path names that work
correctly in XENIX, since either case works in DOS and OS/2. For instance, the
following directives are identical in DOS and OS/2, but only the second works in
XENIX:
# i n c l u d e < ST D I O . H >
#i ncl ude < s t d i o . h>
Subdirectory Conventions
Under XENIX, certain header files are normally placed in a subdirectory named
SYS. Microsoft C follows this convention to ease the process of transporting pro
grams to XENIX. If you do not plan to transport your programs, you can place
the SYS header files elsewhere.
Path-Name Delimiters
XENIX uses the slash (/) in path names, while DOS and OS/2 use the backslash
(\). To transport programs to XENIX, it is advantageous to use path-name
delimiters that are compatible with XENIX whenever possible.
·
10 Microsoft C Run-Time Library Reference
• Some macros treat arguments with side effects incorrectly when the macro
evaluates its arguments more than once (see the example that follows this
list). Not every macro has this effect. To determine if a macro handles side ef
fects as desired, examine its definition in the appropriate header file.
• A function name evaluates to an address, but a macro name does not. Thus,
you cannot use a macro name in contexts requiring a function pointer. For in
stance, you can declare a pointer to a function, but you cannot declare a
pointer to a macro.
• You can declare functions, but you cannot declare macros. Thus, the compiler
cannot perform type checking of macro arguments as it does of function argu
ments. However, the compiler can detect when you pass the wrong number of
arguments to a macro.
• You must always include the appropriate header file when using a library
macro. Every library macro is defined with a #define directive in a header
file. If you do not include the header file, the macro is undefined.
Using C Library Routines 1 1
The following example demonstrates how some macros can produce unwanted
side effects. It uses the toupper routine from the standard C library.
#i n c l u d e < c t y p e . h>
i n t a = 'm' ;
a = t o u p p e r ( a ++ ) ;
The definition uses the conditional operator (? :). The conditional expression
evaluates the argument c twice: once to check if it is lowercase and again to cre
ate the result. This macro evaluates the argument a++ twice, increasing a by 2
instead of 1. As a result, the value operated on by islower differs from the value
operated on by _toupper.
Like some other library routines, toupper is provided in both macro and function
versions. The header file CTYPE.H not only declares the toupper function but
also defines the toupper macro.
Choosing between the macro version and function version of such routines is
easy. If you wish to use the macro version, you can simply include the header file
that contains the macro definition. Because the macro definition of the routine al
ways appears after the function declaration, the macro definition normally takes
precedence. Thus, if your program includes CTYPE.H and then calls toupper,
the compiler uses the toupper macro:
i n t a = 'm' ;
a = touppe r ( a ) ;
You can force the compiler to use the function version of a routine by enclosing
the routine's name in parentheses:
# i n c l u d e < c t y p e . h>
i n t a = 'm' ;
a = ( touppe r ) ( a ) ;
Because the name toupper is not immediately followed by a left parenthesis, the
compiler cannot interpret it as a macro name. It must use the toupper function.
12 Microsoft C Run-Time Library Reference
A second way to do this is to "undefine" the macro definition with the #undef
directive:
#i n c l u d e < c t y p e . h>
#undef toupper
# i n c l u d e < c ty p e .h>
i n t t o u p p e r ( i n t _c l ;
Since this function declaration appears after the macro definition in CTYPE.H, it
causes the compiler to use the toupper function.
When you use errno, perror, and strerror, remember that the value of errno re
flects the error value for the last call that set errno. To avoid confusion, you
should always test the return value to verify that an error actually occurred. Once
you detennine that an error has occurred, use errno or perror immediately.
Otherwise, the value of errno may be changed by intervening calls.
Library math routines set errno by calling the matherr or _matherrl library
routines, which are described in the reference section. If you wish to handle math
errors differently from these routines, you can write your own routine and name
The ferror library routine allows you to check for errors in stream input/output
operations. This routine checks if an error indicator has been set for a given
stream. Closing or rewinding the stream automatically clears the error indicator.
You can also reset the error indicator by calling the clearerr library routine.
The feof library routine tests for end-of-file on a given stream. An end-of-file
condition in low-level input and output can be detected with the eof routine or
when a read operation returns 0 as the number of bytes read.
The _grstatus library routine allows you to check for errors after calling certain
graphics library operations. See the reference page on the _grstatus function for
details.
14 Microsoft C Run-Time Library Reference
1. 7 Operating-System Considerations
The library routines listed in this section behave differently under different oper
ating system versions. For more information on an individual routine, see the de
scription of that routine in the reference section.
Routine Restrictions
locking These routines are effective only in OS/2 and in
sopen DOS versions 3.0 and later.
_fsopen
dosexterr The dosexterr routine provides error handling for
system call Ox59 (get extended error) in DOS ver
sions 3.0 and later.
dup The dup and dup2 routines can cause unexpected re
dup2 sults in DOS versions earlier than 3.0. If you use
dup or dup2 to create a duplicate file handle for
stdio, stdout, stderr, stdaux, or stdprn, calling the
close function with one handle causes errors in later
1/0 operations that use the other handle. This
anomaly does not occur in OS/2 or in DOS versions
3.0 and later.
exec . When using the exec and spawn families of func
spawn tions under DOS versions earlier than 3.0, the value
of the argO argument (or argv[O] to the child
process) is not available to the user; a null string
("") is stored in that position instead. In OS/2, the
argO argument contains the command name; in DOS
versions 3.0 and later, it contains the complete com
mand path.
Microsoft C defines global variables that indicate the version of the current oper
ating system. You can use these to determine the operating-system version in
which a program is executing. See Chapter 3, "Global Variables and Standard
Types," for more information.
Using C Library Routines 15
1. 8 Floating-Point Support
Microsoft math library routines require floating-point support to perfonn calcula
tions with real numbers (numbers that can contain fractions). This support can be
provided by the floating-point libraries that accompany your compiler software
or by an 8087, 80287, or 80387 coprocessor. The names of the functions that re
quire floating-point support are listed below:
acos · cos fmodl powI
acosl cosl fmsbintoieee sin
asin cosh _fpteset sinl
asinl coshi frexp sinh
atan dieeetomsbin frexpl sinhl
atanl diffiime gcvt sqrt
atan2 dmsbintoieee hypot sqrtl
atan21 ecvt hypotl status87
atof exp Idexp strtod
atold expI ldexpl _strtold
bessel fabs log tan
cabs fabsl logl tanl
cabsl fcvt loglO tanh
ceil fieeetomsbin loglOI tanhl
ceill floor modf
clear87 tloorl modtl
=control87 fmod pow
Note that the bessel routine does not correspond to a single function, but to
twelve functions namedjO, jl, jn, yO, yl, yn, JOI, JU, Jnl, JOI, Jll, and
JDI. Also note that the _clear87 and _control87 functions are not available with
the /FPa compiler option.
Also requiring floating-point support is the printf family of functions (cprintf,
fprintf, printf, sprintf, vfprintf, vprintf, and vsprintf). These functions require
support for floating-point input and output if used to print floating-point values.
The C compiler tries to detect whether floating-point v alues are used in a pro
gram so that supporting functions are loaded only if required. This behavior
saves a considerable amount of space for programs that do not require floating
point support.
When you use a floating-point type specifier in the fonnat string for a printf or
scanf call, make sure you specify floating-point values or pointers to floating
point values in the argument list. These must correspond to any floating-point
16 Microson C Run-Time Library Reference
type specifiers in the format string. The presence of floating-point arguments al
lows the compiler to detect that floating-point support code is required. If a
floating-point type specifier is used to print an integer argument, for example,
floating-point values will not be detected because the compiler does not actually
read the format string used in the printf and scanf functions. For instance, the fol
lowing program produces an error at run time:
ma i n ( ) / * T hi s e x a mp l e c a u s e s a n e r r o r * /
{
l on g f = 10L ;
p r i nt f(" %f " , f ) ;
}
In the preceding example, the functions for floating-point support are not loaded
·
because
Fl oa t i n g p o i n t not l oa ded
Here is a corrected version of the above call to printf in which the long integer
value is cast to double:
ma i n( ) / * T h i s e x a mp l e w o r ks c o r r e c t l y * /
{
l ong f = 10L ;
p r i n t f (" % f " , (d o u b l e ) f } ;
}
With this set of functions, you can read from, write to, search, sort, copy, initial
ize, compare, or dynamically allocate and free _huge arrays; the _huge array can
be passed without difficulty to any of these functions in a compact-, large-, or
huge-model program. The model-independent routines in the above list (those
beginning with _f) are available in all memory models.
The memset, memcpy, and memcmp library routines are available in two ver
sions: as C functions and as intrinsic (in-line) code. The function versions of
these routines support huge pointers in compact and large memory models, but
the intrinsic versions do not support huge pointers. (The function version of such
routines generates a call to a library function, whereas the intrinsic version in
serts in-line code into your program. Your compiler documentation explains how
to select the intrinsic versions of library routines.)
CHAPTER
Run-Time Routines
by Category
Microsoft C library routines handle various kinds of tasks. If you know the type
of task you need done, but don't know exactly which routine to use, the catego
rized lists of routines in this chapter can help.
The descriptions here are intended only to give you a brief overview of the capa
bilities of the run-time library. For a complete description of the behavior, syn
tax, and use of each routine, see Part 2, "Run-Time Functions."
The main categories of library routines are
• Buffer manipulation
• Character classification and conversion
• Data conversion
• Directory control
• File handling
• Graphics
• Input and output
• Internationalization
• Math
• Memory allocation
• Process and environment control
• Searching and sorting
• String manipulation
• System calls
• Time
• Variable-length argument lists
19
20 Microsoft C Run-Time Library Reference
2. 1 Buffer Manipulation
The buffer-manipulation routines are useful for working with areas of memory
on a character-by-character basis. A "buffer" is an array of characters, similar
to a character string. However, unlike strings, buffers are not usually termi
nated with a null character ( '\0 ' ) . Therefore, the buffer-manipulation routines
always take a length or count argument. Function declarations for the buffer
manipulation routines are given in the include files MEMORY.H and
STRING.H, with an exception being the swab function, which appears in
STDLIB.H.
Routines beginning with _f are model independent; the _f stands for far. These
routines are useful in writing mixed-model programs because they can be called
from any program, regardless of the memory model being used.
Routine Use
memccpy, Copy characters from one buffer to another until a
_fmemccpy given character or a given number of characters has
been copied
memchr, _fmemchr Return a pointer to the first occurrence, within a
specified number of characters, of a given character
in the buffer
memcmp, _fmemcmp Compare a specified number of characters from two
buffers
memcpy, _fmemcpy Copy a specified number of characters from one
buffer to another
memicmp, Compare a specified number of characters from two
_fmemicmp buffers without regard to the case of the letters (up
percase and lowercase treated as equivalent)
memmove, Copy a specified number of characters from one
fmemmove buffer to another
rnemset, frnemset Use a given character to initialize a specified num
ber of bytes in the buffer
swab Swaps bytes of data and stores them at the specified
location
Run-Time Routines by Category 21
When the source and target areas overlap, only the memmove and _fmemmove
. functions are guaranteed to copy the full source properly. (The memcpy and
_fmemcpy routines do not always copy the full source in such cases.)
Routine Use
isalnum Tests for alphanumeric character
isalpha Tests for alphabetic character
isascii Tests for ASCII character
iscntrl Tests for control character
isdigit Tests for decimal digit
isgraph Tests for printable character except space
islower Tests for lowercase character
isprint Tests for printable character
ispunct Tests for punctuation character
isspace Tests for white-space character
isupper Tests for uppercase character
isxdigit Tests for hexadecimal digit
toascii Converts character to ASCII code
tolower Tests character and converts to lowercase if
uppercase
_tolower Converts character to lowercase (unconditional)
toupper Tests character and converts to uppercase if
lowercase
_toupper Converts character to uppercase (unconditional)
22 Microsoft C Run- Time Library Reference
All of these routines are implemented in two versions: as functions and as mac
ros. The function prototypes and macro definitions appear in CTYPE.H. Section
1 .4, "Choosing Between Functions and Macros," explains how to choose the
appropriate version. The toupper and tolower functions are also declared in the
STDLIB.H header file.
Routine Use
abs Finds absolute value of integer
atof Converts string to float
atoi Converts string to int
atol Converts string to long
atold Converts string to long double
ecvt Converts double to string
fcvt Converts double to string
gcvt Converts double to string
itoa Converts int to string
labs Finds absolute value of long integer
ltoa Converts long to string
strtod Converts string to double
Run-Time Routines by Category 23
2. 4 Directory Control
The directory-control routines let a program access, modify, and obtain informa
tion about the directory structure. These routines are functions and are declared
in DIRECT.H.
Routine Use
chdir Changes current working directory
_chdrive Changes current drive
getcwd Gets current working directory
__getdcwd Gets current working directory for the specified drive
__getdrive Gets the current disk drive
mkdir Makes a new directory
rmdir Removes a directory
_searchenv Searches for a given file on specified paths
2. 5 File Handling
The file-handling routines let you create, manipulate, and delete files. They also
set and check file-access permissions.
File-handling routines work on a file designated by a path name or by a "file
handle," an integer assigned by the operating system that identifies an open file.
These routines modify or give information about the designated file. Most of
them are declared in the include file 10.H, with the exceptions being the fstat
and stat functions (declared in SYS\STAT.H), the _fullpath routine (declared in
DIRECT.H), and the remove and rename functions (also declared in STDIO.H).
24 Microsoft C Run-Time Library Reference
Routine Use
access Checks file-permission setting
chmod Changes file-permission setting
chsize Changes file size
filelength Gets file length
fstat Gets file-status information on handle
_fullpath Makes an absolute path name from a relative
path name
isatty Checks for character device
locking Locks areas of file (available with OS/2 and
DOS versions 3.0 and later)
_makepath Merges path-name components into a single, full
path name
mktemp Creates unique file name
remove Deletes file
rename Renames file
setmode Sets file-translation mode
_splitpath Splits a path name into component pieces
stat Gets file-status information on named file
umask Sets default-permission mask
unlink Deletes file
2. 6 Graphics
Microsoft C graphics routines offer a wide variety of graphics functions, low
level graphics primitives, font functions, and presentation graphics (displays such
as graphs and pie charts).
Graphics functions are supplied in two libraries that must be explicitly linked
with your program. The GRAPIIlCS.LIB library provides support for low-level
graphics and character-font routines. The library PGCHART.LIB supports
presentation-graphics routines.
Category Task
Configuring mode and Select the proper display mode for the hardware and
environment (OS/2 establish memory areas for writing and displaying of
.
and DOS) images
Setting coordinates Specify the logical origin and the active display area
within the screen
Setting low-level Specify a palette mapping for low-level graphics
graphics palettes routines
Setting attributes Specify background and foreground colors, fill
masks, and line styles for low-level graphics routines
Creating graphics Draw and fill figures
output
Creating text output Write text on the screen
(OS/2 and DOS)
Transferring images Store images in memory and retrieve them
Displaying fonts Display text in character fonts compatible with
Microsoft Windows™
Routine Use
clearscreen Erases the screen and fills it with the current back
ground color
_getactivepage Gets the current active page number
_getbkcolor Returns the current background color
_getvideoconfig Obtains status of current graphics environment
_getvisualpage Gets the current visual page number
_grstatus Returns the status of the most recent graphics func
tion call
_setactivepage Sets memory area for the active page for writing
images
_setbkcolor Sets the current background color
settextrows Sets the number of text rows
_setvideomode Selects an operating mode for the display screen
setvideomoderows Sets the video mode and the number of rows for text
operations
_setvisualpage Sets memory area for the current visual page
The functions in this category establish window and view coordinate systems and
translate between physical, view, and window coordinate systems.
Routine Use
_getcurrentposition Determines current position in view coordinates
The default view coordinate system is identical to the physical screen coordinate
system. The physical origin (0, 0) is always in the upper-left corner of the dis
play. The x axis extends in the positive direction left to right, while the y axis ex
tends in the positive direction top to bottom.
The physical horizontal and vertical dimensions depend on the hardware display
configuration and the selected mode. These values are accessible at run time by
examining the numxpixels and numypixels fields of the videoconfig structure
returned by _getvideoconfig. (The _getvideoconfig routine is listed in the pre
vious section.)
The _setvieworg function allows you to move the viewport origin to a new posi
tion relative to the physical screen.
Routines that refer to coordinates on the physical screen or viewport require in
teger values. However, in real-world graphing applications, you might wish to
use floating-point values, such as stock prices or average rainfall. The window
coordinate system allows you to display graphics using floating-point values in
stead of integers.
The _setcliprgn function defines a restricted active display area on the screen.
The _setviewport function does the same thing and also resets the viewport
origin to the upper-left corner of the restricted active display area.
The view coordinates of any window coordinate can be determined with the
_getviewcoord_w and _getviewcoord_wxy functions. The window coordinates
of any view coordinate can be determined with the _getwindowcoord function.
Routine Use
_remapallpalette Changes all color indexes in the current palette
Some video modes support a "color palette," which is a table of the color values
that can be displayed together on the screen at any given time. A "color value" is
a long integer representing a color that can be displayed on your system.
In CGA color graphics modes, you can use the _selectpalette routine to choose
one of several predefined palettes.
On EGA and VGA video systems, you can "remap" (change) the palette using
the _remappalette or _remapallpalette routines. For instance, the EGA
ERESCOLOR mode offers a total of 64 color values, of which 1 6 can be dis
played at a time. In this mode, the palette contains 16 "color indices," or slots to
which you can assign color values.
graphics functions rely on a set of attributes that are set independently by the fol
lowing functions:
Routine Use
The _getcolor and _setcolor functions get or set the current color index for
graphics and font output. The _getbkcolor and _setbkcolor functions get or set
the current background color.
The _getfillmask and _setfillmask functions get or set the current fill mask. The
mask is an 8-by-8-bit template array, with each bit representing a pixel. If a bit is
0, the pixel in memory is left untouched, as the mask is transparent to that pixel.
If a bit is I , the pixel is assigned the current color value. The template is repeated
as necessary over the entire fill area.
The _getlinestyle and _setlinestyle functions get or set the current line style. The
line style is determined by a 1 6-bit template buffer with each bit corresponding
to a pixel. If a bit is 1 , the pixel is set to the current color. If a bit is 0, the pixel is
not changed. The template is repeated for the length of the line.
The _getwritemode and _setwritemode functions get or set the logical write
mode for straight line drawing. The default mode, _GPSET, causes lines to be
drawn in the current graphics color. Other modes combine the current graphics
color and the original screen image using various logical operations.
The name of each function announces its task or the figure it draws, as the follow
ing list indicates:
Routine Use
_rectangle, _rectangle_w,
_rectangle_wxy
Draw L scan-fill a rectangle
Most of these routines are available in several forms, which are indicated by their
names. Output functions without a suffix use the view coordinate system. Func
tions that end with _w take double values as arguments and use the window
coordinate system. Functions that end with wxy use _wxycoord structures to de
_
Circular figures, such as arcs and ellipses, are centered within a "bounding rec
tangle" specified by two points that define the diagonally opposed comers of the
rectangle. The center of the rectangle becomes the center of the figure, and the
rectangle' s borders determine the size of the figure.
All of the routines listed in this section work in OS/2 as well as DOS.
Routine Use
The _outtext and _outmem routines provide no formatting. If you want to out
put integer or floating-point values, you must convert the values into a string vari
able (using the sprintf function) before calling these routines.
The _outtext routine recognizes the \n (newline character) and \r (carriage re
turn) sequences. The _outmem routine treats these sequences as printable
graphics characters.
2. 6. 1. 7 Transferring Images
The functions in this category transfer screen images between memory and the
display, using a buffer allocated by the application, or determine the size in bytes
of the buffer needed to store a given image.
The functions that end with _w or _wxy use window coordinates; the other func
tions in this set use view coordinates.
32 Microsoft C Run-Time Library Reference
Routine Use
In some cases, the buffer needed to store an image with the _getimage functions
must be larger than 64K (65,535) bytes. Use the halloc routine to allocate a buff
er larger than 64K.
2. 6. 1. B Displaying Fonts
The functions listed in this section control the display of font-based characters on
the screen.
Routine Use
Category Task
Displaying presen Initialize video structures for presentation graphics
tation graphics and establishes the default chart type. Display
presentation-graphics chart: bar, column, pie, scat
ter, or line chart.
Analyzing Analyze data (does not display chart).
presentation-graphics
data
Routine Use
_pg_chart Displays a single-series bar, column, or line chart
_pg_chartms Displays a multiseries bar, column, or line chart
_pg_chartpie Displays a pie chart
_pg_chartscatter Displays a scatter diagram for a single series of data
_pg_chartscatterms Displays a scatter diagram for more than one series
of data
_pg_defaultchart Initializes all necessary variables in the chart en
vironment for a specified chart type
_pg_initchart Initializes the presentation-graphics library
34 Microsoft C Run·Time Library Reference
Routine Use
_pg_analyzechart Analyzes a single series of data for a bar, column, or
line chart
Routine Use
_pg_hlabelchart Writes text horizontally on the screen
_pg_vlabelchart Writes text vertically on the screen
_pg_getpalette Retrieves current colors, line styles, fill patterns, and
plot characters for all presentation-graphics palettes
_pg_setpalette Sets current colors, line styles, fill patterns, and plot
characters for all presentation-graphics palettes
_pg_resetpalette Sets current colors, line styles, fill patterns, and plot
characters to the default values for the current screen
mode
I. Stream
2. Low-level
The "console and port" 1/0 routines allow you to read or write directly to a con
sole (keyboard and screen) or an I/O port (such as a printer port). The port 1/0
routines simply read and write data in bytes. With console 1/0 routines, some ad
ditional options are available, such as detecting whether a character has been
typed at the console. YOU c an also choose between echoing characters to the
screen as they are read or reading characters without echoing.
The C library also provides a number of direct DOS 1/0 system call routines.
These are described in Section 2. 14, "System Calls."
File 1/0 operations can be performed in two modes: text or binary. The following
section describes these modes and their use.
WARNING Because stream routines are buffered and low-level routines are not, the two
types of routines are generally incompatible. You should use either stream or low-level
routines consistently forprocessing a given file.
Sometimes you may want to process a file without making those translations. In
these cases you use binary mode, which suppresses CR-LF translations.
You can control the file translation mode in the following ways:
• To process a few selected files in binary mode, while retaining the default
text mode for most files, you can specify binary mode when you open the
selected files. The fopen routine opens a file in binary mode when you
specify the letter b in the access-mode string for the file. The open routine
opens a file in binary mode when you specify the 0_BINARY flag in the of/ag
argument. For more information about fopen and open, see the reference de
scription of each routine.
• To process most or all files in binary mode, you can change the default mode
to binary. The global variable _fmode controls the default translation mode,
which is normally text. If you set _fmode to O_BINARY, the default mode is
binary except for stdaux and stdprn, which are opened in binary mode by
default.
1. Link with the file BINMODE.OBJ (supplied with Microsoft C). This changes
the initial setting of _fmode to the 0_BINARY flag, causing all files except
stdio, stdout, and stderr to be opened in binary mode.
2. Change the value of _fmode directly by setting it to the 0_BINARY flag in
your program. This has the same effect as linking with BINMODE.OBJ.
You can still override the default mode (now binary) for a particular file by open
ing it in text mode. Specify the letter t when using fopen, or specify the 0_TEXT
flag when using open.
By default, the stdio, stdout, and stderr files are opened in text mode, and the
stdaux and stdprn files are opened in binary mode. The setmode routine allows
you to change these defaults or change the mode of a file after it has been
opened. See the reference description of setmode for details.
When a file is opened for 1/0 using the stream functions, the opened file is as
sociated with a structure of type FILE (defined in STDIO.H) containing basic in
formation about the file. A pointer to the FILE structure is returned when the
stream is opened. Subsequent operations use this pointer (also called the "stream
pointer," or just "stream") to refer to the file.
The stream functions provide for buffered, formatted, or unformatted input and
output. When a stream is buffered, data that is read from or written to the stream
is <;:ollected in an intermediate storage location called a "buffer". In write opera
tions, the output buffer's contents are written to the appropriate final location
when the buffer is full, the stream is closed, or the program terminates normally.
The buffer is said to be "flushed" when this occurs. In read operations, a block of
data is placed in the input buffer read from the buffer; when the input buffer is
empty, the next block of data is transferred into the buffer.
B uffering produces efficient 1/0 because the system can transfer a large block of
data in a single operation rather than performing an 1/0 operation each time a
data item is read from or written to a stream. However, if a program terminates
abnormally, output buffers may not be flushed, resulting in loss of data.
Routine Use
clearerr Clears the error indicator for a stream
The fdopen, fopen, freopen, and _fsopen functions return a FILE pointer. You
normally assign the pointer value to a variable and use the variable to refer to the
opened stream. For instance, if your program contains the lines
FI L E *i n fil e
i n fi l e= fopen ( " test . da t " , "r" ) ;
you can use the FILE pointer variable i nfi 1 e to refer to the stream.
You can refer to the standard streams with the following predefined stream
pointers:
40 Microsoft C Run-Time Library Reference
Pointer Stream
stdin Standard input
You can use these pointers in any function that requires a stream pointer as an ar
gument. Some functions, such as getchar and putchar, are designed to use stdio
or stdout automatically. The pointers stdio, stdout, stderr, stdaux, and stdprn
are constants, not variables; do not try to assign them a new stream pointer value.
DOS and OS/2 allow you to redirect a program' s standard input and standard out
put at the operating-system command level. OS/2 also allows you to redirect a
program's standard error. See your operating system user's manual for a com
plete discussion of redirection.
Within your program, you can use freopen to redirect stdio, stdout, stderr,
stdaux, or stdprn so that it refers to a disk file or to a device. See the reference
description of freopen for more details.
By using the setbuf or setvbuf function, you can cause a stream to be unbuff
ered, or you can associate a buffer with an unbuffered stream. Buffers allocated
by the system are not accessible to you, but buffers allocated with setbuf or
setvbuf refer to arrays in your program and can be manipulated. Buffers can be
any size up to 32,767 bytes. This size is set by the manifest constant BUFSIZ in
STDIO.ff if you use seftbuf; if you use setvbuf, you can set the size of the buffer
yourself. (See the descriptions of setbuf and setvbuf in the reference section for
more details.)
NOTE These routines affect only buffers created by C library routines. They have no effect
on buffers created by the operating system.
Run· Time Routines by category 41
Reading and writing operations on streams always begin at the current position
of the stream, known as the "file pointer" for the stream. The file pointer is
changed to reflect the new position after a read or write operation takes place.
For example, if you read a single character from a stream, the file pointer is in
creased by one byte so that the next operation begins with the first unread char
acter. If a stream is opened for appending, the file pointer is automatically
positioned at the end of the file before each write operation.
The fseek and fsetpos functions allow you to position the file pointer anywhere
in a file. The next operation occurs at the positi on you specified. The rewind
routine positions the file pointer at the beginning of the file. Use the ftell or
fgetpos routine to determine the current position of the file pointer.
The feof macro detects an end-of-file condition on a stream. Once the end-of-file
indicator is set, it remains set until the file is closed, or until clearerr, fseek,
fsetpos, or rewind is called.
Streams associated with a character-oPiented device (such as a console) do not
have file pointers. Data coming from or going to a console cannot be accessed
randomly. Routines that set or get the file-pointer position (such as fseek,
fgetpos, fsetpos, ftell, or rewind) have undefined results if used on a stream as
sociated with a character-oriented device.
2. 7. 3 Low-Level Routines
Low-level input and output calls do not buffer or fonnat data. Declarations
for the low-level functions are given in the include files IO.H, FCNTL.H,
SYS\TYPES.H, and SYS\STAT.H. Unlike the stream functions, low-level func
tions do not require the include file STDIO.H. However, some common con
stants are defined in STDIO.H; for example, the end-of-file indicator (EOF) may
be useful. If your program requires these constants, you must include STDIO.H.
Routine Use
close Closes a file
creat Creates a file
dup Creates a second handle for a file
dup2 Reassigns a handle to a file
eof Tests for end-of-file
lseek Repositions file pointer to a given location
open Opens a file
read Reads data from a file
sopen Opens a file for file sharing
tell Gets current file-pointer position
umask Sets default file-pennission mask
write Writes data to a file
Stream Handle
stdin 0
stdout 1
stderr 2
stdaux (DOS only) 3
stdprn (DOS only) 4
You can use these file hanqles without previously opening the files. The files are
opened and the handles are assigned when the program starts.
The dup and dup2 functions allow you to assign multiple handles for the same
file. These functions are typically used to associate the predefined file handles
with different files.
44 Microsoft C Run-Time Library Reference
In DOS and OS/2, you can redirect the standard input and standard output at the
operating-system command level. OS/2 also allows you to redirect the standard
error. See your operating system user's manual for a complete discussion of
redirection.
Routine Use
cgets Reads a string from the console
cprintf Writes formatted data to the console
NOTE Programs that need only run under DOS can also use a number of direct DOS 110
system calls ( _das_ open, _das_read, das close, etc.) These are described in detail In
_ _
The console or port does not have to be opened or closed before 1/0 is per
formed, so there are no open or close routines in this category. The port 1/0
Run-Time Routines by Category 45
routines inp and outp read or write one byte at a time from the specified port.
The inpw and outpw routines read and write two-byte words, respectively.
The console 1/0 routines allow reading and writing of strings (cgets and cputs),
formatted data (cscanf and cprintf), and characters. Several options are available
when reading and writing characters.
The putch routine writes a single character to the console. The getch and getche
routines read a single character from the console; getche echoes the character
back to the console, while getch does not. The ungetch routine "ungets" the last
character read; the next read operation on the console begins with the "ungotten"
character.
The kbhit routine determines whether a key has been struck at the console. This
routine allows you to test for keyboard input before you attempt to read from the
console.
NOTE The console 110 routines are not compatible with stream or low-level library
routines and should not be used with them.
2. 8 Internationalization
Internationalization routines are useful for creating different versions of a pro
gram for international markets. These routines are declared in the header file
LOCALE.H, except for strftime, which is declared in TIME.H.
Routine Use
localeconv Sets a structure with appropriate values for format
ting numeric quantities
setlocale Selects the appropriate locale for the program
strcoll Compares strings using locale-specific information
strftime Formats a date and time string
strxfrm Transforms a string based on locale-specific
information
2. 9 Math
The math routines allow you to perform common mathematical calculations. All
math routines work with floating-point values and therefore require floating
point support (see Section 1 .8, "Floating-Point Support").
46 Microsoft C Run-Time Library Reference
The math library provides two versions of some routines. The first version of the
routine supports double arguments and return values. The second version sup
ports an 80-bit data type, allowing the routine to take long double arguments and
return a long double value. The second version usually has the same name with
the suffix I. For instance, the acos routine supports double arguments and return
values, while acosl supports long double arguments and return values.
Routines which support long double values are not available when you compile
with the /Fpa (alternate math) compiler option. The same is true of the _clear 87,
_control87, and _status87 routines.
Most math declarations are in the include file MATH.H. However, the clear87,
_control87, _fpreset, and _status87 routines are defined in FLOAT.H:-the abs
and labs functions are defined in MATH.H and STDLIB.H, and the div and ldiv
routines are declared in STDLIB.H.
Routine Use
acos, acosl Calculate the arccosine
asin, asinl Calculate the arcsine
atan, atanl Calculate the arctangent
�tan2, atan21 Calculate the arctangent
bessel Calculates Bessel functions
cabs, cabsl Find the absolute value of a complex number
ceil, ceill Find the integer ceiling
_clear87 Gets and clears the floating-point status word
control87 Gets the old floating-point control word and sets a
new control-word value
cos, cosl Calculate the cosine
cosh, coshl Calculate the hyperbolic cosine
dieeetomsbin Converts IEEE double-precision number to Micro
soft (MS) binary format
div Divides one integer by another, returning the
quotient and remainder
dmsbintoieee Converts Microsoft binary double-precision number
to IEEE format
exp, expl Calculate the exponential function
fabs, fabsl Find the absolute value
Run-Time Routines by Category 47
floor, floorl Find the largest integer less than or equal to the
argument
_Irotl, _Irotr Shift an unsigned long int item left ( _lrotl) or right
( _lrotr)
modf, modfl Break down the argument into integer and fractional
parts
The be�el routine does not correspond to a single function, but to twelve func
tions named jO, jl, jn, yO, yl, yn, JOI, jll, jnl, JOI, Jll, and Jnl .
The matherr and _matherrl routines are invoked by the math functions when er
rors occur. The matherr routine handles functions that return a double value and
_matherrl handles routines that return a long double.
These routines are defined in the library, but you can redefine them for different
error-handling. The user-defined function, if given, must follow the rules given
in the reference description of matherr and �matherrl.
You are not required to supply a definition for the matherr routines. If no defini
tion is present, the default error returns for each routine are used. The reference
description of each routine describes that routine's error returns.
2. 10 Memory Allocation
The memory-allocation routines allow you to allocate, free, and reallocate blocks
of memory. Memory-allocation routines are declared in the include file
MALLOC.H.
Routine Use
alloca Allocates a block of memory from
the program's stack
_nmalloe
malloc, bmalloc, -fmalloc, Allocate a block of memory
_nrealloe
realloc, brealloc, -frealloc, Reallocate a block to a new size
The malloc and free routines allocate and free memory space, respectively,
while a program runs. The malloc routine allocates memory from the "heap,"
which is a pool of memory not otherwise used by your program. In tiny-, small-,
and medium-model programs, the heap consists of unused memory in your pro
gram's default data segment. In compact-, large-, and huge-model programs, it is
unused memory outside the default data segment.
The malloc and free routines satisfy the memory-allocation requirements of most
programs. More specialized memory-management routines are discussed below.
The realloc and _expand routines can expand or shrink an allocated memory
block. They behave differently in cases in which there is not enough room to ex
pand the block in its current location. In this case, realloc moves the block as
needed, but _expand does not.
The calloc routine allocates memory for an array and initializes every byte in the
allocated block to 0.
The halloc routine is similar to calloc, except that it can allocate memory for a
huge array (one that exceeds 64K in size). This routine is useful when you need a
50 Microsoft C Run-Time Library Reference
very large data object, or if you need to return allocated memory to the operating
system for subsequent calls to the spawn family of functions.
• Localized data. Based heaps allow you to group related data in a single seg
ment. This can simplify the management of related data. In OS/2, based heaps
can also minimize the risk of general protection faults and improve
performance.
• Faster pointer arithmetic. Although the based heap lies in the far data seg
ment, pointers to its data items are the same size as near pointers. Thus,
pointer arithmetic on items in a based heap is faster than pointer arithmetic on
items in the far heap.
The _bheapseg routine allocates a based heap segment, from which you can then
allocate blocks of memory. You can call _bheapseg more than once to allocate
Run-Time Routines by Category 51
The _bfreeseg routine frees a based-heap segment. This routine frees every block
in the based-heap segment, whether or not you previously freed the blocks
individually.
NOTE Near- . far- . and based-heap calls are not ANSI compatible and will make your pro
gram less portable.
All process-control functions except signal are declared in the include file
PROCESS.H. The signal function is declared in SIGNAL.H. The abort, exit,
and system functions are also declared in the STDLIB.H include file. The
environment-control routines (getenv and putenv) are declared in STDLIB.H.
Routine Use
The atexit and onexit routines create a list of functions to be executed when the
calling program terminates. The only difference between the two is that atexit is
part of the ANSI standard. The onexit function is offered for compatibility with
previous versions of Microsoft C.
The _exit routine terminates a process immediately, whereas exit terminates the
process only after flushing buffers and calling any functions previously regis
tered by atexit and onexit. The _cexit and _c_exit routines are identical to exit
and _exit, respectively, except that they return control to the calling program
without terminating the process.
The setjmp and longjmp routines save and restore a stack environment. These
allow you to execute a nonlocal goto.
The exec and spawn routines start a new process called the "child" process. The
difference between the exec and spawn routines is that the spawn routines are
capable of returning control from the child process to its caller (the "parent"
process). Both the parent process and the child process are present in memory
(unless P_OVERLAY is specified). In the exec routines, the child process over
lays the parent process, so returning control to the parent process is impossible
(unless an error occurs when attempting to start execution of the child process).
54 Microsott C Run·Time Library Reference
There are eight fonns each of the spawn and exec routines (see Table 2. 1 ). The
differences among the fonns involve the method of locating the file to be ex
ecuted as the child process, the method for passing arguments to the child
process, and the method of setting the environment.
Passing an argument list means that the arguments to the child process are listed
separately in the exec or spawn call. Passing an argument array means that the ar
guments are stored in an array, and a pointer to the array is passed to the child
process. The argument-list method is typically used when the number of argu
ments is constant or is known at compile time. The argument-array method is use
ful when the number of arguments must be detennined at run time.
Argument-Passing
Routines Locating the File Convention Environment Settings
execl, spawnl Do not use PATH Argument list Inherited from parent
execv, spawnv Do not use PATH Argument array Inherited from parent
The assert macro is typically used to test for logic errors. It prints a message
when a given "assertion" fails to hold true. Defining the identifier NDEBUG to
any value causes occurrences of assert to be removed from the source file, thus
allowing you to tum off assertion checking without modifying the source file.
Routine Use
bsearch Perfonns binary search
lfmd Perfonns linear search for given value
lsearch Perfonns linear search for given value, which is
added to array if not found
qsort Perfonns quick sort
2. 13 String Manipulation
The string functions are declared in the include file STRING.H. They allow you
to compare strings, copy them, search for strings and characters, and perfonn
various other operations.
Routine Use
strcat, _fstrcat Append one string to another
strchr, _fstrchr Find first occurrence of a given character in a string
strcmp, _fstrcmp Compare two strings
strcpy, _fstrcpy Copy one string to another
strcspn, _fstrcspn Find first occurrence of a character from a given
character set in a string
strdup, _fstrdup, Duplicate a string
_nstrdup
strerror Maps an error number to a message string
56 Microsoft C Run· Time Library Reference
2. 14 System Calls
The following routines give access to IBM-PC BIOS interrupts and DOS system
calls. Except for the FP_OFF, FP_SEG, and segread routines, these routines are
for DOS application programs only; they do not work under OS/2.
Run-Time Routines by Category 57
Routine Use
_bios_disk Issues service requests for both hard and floppy
disks, using INT Ox 1 3
_bios_equiplist Performs an equipment check, using INT Ox 1 1
_bios_keybrd Provides access to keyboard services, using
INT Ox l 6
_bios_memsize Obtains information about available memory, using
INT 0x l 2
_bios_printer Performs printer output services, using INT Ox 17
_bios_serialcom Performs serial communications tasks, using
INT Ox l 4
NOTE BIOS routines are hardware dependent. Some of them may not work as expected
on machines whose hardware differs from the IBM PC.
2. 14.2 D OS Interface
These routines are implemented as functions and declared in DOS.H.
Routine Use
bdos Invokes DOS system call; uses only DX and AL
registers
_chain_intr Chains one interrupt handler to another
_disable Disables interrupts
_dos_allocmem Allocates a block of memory, using DOS system
call Ox48
_dos_close Closes a file, using DOS system call Ox3E
dos creat Creates a new file and erases any existing file
having the same name, using DOS system call Ox3C
58 Microsoft C Run-Time Library Reference
dos tindfirst Finds first occurrence of a given file, using DOS sys
tem call Ox4E
_dos_getdate Gets the system date, using DOS system call Ox2A
_dos_getftime Gets the date and time a file was last written, using
DOS system call Ox57
dos setfileattr Sets the current attributes of a file, using DOS sys
tem call Ox43
_dos_setftime Sets the date and time that the specified file was last
written, using DOS system call Ox57
Run-Time Routines by Category 59
_dos_settime Sets the system time, using DOS system call Ox2D
The dosexterr function obtains and stores the error information returned by DOS
system call Ox59 (extended error handling). This function is provided for use
w ith DOS versions 3.0 and later.
The bdos routine is useful for invoking DOS calls that use either or both of the
DX (DH/DL) and AL registers for arguments. However, bdos should not be used
to invoke system calls that return an error code in AX if the cany flag is set;
since your program cannot detect whether the cany flag is set, it cannot deter
mine whether the value in AX is a legitimate value or an error value. In this case,
the intdos routine should be used instead, since it allows the program to detect
whether the carry flag is set. The intdos routine can also be used to invoke DOS
calls that use registers other than DX and AL.
60 Microsoft C Run· Time Libraty Reference
The intdosx routine is similar to the intdos routine, but is used when ES is re
quired by the system call, when DS must contain a value other than the default
data segment (for instance, when a far pointer is used), or when making the sys
tem call in a large-model program. When calling intdosx, give an argument that
specifies the segment values to be used in the call.
The int86 routine can be used to invoke any interrupt. The int86x routine is simi
lar; however, like the intdosx routine, it is designed to work with large-model
programs and far items, as described in the preceding paragraph.
The FP_OFF and FP_SEG routines allow easy access to the segment and offset
portions of a far pointer value. FP_OFF and FP_SEG are implemented as macros
and defined in DOS.H. You can use these macros in OS/2 as well as DOS.
The segread routine returns the current values of the segment registers. This
routine is typically used with the intdosx and int86x routines to obtain the cor
rect segment values.
The _chain_intr routine is useful for chaining interrupt handlers together. The
_enable routine enables interrupts, while the _disable routine disables interrupts.
The routines prefixed with _dos_ are all direct system interfaces that use the sys
tem calls noted above. More detailed information on these system calls can be
found in the MS-DOS Encyclopedia (Duncan, ed.; Redmond, WA: Microsoft
Press, 1 988)or the Programmer's PC Sourcebook (Hogan; Redmond, WA:
Microsoft Press, 1 988).
NOTE The DOS interface 110 routines are generally Incompatible with console, low-level,
and stream 110 routines. Do not mix different types of 110 routines in the same source file.
2. 15 Time
The time functions allow you to obtain the current time, then convert and store it
according to your particular needs. The current time is always taken from the sys
tem time.
Routine Use
asctime Converts time from type struct tm to a character
string
clock Returns the elapsed CPU time for a process
ctime Converts time from a long integer to a character
string
Run· Time Routines by Category 61
The time and ftime functions return the current time as the number of seconds
elapsed since midnight Universal Coordinated Time (UTC) on January 1 , 1 970.
This value can be converted, adjusted, and stored in a variety of ways by using
the asctime, ctime, gmtime, localtime, and mktime functions. The utime func
tion sets the modification time for a specified file, using either the current time or
a time value stored in a structure.
The clock function returns the elapsed CPU time for the calling process.
The ftime function requires two files: SYS\TYPES.H and SYS\TIMEB.H. It is
declared in SYS\TIMEB.H. The utime function also requires two include files:
SYS\TYPES.H and SYS\UTIME.H. It is declared in SYS\UTIME.H. The re
mainder of the time functions are declared in the include file TIME.ff.
When you want to use ftime or localtime to make adjustments for local time,
you must define an environment .variable named TZ. Section 3.2, which de
scribes the global variables daylight, timezone, and tzname, includes a discus
sion of the TZ variable. TZ is also described on the tzset reference page in Part 2
of this book.
The _strdate and _strtime routines return strings containing the current date and
time, respectively, in the DOS and OS/2 date and time format rather than in the
XENIX-style formats.
The stfrtime function is useful for creating international versions of a program.
See Section 2.8, "Internationalization."
62 Microsoft C Run-Time Library Reference
Routine Use
va_arg Retrieves argument from list
For more information on the differences between the two versions and for an ex
planation of how to use the macros, see their descriptions in Part 2 of this book.
CHAPTER
Global Variables
and Standard Types
3. 1 _amblksiz
The _amblksiz variable controls memory heap granularity.
The _amblksiz variable controls the amount of memory used in the heap for dy
namic memory allocation.
Memory space is always requested from the operating system in blocks contain
ing _amblksiz bytes. The first time a program calls a memory-allocation func
tion such as malloc, the operating system allocates a block of heap memory. The
size of this block is defined by _amblksiz, which has a default value of SK
(8, 192 bytes).
Later memory requests are satisfied from the original block. When that block is
exhausted, another block of _amblksiz bytes is allocated. If your C program
allocates a block larger than _amblksiz, multiple blocks that are each of size
_amblksiz are allocated until the request is satisfied.
To change the size of the default memory block, assign the desired size to the
_amblksiz variable, as in the following example:
ambl ks i z = 2048 ;
63
64 Microsoft C Run· Time Library Reference
The heap allocator always rounds the operating-system request to the nearest
power of 2 greater than or equal to _amblksiz. The above statement allocates
memory in multiples of 2K (2,048 bytes).
Fewer system calls are required if you set _amblksiz to a large value, but your
program may use more memory than needed. If program speed is important, set
_amblksiz to a large value. If size is important, set _amblksiz to a smaller value.
Note that adjusting the value of _amblksiz affects allocation in the near, far, and
based heaps. The value of _amblksiz has no effect on huge memory blocks
(those allocated with halloc and similar functions).
Some time and date routines use the daylight, timezone, and tzname variables
to make local-time adjustments. Whenever a program calls the ftime, localtime,
or tzset function, the value of daylight, timezone, and tzname is determined
from the value of the TZ environment variable. If you do not explicitly set the
value of TZ, the default value of PST8PDT is used. The following list shows
each variable and its value:
Variable Value
daylight Nonzero if a daylight-saving-time zone (DST) is
specified in TZ; otherwise zero. Default value is one.
These variables are declared in the STDLIB.H include file. Manifest constants
for the errno variables are declared in the ERRNO.H include file. The declara
tions are as follows:
extern int _doserrno;
The include file ERRNO.H contains the definitions of the errno values. How
ever, not all of the definitions given in ERRNO.H are used in DOS and OS/2.
Some of the values in ERRNO.H are present to maintain compatibility with
XENIX and UNIX operating systems.
The errno values in DOS and OS/2 are a subset of the values for errno in
XENIX systems. Thus, the errno value is not necessarily the same as the actual
error code returned by a DOS or OS/2 system call. To access the actual DOS and
OS/2 error code, use the _doserrno variable, which contains this value.
In general, you should use _doserrno only for error detection in operations in
volving input and output, since the errno values for input and output errors have
DOS and OS/2 error-code equivalents. In other cases, the value of _doserrno is
undefined.
The syserrlist variable is an array; the perror and strerror routines use it to
process error infonnation. The sys_nerr variable tells how many elements the
sys_errlist array contains.
66 Mit:roso" C Run-Time Library Reference
Table 3. 1 gives the errno values for DOS and OS/2, the system error message
for each value, and the value of each constant. Note that only the ERANGE and
EDOM constants are specified in the ANSI standard.
3. 4 _fmode
The fmode variable controls the default file-translation mode.
These variables are useful for creating programs that run in different versions of
DOS and OS/2. For example, you can test the _osmajor variable before making
a call to sopen; if the major version number is earlier (less) than 3, open should
be used instead of sopen.
The _osmode variable indicates whether the program is in OS/2 protected mode
or in real mode (DOS or OS/2 real mode). An osmode value of DOS MODE in
dicates real mode operation and a value of OS�MODE indicates protected
operation.
3. 6 environ
The environ variable is a pointer to the strings in the process environment.
The environ variable is an array of pointers to the strings that constitute the
process environment. The environment consists of one or more entries of
the form
NAME=string
where NAME is the name of an environment variable and string is the value of
that variable. The string may be empty. The initial environment settings are taken
from the o�rating-system environment at the time of program execution.
The getenv and putenv routines use the environ variable to access and modify
the environment table. When putenv is called to add or delete environment set
tings, the environment table changes size; its location in memory may also
change, depending on the program's memory requirements. The environ varia
ble is adjusted in these cases and always points to the correct table location.
3. 7 _psp
The _psp variable contains the segment address of the program segment prefix
(PSP) for the process.
It is declared in the STDLIB.H include file as follows:
extern unsigned int _psp;
The PSP contains execution information about the process, such as a copy of the
command line that invoked the process and the return address on process termina
tion or interrupt. The _psp variable can be used to form a long pointer to the
PSP, where _psp is the segment value and 0 is the offset value.
Note that the _psp variable is supported only in DOS.
3. 8 Standard Types
A number of library routines use values whose types are defined in include files.
In the following list, these types are described, and the include file defining each
type is given.
Run-Time
Functions
Run- Time Functions
The second part of this book is the reference section. It describes,
in alphabetical order, each function of the run-time library pro
vided with the Microsoft C Professional Development System.
Each reference entry gives syntax, return values, and other useful
information about the library functions. Information on compati
bility is supplied to assist you in writing portable programs.
75
to stderr, then calls raise(SIGABRT). The action taken in response to the SIGABRT signal
depends on what action has been defined for that signal in a prior call to the signal func
tion. The default SIGABRT action is for the calling process to terminate with exit code 3,
returning control to the parent process or operating system.
The abort function does not flush stream buffers or do atexit/onexit processing.
Return Value The abort function does not return control to the caller. Rather, it terminates the process
and, by default, returns an exit code of 3 to the parent process.
In multithread libraries, the abort function does not call raise(SIGABRT). Instead, it
simply terminates the process with exit code 3.
See Also exec functions, exit, _exit, raise, signal, spawn functions
I * A B O RT . C : T h i s t r i e s t o o p e n a f i l e a n d a b o r t s i f t h e a t t em p t f a i l s . * /
#i n c l u d e < s t d i o . h >
#i n c l u d e < s t d l i b . h >
77 abort
v o i d ma i n ( )
{
FI LE *st ream ;
el se
fcl o s e ( s t ream ) ;
Output
C o u l d n ' t o p e n f i l e : N o s u c h f i l e o r d i r e c t o ry
a b n o rm a l p r o g r a m t e rm i n a t i o n
abs 78
#include <Stdlib.h> Required only for function declarations; use either STDLIB.H
#include <math.h> or MATH.H
n Integer value
Remarks The abs function returns the absolute value of its integer argument 11.
Return Value The abs function returns the absolute value of its argument. There is no error return.
I * A B S . C : T h i s p r o g r a m c omp u t e s a n d d i s p l a y s t h e a b s o l u t e v a l u e s o f
* s e v e r a l n um b e r s .
*/
v o i d ma i n ( )
{
i nt ix = -4 , i y ;
l on g lx = - 4 1 567 L , l y ;
doubl e dx = - 3 . 1 4 1 5 9 3 , dy ;
iy = a bs ( i x ) ;
p r i n t f ( " T h e a bsol ute v a l ue of %d i s %d\ n " , i x ' i y ) ;
ly = l abs ( l x ) ;
p r i ntf ( " T h e a b s o l ute v a l ue of %l d i s %l d \ n " , 1 x ' l y ) ;
dy = fabs ( dx ) ;
p r i n t f ( " T h e a b s o l u t e v a l u e o f % f i s % f \ n " , d x , dy l ;
79 abs
Output
Remarks With files, the access function detennines whether the specified file exists and can be
accessed in mode. The possible mode values and their meanings in the access call are as
follows:
Value Meaning
()() Check for existence only
02 Check for write pennission
04 Check for read pennission
06 Check for read and write pennission
With directories, access detennines only whether the specified directory exists; under
DOS and OS/2, all directories have read and write access.
Return Value The access function returns the value 0 if the file has the given mode. A return value of -1
indicates that the named file does not exist or is not accessible in the given mode, and
errno is set to one of the following values:
Value Meaning
EACCES Access denied: the file's pennission setting does not allow the
specified access.
ENOENT File or path name not found.
81 access
#i n c l u d e < i o . h > .
#i n c l u d e < s t d i o . h >
#i n c l ude < s t d l i b . h>
v o i d ma i n ( )
(
I* Check for exi stence */
i f ( ( acces s < • a ccess . c • , 0 > > != -1 >
(
p r i n t f C " Fi l e ex i s t s \ n " ) ;
I * C h e c k f o r w r i t e p e rm i s s i o n * /
i f { ( a cces s ( " a ccess . c " , 2 ) ) ! = -1 )
p r i n t f ( " F i l e h a s w r i t e p e rm i s s i o n \ n " );
Output
Fi l e exi sts
F i l e h a s w r i t e p e rm i s s i o n
acos Functions 82
#include <math.h>
#include <errno.h> Required for definition of ermo constant
Rematts The acos functions return the arccosine of x in the range 0 to 1t radians. The value of x
must be between -1 and 1 . The acosl function is the 80-bit counterpart, which uses an 80-
bit, 1 0-byte coprocessor form of arguments and return values. See the reference page on
the long double functions for more details on this data type.
Return Value The acos functions return the arccosine result. If x is less than - 1 or greater than l , the
function sets ermo to EDOM, prints a DOMAIN error message to stderr, and returns 0.
Error handling can be modified with the matherr (or _matherrl) routine.
Compatibility acos
acosl
See Also asin functions, atan functions, cos functions, matherr, sin functions, tan functions
����-
Exampm ��
1 * A S I N C O S . C : T h i s p r o g r a m p r om p t s f o r a v a l u e i n t h e r a n g e - 1 t o 1 .
* I n p u t v a l u e s o u t s i d e t h i s r a n g e w i l l p r o d u c e D O MA I N e r r o r m e s s a g e s .
* I f a v a l i d v a l u e i s entered , t h e program p r i n t s t h e a rc s i n e a n d t h e
* a rc c o s i n e o f t h a t v a l u e .
*I
#i n c l u d e < ma t h . h >
#i n c l ude <stdi o . h>
#i n c l u d e <stdl i b . h>
#i n c l ude < e r rn o . h >
83 acos Functions
v o i d ma i n ( }
(
doubl e x , y ;
Output
E n t e r a r e a l n um b e r b e t w e e n - 1 a n d 1 : . 32696
A r c s i n e o f 0 . 3 2 6 9 6 0 = 0 . 3 3 3085
Arccos i ne of 0 . 326960 = 1 . 237 7 1 1
al/oca 84
Remarks The alloca routine allocates size bytes from the program's stack. The allocated space is
automatically freed when the calling function is exited.
When you compile with optimization on (either by default or by using one of the /0 op
tions), the stack pointer may not be restored properly in functions that have no local varia
bles and that also reference the alloca function. The following program demonstrates the
·
problem:
I * C o m p i l e wi t h C L / L p / AM / O x / Fe * /
# i n c l u d e <ma l l o c . h >
v o i d ma i n ( v o i d
(
f u n c ( 10 ) ;
To ensure that the stack pointer is properly restored, make sure that any function refer
encing alloca declares at least one local variable.
The pointer value returned by alloca should never be passed as an argument to free, nor
should alloca be used in an expression that is an argument to a function.
Return Value The alloca routine returns a void pointer to the allocated space, which is guaranteed to be
suitably aligned for storage of any type of object. To get a pointer to a type other than
char, use a type cast on the return value. The return value is NULL if the space cannot be
allocated.
85 alloca
I * A L LOCA . C : T h i s p r o g r a m c h e c k s t h e s t a c k s p a c e a v a i l a b l e before
* and a ft e r u s i n g t h e a l l oc a func t i on t o a l l o c a t e space on the s t a c k .
*I
#i n c l u d e <ma l l oc . h >
#i n c l u d e < s t d i o . h>
v o i d ma i n ( )
(
c h a r *buffe r :
I * A l l o c a t e memo ry f o r s t r i ng . * /
b u f f e r - a l l oc a C 1 2 0 * s i zeof ( c h a r > l :
p r i n t f ( " En t e r a s t r i n g : • l :
g et s ( buffer l :
p r i n t f ( " Y o u entered : % s \ n " , b u f f e r l :
p r i n t f ( " By t e s a va i l a b l e o n s ta c k : % u \ n " , s t a c k a v a i l C l l :
Output
Byt e s a v a i l a b l e o n s ta c k : 2028
E n t e r a s t r i n g : How much s t a c k s p a c e w i l l t h i s s t r i ng t a k e ?
Y o u e n t e r e d : H ow mu c h s ta c k s p a c e w i l l t h i s s t r i ng t a k e ?
Byt e s a v a i l a b l e o n s t a c k : 1 90 2
_arc Functions 86
#include <graph.h>
short _far _arc( short xl, short yl, short x2, short y2, short x3, short y3,
short x4, short y4 ) ;
short _far _arc_w( double xl , double yl , double x2, double y2, double x3, double y3,
double x4, double y4 );
short _far _arc_wxy( struct _wxycoord _far *pwxyl , struct _wxycoord _far *pwxy2,
struct _wxycoord _far *pwxy3, struct _wxycoord _far *pwxy4 ) ;
Remarks The _arc functions draw elliptical arcs. The center of the arc is the center of the bounding
rectangle, which is defined by points (xl , yl ) and (x2, y2) for _arc and _arc_w and by
points pwxyl and pwxy2 for _arc_wxy. The arc starts where it intersects an imaginary line
extending from the center of the arc through (.x3, y3) for _arc and _arc_w and through
pwxy3 for _arc_wxy. It is drawn counterclockwise about the center of the arc, ending
where it intersects an imaginary line extending from the center of the arc through (x4, y4)
for _arc and _arc_w and through pwxy4 for _arc_wxy.
The _arc routine uses the view coordinate system. The _arc_w and _arc_wxy functions
use the real-valued window coordinate system.
In each case, the arc is drawn using the current color. Since an arc does not define a closed
area, it is not filled.
87 _arc Functions
Return Value These functions return a nonzero value if the arc is successfully drawn; otherwise, they
retum O.
See Also _ellipse functions, _lineto functions, _pie functions, _rectangle functions, _setcolor
/ * A RC . C : T h i s p r o g r a m _d raws a s i mp l e a rc . * /
v o i d ma i n ( )
{
s hort x , y ;
s t ruct xyc o o r d xy s t a rt , xyend , xyf i l l ;
I * Fi nd a v a l i d g r a p h i c s mode * I
i f { ! _s et v i d eomod e ( _MAX R E SMODE ) )
exi t ( 1 ) ;
I * D raw a rc s */
x = 1 00 ; y = 1 00 ;
_a rc ( x 60 , y
- - 60 , x, y, x - 30 , y - 60 , x - 60 , y - 30 );
_a rc ( x + 6 0 , y + 60 , x, y, x, y + 30 , x + 30 , y );
getch ( ) ;
_s e t v i d e omod e ( _D E FAU LTMOD E ) ;
asctime 88
#include <time.h>
Rsmadrs The asctime function converts a time stored as a structure to a character string. The
timeptr value is usually obtained from a call to gmtime or localtime, both of which return
a pointer to a tm structure, defined in TIME.H. (See gmtime for a complete description of
the tm structure fields.)
The tm structure contains the following elements:
Element Description
int tm_sec Seconds after the minute (0-59)
int tm_min Minutes after the hour (0-59)
int tm_hour Hours since midnight (0-23)
The string result produced by asctime contains exactly 26 characters and has the form of
the following example:
Wed J a n 02 0 2 : 0 3 : 5 5 1 9 80 \ n \ 0
A 24-hour clock i s used. All fields have a constant width. The newline character (\n) and
the null character ( '\0 ') occupy the last two positions of the string. The asctime function
uses a single statically allocated buffer to hold the return string. Each call to this routine de
stroys the result of the previous call.
Rsturn Va/us The asctime function returns a pointer to the character string result. There is no error
return.
89 asctime
I * ASCT I M E . C : T h i s p r o g r a m pl a c e s t h e s y s t em t i me i n t h e l o n g i n t e g e r a c l o c k ,
* t r a n s l a t e s i t i n t o t h e s t r u c t u r e newt i me a n d t h en c o n v e r t s i t t o
* s t r i n g form f o r o u t p u t , u s i ng t h e a s c t i me f u n c t i on .
*I
#i n c l u d e < t i me . h >
#i n c l ude < s t d i o . h >
s t r u c t tm *newt i me ;
t i me_t a c l o c k ;
v o i d ma i n C l
(
t i me ( &a c l o c k > : I * G e t t i me i n s e c o n d s * /
/ * P r i n t l oc a l t i me a s a s t r i n g * /
p r i n t f ( " T h e c u r rent d a t e a n d t i me a re : % s \ n " , a s c t i me C n ewt i me ) ) ;
Output
T h e c u r rent d a t e a n d t i me a r e : T h u J u n 1 5 06 : 57 : 59 1 989
asin Functions 90
#include <math.h>
#include <errno.h>
Remarks The asin functions calculate the arcsine of x in the range -rc/2 to rt/2 radians. The value of
x must be between -1 and 1 . The asinl function is the 80-bit counterpart, which uses an 80-
bit, 1 0-byte coprocessor form of arguments and return values. See the reference page on
the long double functions for more details on this data type.
Return Value The asin functions return the arcsine result. If x is less than -1 or greater than 1 , asin sets
errno to EDOM, prints a DOMAIN error message to stderr, and returns 0.
Error handling can be modified by using the matherr (or _matherrl) routine.
Compatibility asin
asinl
S1111 Also acos functions, atan functions, cos functions, matherr, sin functions, tan functions
Example ������
I * AS I N COS . C : T h i s p ro g r a m p r ompts f o r a v a l ue i n t h e r a n ge -1 to 1 .
* I n p u t v a l ues o u t s i d e t h i s r a n g e wi l l p r o d u c e DOMA I N e r ro r mes s a ges .
* I f a v a l i d va l ue i s ente red , t h e p r o g r a m p r i n t s t h e a rc s i n e a n d t h e
* a rc c o s i n e o f t h a t v a l ue .
*I
#i n c l u d e <ma t h . h>
#i n c l u d e <stdi o . h>
#i n c l ude < s t d l i b . h>
#i n c l ude <errno . h>
91 asin Functions
v o i d ma i n ( )
{
doubl e x , y ;
p r i n t f ( " E n t e r a r e a l n um b e r b e t w e e n - 1 a n d 1 : " );
s c a n f ( " %l f " , &x ) ;
y = asin( x ) ;
p r i n t f ( " A r c s i n e of % f = % f \ n " , x , y l ;
y = a cos ( x ) ;
p r i n t f ( " A r c c o s i n e of %f = % f \ n " , x , y ) ;
Output
#include <assert.h>
#include <Stdio.h>
Remadrs The assert routine prints a diagnostic message and calls the abort routine if expression is
false (0). The diagnostic message has the form
where filename is the name of the source file and line number is the line number of the
assertion that failed in the source file. No action is taken if expression is true (nonzero).
The assert routine is typically used in program development to identify program logic er
rors. The given expression should be chosen so that it holds true only if the program is
operating as intended. After a program has been debugged, the special "no debug" identi
fier NDEBUG can be used to remove assert calls from the program. If NDEBUG is defined
(by any v alue) with a ID command-line option or with a #define directive, the C preproces
sor removes all assert calls from the program source.
#i n c l u d e < s t d i o . h >
#i n c l u d e < a s s e r t . h >
#i n c l ude < s t r i n g . h >
assert
v o i d a n a l y z e_s t r i n g ( c h a r * s t r i n g ) ; / * P rototype * /
v o i d ma i n ( )
(
. . .
c h a r t e s t l [ ] = " a bc " , * t e s t 2 = N U L L , t e s t 3 [ ] = .
I * Tes t s a s t r i ng to s e e i f i t i s N U L L , empty , o r l on g e r t h a n 0 c h a r a c t e r s * /
v o i d a n a l y z e_s t r i n g ( c h a r * s t r i n g )
(
a s sert< stri ng ! = NULL ) ; I * Ca nnot be N U L L */
a s sert < *stri ng ! = ' \0 ' > ; I * C a n n o t b e empty * /
a s s e r t ( s t r l en ( s t r i n g ) > 2 ) ; I * L e n g t h m u s t b e g re a t e r t h a n 2 * /
Output
An a l y z i n g s t r i n g ' a bc '
Ana l y z i n g s t r i n g ' ( n u l l ) '
A s s e rt i o n fa i l ed : s t r i n g ! = N U L L , f i l e a s s e rt . c , l i n e 2 8
a bn o rma l p r o g r a m t e rmi n a t i on
atan Functions 94
Description Calculate the arctangent of x (atan and atanl) and the arctangent of ylx (atan2 and atan21).
#include <math.h>
x, y Any number
Remarks The atan family of functions calculates the arctangent of x, and the atan2 family of func
tions calculates the arctangent of y/x. The atan group returns a value in the range -7r./2 to
7r./2 radians, and the atan2 group returns a value in the range -7t to 7t radians. The atan2
functions use the signs of both arguments to determine the quadrant of the return value.
Return Value The atan family of functions returns the arctangent result. If both arguments of atan2 or
atan21 are 0, the function sets errno to EDOM, prints a DOMAIN error message to stderr,
and returns 0.
Error handling can be modified by using the matherr (or _matherrl) routine.
atanl, atan21
SBB A/so acos functions, asin functions, cos functions, matherr, sin functions, tan functions
#i n c l u d e <ma t h . h >
#i n c l u d e < s td i o . h >
#i n c l u d e < e r r n o . h>
95 atan Functions
v o i d ma i n ( )
I
doubl e x l , x2 , y:
Output
E n t e r a rea l n umbe r : - 8 6 2 . 42
A r c t a n gent of - 8 6 2 . 420000 : - 1 . 5 6 9 6 3 7
E n t e r a s e c o n d rea l n umbe r : 7 8 . 5 1 4 9
A rc t a n g ent of - 8 6 2 . 420000 I 78 . 5 1 4900 : - 1 . 480006
atexit 96
Remarks The atexit function is passed the address of a function <June) to be called when the pro
gram terminates normally. Successive calls to atexit create a register of functions that are
executed in LIFO (last-in-first-out) order. No more than 32 functions can be registered
with atexit or onexit. The functions passed to atexit cannot take parameters.
All routines passed to atexit should have the _loadds attribute if used in multithread
dynamic-link libraries.
Return Value The atexit function returns 0 if it is successful, or a nonzero value if an error occurs (e.g.,
if there are already 32 exit functions defined).
Use the ANSI-standard atexit function (rather than the similar onexit function) whenever
ANSI portability is desired.
In the OS/2 environment, the atexit function calls the OS/2 function DosExitList.
I * AT E X I T . C : T h i s p r o g r a m p u s h e s four f u n c t i on s o n t o t h e s t a c k of funct i on s
* t o b e e x e c u t e d w h e n a t ex i t i s c a l l ed . W h e n t h e p r o g r a m e x i t s , t h e s e
* p r o g rams a re exec u t ed on a " l a s t i n , f i r s t out " ba s i s .
*I
#i n c l u d e < s t d l i b . h >
#i n c l u d e < s t d i o . h >
97 atexit
v o i d ma i n ( }
(
a t ex i t ( f n l > ;
a t ex i t ( fn2 } ;
a t e x i t ( fn3 } ;
a t ex i t ( fn4 } ;
p r i n t f ( " T h i s i s e x e c u t ed fi r s t . \ n " } ;
v o i d fn l C }
(
p r i n t f C " n ext . \ n " } ;
v o i d fn 2 ( }
(
p r i n t f ( • ex e c u ted • } ;
v o i d fn 3 C }
(
pri ntf( " i s • } ;
v o i d fn4 ( }
I
pri ntf( "Thi s " } ;
Output
T h i s i s executed f i r s t .
T h i s i s executed next .
atof, atoi, atol, _atold 98
Description Convert strings to double (atof), long double (_atold) integer (atoi), or long (atol).
Remades These functions convert a character string to a double-precision floating-point value (atof),
an integer value (atoi), a long integer value (atol); or a long double value (_atold). The
input string is a sequence of characters that can be interpreted as a numerical value of the
specified type.
The string size that can be handled by the atof or _atold function is limited to 100
characters.
The function stops reading the input string at the first character that it cannot recognize as
part of a number. This character may be the null character ( ' \0 ' ) terminating the string.
The atof and _atold functions expect string to have the following form:
[whitespaceD [ { sign ) D [ IKOdigitsD [.digitsD [ { d I D I e I E } [sign]digitsD
A whitespace consists of space and/or tab characters, which are ignored; sign is either plus
(+) or minus (-); and digits are one or more decimal digits. If no digits appear before the
decimal point, at least one must appear after the decimal point. The decimal digits may be
followed by an exponent, which consists of an introductory letter (d, D, e, or E) and an op
tionally signed decimal integer.
The atoi and atol functions do not recognize decimal points or exponents. The string argu
ment for these functions has the form
[whitespaceD [signDdigits
where whitespace, sign, and digits are exactly as described above for atof.
99 atof, atoi, atol, _atold
Return Value Each function returns the double, long double, int, or long value produced by interpret
ing the input characters as a number. The return value is 0 (for atoi), OL (for atol), and 0.0
(for atof and _atold) if the input cannot be converted to a value of that type. The return
value is undefined in case of overflow.
_atold
#i n c l u d e < s t d l i b . h >
#i n c l u d e < s td i o . h >
v o i d ma i n ( )
{
c h a r *s ; d o u b l e x; i n t i ; l on g 1 ;
s = • - 2 3 09 . 1 2 E - 1 5 " ; / * T e s t of a t of * /
x = atofC s ) ;
p r i n t f C • a t of test : A SC I I s t r i ng : % s \ t f l o a t : %e\n " , s , x );
s =• - 9885 p i g s " ; / * T e s t of a t o i * /
i =atoi C s ) ;
pri ntf( " atoi test : A SC I I s t r i n g : % s \ t \ t i n t eg e r : %d \ n " , s , );
Output
#include <dos.h>
int bdos( int dosfunc, unsigned int dosdx, unsigned int dosal );
Remades The bdos function invokes the DOS system call specified by dosfunc after placing the
values specified by dosdx and dosal in the DX and AL registers, respectively. The bdos
function executes an INT 2 1 H instruction to invoke the system call. When the system call
is complete, bdos returns the contents of the AX register.
The bdos function is intended to be used to invoke DOS system calls that either take no
arguments or take arguments only in the DX (DH, DL) and/or AL registers.
Do not use the bdos function to call interrupts that modify the DS register. Instead, use the
intdosx or int86x function. The intdosx and int86x functions load the DS and ES registers
from the segregs parameter and also store the DS and ES registers into segregs after the
·
function call.
This call should not be used to invoke system calls that indicate errors by setting the carry
· flag. Since C programs do not have access to this flag, your program cannot determine
whether the return value is an error code. The intdos function should be used in these
cases.
Return llatue The bdos function returns the value of the AX register after the system call has completed.
v o i d ma i n ( )
(
I * Offset of s t r i n g mu s t be i n D X , segment i n D S . A L i s not needed ,
* s o 0 i s u s ed .
*/
bdos C 0x09 , ( i n t ) s t r , 0 ) ;
Output
Hel l o worl d !
103 _beginthread
RemalkB The _beginthread function creates a thread that begins execution of a far routine at
start address. When the thread returns from that far routine, it is terminated automatically.
The user can also terminate the thread by calling endthread.
-
The address of the thread stack is given by stack_bottom. If stack_bottom is set to NULL,
the run-time library code will allocate and deallocate the thread stack as needed. Since the
_beginthread function can determine the current status of all thread IDs, it can free the old
stack and allocate a new stack whenever a thread is reused.
If it is not NULL, the stack_bottom argument must specify a word address, and the stack
must be at least as long as specified by the stack_size argument. Usually this memory is
either a global array or memory returned by malloc or _fmalloc.
practice in multithread programming is to make the first thread the main thread and wait
All threads will be tenninated if any thread calls abort, exit, exit, or DosExit. A good
The OS/2 function DosCreateThread should not be called directly to create threads. The
_beginthread function perfonns initialization procedures required to call other C run-time
library functions safely.
Return Value The function returns the thread identification number of the new thread, if successful. A re
turn value of -1 indicates an error, and errno is set to one of the following values:
Value Meaning
I * B EGTH RD . C i l l u s t ra t e s mul t i p l e t h re a d s u s i n g f u n ct i o n s :
* _beg i n t h r e a d _en d t h r e a d
*
* Al s o t h e g l oba l v a r i a b l e :
* _t h r ea d i d
*
* T h i s p r o g r a m req u i res t h e mul t i t h re a d l i b ra ry . For e x a mp l e , c omp i l e
* w i t h t h e f o l l ow i n g c omma nd l i n e :
* C L / MT TH READS . C
*I
#d e f i n e I N C L_NOCOMMON
fld e f i n e i N C L_NO P M
#d e fi n e I N C L_DOS P ROC E S S
I/d e f i n e I N C L_V I O
#i n c l u d e < o s 2 . h >
#i n c l u d e < p ro c e s s . h > / * _beg i nt h r ead , _en d t h r e a d * /
#i n c l u d e < s tddef . h > / * _t h r ea d i d */
#i n c l u d e < s t d l i b . h >
#i n c l u d e < c on i o . h >
v o i d ma i n ( )
{
PCHAR s ta c k :
CHAR ch = 'A' ;
/ * B o u n c e - T h r e a d t o c r e a t e a n d c o n t r o l a c o l o red l et t e r t h a t m o v e s
* a round o n t h e s c reen .
*
* P a rams : c h - t h e l et t e r t o be moved
*I
v o i d Boun c e ( i nt ch
(
/ * Gen e r a t e l et t e r a n d col o r a t t r i bute f rom t h re a d a rg ument . * /
char b l a n kc e l l [ 2 ] = ( 0x20 , 0x07 l :
char bl ockcel l [ 2 ] = ( c h , ( ch % 16> + 1 l :
i nt x o l d , x c u r , yol d , y c u r ;
BOO L f i r s t = T RU E :
_beginthread 106
/ * S e e d r a n d om n um b e r g e n e r a t o r a n d g e t i n i t i a l l o c a t i on . * /
s r a n d ( *_t h r e a d i d ) ;
x c u r - G e t Ra n d om ( 0 , vmi . c o l - 1 );
y c u r = Get Ra n d om < 0 , vmi . row - 1 l;
whi l e < repea t )
(
I * P a u s e b e t w e e n l oo p s . * /
DosSl eep ( 100L l ;
I * B l a n k o u t o u r o l d p o s i t i o n o n t h e s c reen , a n d d r aw n ew l e t t e r . * /
i f ( fi rst )
f i r s t .. FA L S E ;
el se
V i oWrt C e l l St r ( b l a n k c e l l , 2 , y o l d , x o l d , 0 ) ;
V i o W r t C e l l St r ( b l o c k c e l l , 2 , y c u r , x c u r , 0 ) ;
I * I n c rement t h e c o o rd i n a t e f o r n e x t p l a cement o f t h e b l o c k . * /
xol d = xcu r ;
yol d = yc u r ;
xcur += Get Ra n d om ( - 1 , 1 );
ycur += Get Random( - 1 , 1 l;
I * C o r r e c t p l a c ement < a n d b e e p ) i f a b o u t t o g o o f f t h e s c r e e n . * I
i f ( xcur < 0 )
xcur "' 1 ;
el se i f ( x c u r == v m i . c o l
xcur = vmi . col - 2 ;
el se i f ( ycur < 0 )
ycur = 1;
el se i f ( y c u r � v m i . row
ycur = v m i . row - 2 ;
I * I f n o t a t s c r e e n b o rd e r , c o n t i n u e , o t h e rw i s e b e e p . * /
e ls e
cont i nue ;
D o s B e e p ( ( c h - ' A ' l * 1 00 , 1 7 5 l ;
I * _e n d t h r e a d g i v e n ( b u t n o t r e a l l y n e e d ed ) to t e rm i n a t e . * /
_e n d t h r e a d ( ) ;
107 Bessel Functions
#include <math.h>
x Floating-point value
n Integer order
Remarks The jO, jl, and jn routines return Bessel functions of the first kind-orders 0, 1 , and n,
respectively.
The yO, yl, and yn routines return Bessel functions of the second kind-orders 0, 1 , and n,
respectively. The argument x must be positive.
The long double versions of these functions are the 80-bit counterparts and use the 80-bit,
1 0-byte coprocessor form of arguments and return values. See the reference page on the
long double functions for more details on this data type.
The Bessel functions are explained more fully in most mathematics reference books, such
as the Handbook ofMathematical Functions (Abramowitz and Stegun; Washington: U.S.
Government Printing Office, 1 964). These functions are commonly used in the mathemat
ics of electromagnetic wave theory.
Bessel Functions 108
For yO, yl, or yn, if x is negative, the routine sets errno to EDOM, prints a DOMAIN error
message to stderr, and returns -HUGE_VAL.
Error handling can be modified by using the matherr (or _matherrl) routine.
v o i d ma i n ( )
(
d o u b l e x = 2 . 387 ;
i nt n = 3, c;
Output
B e s s e l funct i on s f o r x = 2 . 387000 :
Ki nd Order Fun c t i on Re s u l t
Remarks The _bfreeseg function frees a based heap. The seg argument is a based heap returned by
an earlier call to _bheapseg. It specifies the based heap to be freed.
The number of bytes freed is the number of bytes specified when the block was allocated.
After the call, the freed heap is again available for allocation.
Return Value The _bfreeseg function returns 0 if successful and -1 in the case of an error.
See Also _bheapseg, calloc functions, free functions, malloc functions, realloc functions
/ * BH EAP S EG . C : T h i s p r o g r a m C i l l u s t ra t e s dynami c a l l oc a t i on of ba s ed
* memo ry u s i n g f u n c t i o n s _bh e a p s e g , _bf r ee s e g , _bma l l oc , a n d _bf ree .
*I
#i n c l u d e <stdi o . h>
#i n c l u d e <ma l l oc . h >
#i n c l u d e <stdl i b . h>
#i n c l u d e <stri ng . h>
v o i d ma i n ( )
(
_s egment s e g ;
c h a r _ba s e d ( s e g * ou t s t r , _ba s e d ( s e g *i nstr ;
c h a r _ba s e d ( s e g *pout , _b a s ed ( s e g *pi n ;
c h a r tmp s t r [ 80 ] ;
i nt l en ;
i f( C s e g • _b h e a p s e g ( 1 000 ) ) .... _N U L L S E G )
exi t ( 1 ) ;
I * A l l o c a t e ba s ed memo ry f o r two s t r i n g s . * /
II
l e n .. s t r l e n C tmp s t r ) ;
i f ( ( ( i n s t r .. _bma l l o c C s e g , J e n + 1 ) ) .... _N U L L O F F )
C C o u t s t r - _bma l l oc C s e g , l e n + 1 ) ) .... _NU L LO F F > )
exi t ( 1 ) ;
I * C o py a l ow e r c a s ed s t r i n g t o dy n a m i c memo ry . T h e b a s e d memo ry i s
* fa r w h e n a d d re s s ed a s a w h o l e .
*I
_f s t r l w r C _f s t rc py ( ( c h a r _fa r * ) i n s t r , ( c h a r _fa r * ) tmps t r ) ) ;
I * C o py i n p u t s t r i n g t o o u t p u t s t r i n g i n r e v e r s ed o r d e r . W h e n r e a d i n g
* a nd w r i t i n g i n d i v i d u a l c h a r a c t e r s f r om a ba s ed h e a p , t h e c om p i l e r w i l l
* t ry t o p r o c e s s t h em a s n ea r , t h u s s p e ed i n g u p t h e p r o c e s s i n g .
*I
fo r ( p i n i n s t r + l en - 1 , p o u � .. o u t s t r ;
m
I * D i s p l a y s t r i n g s . A g a i n s t r i n g s a s a w h o l e a r e fa r . * I
pri ntf( " I nput : SFs \ n " , ( c h a r _fa r * ) i n s t r ) ;
pri ntfC • output : SFs\ n " , ( c h a r _fa r * ) o u t s t r > ;
I * F r e e b l o c k s a n d r e l e a s e ba s ed h e a p . * /
_b f r ee C s e g , i n s t r > ;
_b f r ee C s e g , o u t s t r > ;
_b f r e e s e g C s eg > ;
Output
E n t e r a s t r i n g : Wa s I g o d
I nput : wa s i g o d
Output : dog i saw
_bheapseg 112
R1matb The _bheapseg function allocates a based-heap segment of at least size bytes. (The block
may be larger than size bytes because of space required for alignment and for maintenance
infonnation.)
The heap code will try to enlarge the heap as necessary. If the original block of memory is
depleted (e.g., by calls to _bmalloc and _brealloc), the run-time code will try to enlarge
the heap as necessary.
The value returned by _bheapseg is the identifier of the based-heap segment. This value
should be saved and used in subsequent calls to other based-heap functions.
The _bheapseg function can be called repeatedly. For each call, the C library will allocate
a new based-heap segment.
Return Value The _bheapseg function returns the newly allocated segment selector that the user must
save for use in subsequent based-heap functions. A return value of -1 indicates failure.
Always check the return from the _bheapseg function (especially when it is used in real
mode), even if the amount of memory requested is small.
S11 Also calloc functions, free functions, malloc functions, realloc functions
/ * B H E A P S E G . C : T h i s p r o g r a m C i l l u s t r a t e s dynami c a l l o c a t i on of b a s ed
* memory u s i n g funct i on s _b h e a p s e g , _bf r e e s eg , _bma l l oc , a nd _bf r e e .
*I
v o i d ma i n ( )
{
_s egment s e g ;
c h a r _ba sed ( s e g *out s t r , _ba sed ( s e g *i nstr ;
c h a r _ba sed ( s e g *pout , _ba sed ( s e g *pi n ;
c h a r tmp s t r [ 80 J ;
i n t l en ;
p r i n t f ( " En t e r a s t r i ng : " ) ;
g et s ( tmps t r ) ;
exi t ( l ) ;
exi t ( l ) ;
/ * C opy i n p u t s t r i n g t o output s t r i n g i n r e v e r s e d o r d e r . W h e n re a d i n g
* a nd w r i t i n g i n d i v i d u a l c h a r a c t e r s from a b a s ed h ea p , t h e c omp i l e r w i l l
* t ry t o p r o c e s s t h em a s nea r , t h u s speed i n g u p t h e p r o c es s i n g .
*I
fo r ( p i n = i n s t r + l en - l , p o u t = out s t r ;
pout < o u t s t r + l en ; p i n - - , pou t++ )
*pout = *pi n ;
*pout = ' \ 0 ' ;
I * D i s p l ay s t r i n g s . Ag a i n , s t r i n g s a s a w h o l e a re fa r . * /
p r i n t f ( " I n p u t : % Fs \ n " , ( c ha r _fa r * ) i n s t r ) ;
p r i n t f ( " O u t p u t : % F s \ n " , < c ha r _fa r * l ou t s t r ) ;
I * F ree b l o c k s a n d rel ea s e b a s ed h ea p . * /
_b free ( s e g , i n s t r ) ;
_b free ( s e g , o u t s t r ) ;
_bf r ee s eg ( s e g ) ;
_bheapseg 114
Output
E n t e r a s t r i n g : Wa s I god
I n put : wa s i god
Output : d o g i s a w
1 15 _bias_ disk
#include <bios.h>
Remalks The _bios_disk routine uses system call INT Ox l 3 to provide several disk-access func
tions. The service parameter selects the function desired, while the diskinfo structure pro
vides the necessary parameters. Note that the low-level disk operations allowed by the
_bios_disk routine are very dangerous to use because they allow direct manipulation of
the disk.
Element Description
unsigned drive Drive number
void far *buffer Memory location to write to, read from, or compare
The service argument can be set to one of the following manifest constants:
Constant Function
_DISK FORMAT
_ Formats the track specified by diskinfo. The head and track
fields indicate the track to format. Only one track can be for
matted in a single call. The biiffer field points to a set of sector
markers. The format of the marlcers depends on the type of
disk drive; see a technical reference to the PC BIOS to deter
mine the marlcer format. There is no return value.
_bias_ disk 116
DISK READ
_ _ Reads one or more disk sectors into memory. This service
uses all fields of the structure pointed to by diskinfo, as de
fined earlier in this section. If no error occurs, the function re
turns 0 in the high-order byte and the number of sectors read
in the low-order byte. If there is an error, the high-order byte
will contain a set of status flags. If there is an error, the high
order byte will contain a set of status flags, as defined under
_ DISK READ Status is returned in the 8 high-order bits of
_ .
Bits Meaning
_ DISK RESET Forces the disk controller to do a hard reset, preparing for
floppy-disk 1/0. This is useful after an error occurs in another
_
_DISK VERIFY
_ Checks the disk to be sure the specified sectors exist and can
be read. It also runs a CRC (cyclic redundancy check) test.
This service uses all fields (except buffer) of the structure
pointed to by diskinfo, as defined earlier in this section. If no
error occurs, the function returns 0 in the high-order byte and
the number of sectors compared in the low-order byte. If there
is an error, the high-order byte will contain a set of status
flags, as defined under _DISK READ
_ (above).
_DISK WRITE
_ Writes data from memory to one or more disk sectors. This
service uses all fields of the structure pointed to by diskinfo,
as defined earlier in this section. If no error occurs, the func
tion returns 0 in the high-order byte and the number of sectors
written in the low-order byte. If there is an error, the high
order byte will contain a set of status flags, as defined under
_ DISK READ
_ (above).
Retum Value The _bios_disk function returns the value in the AX register after the BIOS interrupt.
&• ��
����---
I * BD I S K . C : T h i s p r o g r a m f i r s t a t t empts to v e r i fy a d i s k by u s i ng a n
* i n v a l i d d i s k h e a d n umbe r . Aft e r p r i n t i ng t h e return v a l ue e r r o r code ,
* t h e p rog r a m v e r i fi es t h e d i s k by u s i n g a v a l i d d i s k h e a d code .
*I
#i n c l u d e < c o n i o . h >
#i n c l u d e < s t d i o . h>
#i n c l u d e < b i os . h >
v o i d ma i n ( )
(
u n s i gned s t a t u s = 0 ;
s t r uct d i s k i nfo_t d i s k_i n f o ;
d i s k_i n fo . d r i v e = 0;
d i s k_i nfo . h e a d = 10 ; / * I n v a l i d h e a d number * /
d i s k_i nfo . t ra c k = l;
d i s k_i nfo . s e c t o r 2;
d i s k_i nfo . n s e c t o r s = 8 ;
=
_bias_ disk 1 18
p r i n t f ( " I n s e rt d i s k i n d r i v e A : a n d p r e s s a ny k ey \ n " ) ;
getch ( ) ;
s t a t u s = _b i os_d i s k C _D I S K_V E R I FY , & d i s k_i nfo ) ;
p r i n t f ( " Re t u r n v a l u e : 0x% . 4x \ n " , s t a t u s ) ;
i f ( s t a t u s & 0xff00 ) / * E r r o r i f h i g h byte i s 0 * /
p r i n t f ( " Se e k e r r o r \ n " > :
el se
p r i n t f ( " No s e e k e r ro r \ n " > :
p r i n t f C " P re s s a ny k ey \ n " ) ;
getc h C ) ;
d i s k_i n f o . h e a d
= 0; / * V a l i d h e a d n umbe r * /
s t a t u s = _b i os_d i s k ( _D I S K_V E R I FY , & d i s k_i nfo > :
p r i n t f ( " Re t u r n v a l u e : 0x% . 4x \ n " , s t a t u s > :
i f ( s t a t u s & 0x ff00 ) / * E r r o r i f h i g h by te i s 0 * /
p r i n t f ( " Se e k e r ro r \ n " ) ;
el se
pri ntf ( " No seek error\ n " ) ;
Outpul
I n s e rt d i s k i n d r i v e A : a nd p r e s s a ny key
Ret u rn v a l u e : 0x0400
Seek e r r o r
P r e s s a ny k ey
Ret u rn v a l u e : 0x0008
No seek error
1 19 _bios_equiplist
Description Calls BIOS equipment-list service, using system call INT Oxl 1 .
#include <bios.h>
Remarks The _bios_equiplist routine uses system call INT Ox l l to determine what hardware and
peripherals are currently installed on the machine.
Return Value The function returns a set of bits indicating what is installed, as defined below:
Bits Meaning
I * B EOU I P L I . C : T h i s p r o g r a m c h e c k s f o r t h e p r e s e n c e of d i s kettes . * /
#i n c l u d e < b i o s . h >
#i n c l u d e < s t d i o . h >
_bios_equiplist 120
v o i d ma i n ( )
I
uns i gned e q u i pment ;
e q u i pment = _b i o s_e q u i p l i s t ( ) ;
p r i n t f ( " Eq u i pment b i t s : 0x% . 4x \ n " , e q u i pment ) ;
i f ( e q u i pment & 0x 1000 ) / * C h e c k f o r g a me a d a pt e r b i t * /
p r i n t f ( " Game a d a pt e r i n s t a l l ed \ n " l ;
el se
p r i n t f ( " N o g a me a d a p t e r i n s t a l l ed \ n " l ;
Output
E q u i pment b i t s : 0x40 6 1
N o g ame a d a pt e r i n s t a l l ed
121 _bios_keybrd
Remarks The _bios_keybrd routine uses system call INT Ox 1 6 to access the ke)'board services. The
service argument can be any of the following manifest constants:
Constant Meaning
_KEYBRD_READ, Reads the next character from the key
_NKEYBRD_READ board. If no character has been typed, the
call will wait for one. If the low-order
byte of the return value is nonzero, the
call contains the ASCII value of the char
acter typed. The high-order byte contains
the keyboard scan code for the character.
The NKEYBRD READ constant is used
withenhanced keyboards to obtain the
scan codes for function keys FI I and F12
and the cursor control keys.
_KEYBRD_READY, y
Checks whether a ke stroke is waiting to
_NKEYBRD_READY be read and, if so, reads it. The return
value is 0 if no keystroke is waiting, or it
is the character waiting to be read, in the
same format as the _KEYBRD_READ or
_NKEYBRD_READY return. This service
does not remove the waiting character
from the input buffer, as does the
_KEYBRD_READ or _NKEYBRD_READ
service. The NKEYBRD READY con
stant is used ;ith enhanc ed keyboards to
obtain the scan codes for function keys Fl I
and FI2 and the cursor control keys.
_bios_keybrd 122
Return Value With the ""READ and SHIFrSTATUS arguments, the _bios_keybrd function returns the
•••
I* B K EY B RD . C : T h i s p r o g r a m p r i n t s a mes s a ge on t h e s c reen u n t i l t h e
* r i g h t S H I FT k ey i s p res s ed .
*I
#i n c l u d e < b i os . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n { )
(
w h i l e { ! { _b i os_keyb rd { _KEY BRD_S H I FTSTATUS ) & 000 1 ) )
p r i n t f { " U s e t h e r i g h t SH I FT k ey to stop t h i s mes s a g e \ n " ) ;
p r i n t f { " Ri g h t SH I FT k ey pres s ed \ n " > :
Output
Description Calls the BIOS memory-size service, using system call INT Ox1 2.
#include <bios.h>
Rematts The _bios_memsize routine uses system call INT Ox 1 2 to detennine the total amount of
main memory installed.
Return Value The routine returns the total amount of installed memory in lK blocks. The maximum re
turn value is 640, representing 640K of main memory.
#i n c l u d e < b i o s . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
(
u n s i g n e d memo ry ;
memo ry = _b i os_mems i z e C ) :
p r i n t f C " T h e amount of memo ry i n st a l l ed i s : % d K \ n " , memory l;
Output
T h e amount o f memo ry i n s t a l l ed i s : 6 3 9 K
125 _bias_printer
#include <bios.h>
Remarks The _bios_printer routine uses system call INT Ox 17 to perfonn printer output services
for parallel printers. The printer argument specifies the affected printer, where 0 is LPT l ,
1 i s LPT2 , and s o forth.
Some printers do not support the full set of signals. As a result, the "Out of Paper" condi
tion, for example, may not be returned to your program.
The service argument can be any of the following manifest constants:
Constant Meaning
_PRINTER_INIT Initializes the selected printer. The data argument is ignored.
The return value is the low-order status byte defined below.
_PRINTER_STATUS Returns the printer status in the low-order status byte defined
below. The data argument is ignored.
_PRINTER_WRITE Sends the low-order byte of data to the printer specified by
printer. The low-order byte of the return value indicates the
printer status after the operation, as defined below:
R11tum Value The _bios_printer function returns the value in the AX register after the BIOS interrupt.
Exampm �����
/ * B P R I N T E R . C : T h i s p r o g r a m c h e c k s t h e s t a t u s of t h e p r i n t e r a t t a c Hed t o
* L P T l w h e n i t i s off l i ne , t h e n i n i t i a l i z es t h e p r i n t e r .
*/
#i n c l u d e < b i o s . h >
#i n c l u d e < c o n i o . h >
#i n c l u d e < s t d i o . h >
/ld efi n e L P T l 0
v o i d ma i n ( )
(
uns i gned status ;
s t a t u s = _b i o s_p r i n t e r C _P R I NT E R_I N I T , L P T l , 0 ) ;
p r i n t f ( " St a t u s a f t e r p r i n t e r i n i t i a l i z ed : 0x% . 4x \ n " , s t a t u s > :
Output
P l a c e p r i n t e r off l i n e a nd p r e s s a ny k ey
S t a t u s w i t h p r i n t e r off l i n e : 0x00 1 8
P u t t h e p r i n t e r on l i n e a n d t h e n
P r e s s a ny k ey to i n i t i a l i ze p r i n t e r
S t a t u s a ft e r p r i n t e r i n i t i a l i z ed : 0x0090
127 _bios_serialcom
Daer/pt/an Calls BIOS communications services, using system call INT Ox1 4.
#include <bios.h>
Remades The _bios_serialcom routine uses system call INT Ox14 to provide serial communications
. services. The serial_port argument is set to 0 for COM l , to 1 for COM2, and so on.
The _bios_serialcom routine may not be able to establish reliable communications at baud
rates in excess of 1 ,200 baud ( _COM_1200) due to the overhead associated with servicing
computer interrupts. Faster data communication rates are possible with more direct pro
gramming of serial-port controllers. See C Programmer's Guide to Serial Communications
for more details on serial-communications programming in C.
The service argument can be set to one of the following manifest constants:
Constant Service
_COM_INIT Sets the port to the parameters specified in the data argument
_COM_SEND Transmits the data characters over the selected serial port
_COM_RECEIVE Accepts an input character from the selected serial port
_COM_STATUS Returns the current status of the selected serial port
Constant Meaning
_COM_CHR7 7 data bits
_COM_CHR8 8 data bits
_COM_STOPl 1 stop bit
_COM_STOP2 2 stop bits
_COM_NOPARITY No parity
_bios_serialcom 128
Return Value The function returns a 1 6-bit integer whose high-order byte contains status bits. The mean
ing of the low-order byte varies, depending on the service value. The high-order bits have
the following meanings:
15 Timed out
14 Transmission-shift register empty
13 Transmission-hold register empty
12 Break detected
11 Framing error
10 Parity error
9 Overrun error
8 Data ready
When service is _COM_SEND, bit 15 will be set if data could not be sent.
When service is _COM_RECEIVE, the byte read will be returned in the low-order bits if
the call is successful. If an error occurs, any of the bits 9, 10, 1 1 , or 15 will be set.
129 _bias_ssrialcam
When service is -COM-INIT or -COM -STATUS, the low-order bits are defined as
follows:
Note that this function works only with IBM personal computers and true compatibles.
I* B S E R I A LC . C : T h i s p r o g r a m c h e c k s t h e s t a t u s of s e r i a l p o r t COM l . * /
#i n c l u d e < b i o s . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
I
u n s i gned c oml_s ta t u s ;
Output
C O M l s t a t u s : 0x6000
130
D•t:rlptlon Calls BIOS time and date services, using system call INT Ox lA.
#include <bios.h>
Rematb The _bios_timeofday routine uses system call INT OxlA to get or set the clock count. The
service argument can be either of the following manifest constants:
Constant Meaning
_TIME_GETCLOCK Copies the current value of the clock count to the location
pointed to by timeval. If midnight has not passed since the last
time the system clock was read or set, the function returns O;
otherwise, the function returns 1 .
_TIME_SETCLOCK Sets the current value of the system clock to the value in the
location pointed to by timeval. There is no return value.
Rllum Value The _bios_timeofday function returns the value in the AX register after the BIOS
interrupt.
I
i
Exampm �-+-����---
1 * BT I M EO F D lC: T h i s p r o g r a m g e t s t h e c u r rent sys tem c l o c k count before a n d a ft e r
* a "do-no yhi ng• l oop a n d d i s p l a y s t h e d i fference .
*I
i
I
i
v o i d ma i n { )
(
l ong i , b e g i n_t i c k , end _t i c k ;
fo r { i = l ; i <= 900000 ; i ++ )
p r i n t f { " Be g i n n i ng t i c k count : %l u \ n " , b e g i n_t i c k ) ;
tlutput
B e g i n n i ng t i c k count : 1 1 1 4 2 5 5
E nd i n g t i c k c o u n t : 1 1 14287
E l a ps ed t i c k s : 32
bsean:hl 132
Remarks The bsearch function perfonns a binary search of a sorted array of num elements, each of
width bytes in size. The base value is a pointer to the base of the array to be searched, and
key is the value being sought.
The compare argument is a pointer to a user-supplied routine that compares two array ele
compare routine one or more times during the search, passing pointers to two array ele
ments and returns a value specifying their relationship. The bsearch function calls the
ments on each call. The routine compares the elements, then returns one of the following
values:
Value Meaning
If the array you are searching is not in ascending sort order, bsearch does not work prop
erly. If the array contains duplicate records with identical keys, there is no way to predict
which of the duplicate records will be located by bsearch.
Return Va/us The bsearch function returns a pointer to the first occurrence of key in the array pointCd to
by base. If key is not found, the function returns NULL.
133 bsearch
#i n c l u d e < s e a r c h . h >
#i n c l ude < s t r i n g . h >
#i n c l ude < s t d i o . h > ·
v o i d ma i n ( i n t a r gc , c h a r * * a r g v }
(
cha r **resul t ;
c h a r * k ey = " c a t " ;
i nt i ;
I * Sort u s i n g Q u i c k s o rt a l g o r i t hm : * /
q s o rt ( ( c h a r * } a rg v , a rg c , s i z eo f ( c h a r * } , c omp a re > :
I * Fi n d t h e word • c a t • u s i n g a b i n a ry s e a r c h a l g o r i t hm : * /
res u l t = C c h a r ** ) b s e a rc h C ( c h a r * ) & k ey , ( c h a r * ) a rg v , a r gc ,
s i zeof C c ha r * } , c ompa re > :
i f ( res u l t >
p r i n t f C " \ n%s foun d a t % F p \ n " , * r e s u l t , r e s u l t > :
el se
p r i n t f ( " \ n C a t n o t found ! \ n " > :
Output
[ C : \ L I BR E F J b s e a r c h d o g p i g h o r s e c a t h uma n r a t c ow goa t
b s e a r c h c a t c ow dog g o a t h o r s e h uma n p i g r a t
c a t f o u n d a t 0 2 9 2 : 0 FD0
I
cabs, ca sl fI
134
#include <math.h>
. z Complex number
Remarks The cabs and cabsl functions calculate the absolute value of a complex number, which
must be a structure of type complex (or _complexl). The structure z is composed of a real
component x and an imaginary component y. A call to one of the cabs routines is equiv
alent to the following:
The cabsl function is the 80-bit counterpart and it uses the 80-bit, 10-byte coprocessor
form of arguments and return values. See the reference page on the long double functions
for more details on this data type.
Return Value On overflow, these functions call matherr or _matherrl, return HUGE_VAL, and set
ermo to ERANGE.
Campallblllly cabs
cabsl
Exampm �-+����������������������������---
�
1 * CABS . C : U i n g c a b s , t h i s p r o g r a m c a l c u l a t e s t h e a b s o l ute va l u e of
* a c omp l e�. n umber .
*/
I
#i n c l ude <ma t h . h >
#i n c l ude < s t � i o . h >
135 cabs, cabs/
v o i d ma i n ( )
(
s t r uct c omp l ex n umbe r = ( 3 . 0 , 4 . 0 J ;
doubl e d ;
d = c a b s ( number ) ;
p r i n t f ( " T h e a b s o l u t e v a l ue o f % f + %fi i s % f \ n " ,
n umbe r . x , n umbe r . y , d ) ;
Output
136
I
Daer/pt/an I Allocate an array in memory with elements initialized to 0.
I
I
Remarks The calloc family of functions allocates storage space for an array of num elements, each
of length size bytes. Each element is initialized to 0.
In large data models (compact-, large-, and huge-model programs), calloc maps to
_fcalloc. In small data models (tiny-, small-, and medium-model programs), calloc maps
to _ncalloc.
The various calloc functions allocate storage space in the data segments shown in the list
below:
Function Data Segment
calloc Depends on data model of program
_bcalloc Based heap, specified by seg segment selector
fcalloc Far heap (outside default data segment)
_ncalloc Near heap (inside default data segment)
Return Value The calloc functions return a pointer to the allocated space. The storage space pointed to
by the return value is guaranteed to be suitably aligned for storage of any type of object.
To get a pointer to a type other than void, use a type cast on the return value.
The _fcalloc and _ncalloc functions return NULL if there is insufficient memory available
or if num or size is 0. The _bcalloc function returns _NULLOFF in this case.
137 ca/lac Functions
Compatibility canoe
See Also free functions, halloc, hfree, malloc functions, realloc functions
I * C A L LOC . C : T h i s p r o g r a m u s e s c a l J oc t o a l l o c a t e s p a c e f o r 40 l on g i n t e g e r s .
* I t i n i t i a l i z e s ea c h e l eme n t t o z e ro .
*/
#i n c l u d e < s t d i o . h >
#i n c l u d e <ma l l oc . h >
v o i d ma i n ( )
(
l on g *buffe r ;
b u f f e r = ( l o n g * ) c a l l oc C 40 , s i zeof ( l on g ) > :
i f ( buffer ! = N U L L )
p r i n t f C " A l l o c a t ed 40 l ong i n t e g e r s \ n " > :
el s e
p r i n t f ( " Ca n ' t a l l o c a t e memo ry \ n " ) ;
free ( buffer > :
Output
Al l o c a ted 40 l on g i nt e g e r s
ceil, ce if 138
I
I
#include <math.h>
x Floating-point value
Remarks The ceil and ceill functions return a double (or long double) value representing the
smallest integer that is greater than or equal to x.
The ceill function is the 80-bit counterpart and it uses the 80-bit, 1 0-byte coprocessor fonn
of arguments and return values. See the reference page on the long double functions for
more details on this data type.
Relum Value These functions return the double or long double result. There is no error return.
Campallblllly ceil
ceill
Examp� �-+------
1
I * F LOOR . C : T h i s examp l e d i s p l a y s t h e l a rg e s t i n t e g e r s l es s t h a n o r equa l
* t o t h e f o a t i n g - po i n t v a l ues 2 . 8 a nd - 2 . 8 . I t t h e n s h ows t h e sma l l e s t
* i n t e g e r s g r e a t e r t h a n o r e q u a l t o 2 . 8 and - 2 . 8 .
I
*I I
!
I
139 ceil, ceill
v o i d ma i n ( )
{
doubl e y;
y = fl oo r ( 2 . 8 ) ;
p r i n t f ( " T h e fl o o r of 2 . 8 i s %f\ n " , y ) ;
y = fl o o r ( - 2 . 8 ) ;
p r i n t f { " Th e f l o o r o f - 2 . 8 i s % f \ n " , y ) ;
y = cei l ( 2.8 l ;
pri ntf ( "The cei l of 2 . 8 i s %f\ n " , y ) ;
y = cei l ( -2 . 8 ) ;
pri ntf ( "The cei l of - 2 . 8 i s %f\ n " , y ) ;
Output
Description Perform clean-up operations and return without terminating the process.
#include <process.h>
Remarks The _cexit function calls, in LIFO ("last in, first out") order, the functions registered by
atexit and onexit. Then the _cexit function flushes all 1/0 buffers and closes all open files
·
before returning.
The _c_exit function returns to the calling process without processing atexit or onexit
functions or flushing stream buffers.
The behavior of the exit, -exit, -cexit, and -c-exit functions is described in the following
list:
Function Action
exit Performs complete C library termination procedures, termi
nates the process, and exits with the supplied status code
_exit Performs "quick" C library termination procedures, terminates
the process, and exits with the supplied status code
_cexit Performs complete C library termination procedures and re
turns to caller, but does not terminate the process
_c_exit Performs "quick" C library termination procedures and re
turns to caller, but does not terminate the process
See Also abort, atexit, exec functions, exit, onexit, spawn functions, system
141 cgets
Remarks The cgets function reads a string of characters directly from the console and stores the
string and its length in the location pointed to by buffer. The buffer argument must be a
pointer to a character array. The first element of the array, buffer[O] , must contain the maxi
mum length (in characters) of the string to be read. The array must contain enough ele
ments to hold the string, a terminating null character ( '\0 ' ) , and two additional bytes.
The cgets function continues to read characters until a carriage-return-line-feed (CR-LF)
combination is read, or the specified number of characters is read. The string is stored
starting at str[2]. If a CR-LF combination is read, it is replaced with a null character ('\0')
before being stored. The cgets function then stores the actual length of the string in the sec
ond array element, buffer[ I ] .
Because all DOS editing keys are active when you call cgets, pressing F3 repeats the last
entry.
Return Value The cgets function returns a pointer to the start of the string, at buffer[2]. There is no error
return.
I * CGETS . C : T h i s p r o g r a m c r e a t e s a b u f f e r a n d i n i t i a l i z es t h e f i r s t by t e
* t o t h e s i z e of t h e b u f f e r - 2 . Next , t h e p r o g r a m a c c e p t s a n i n p u t s t r i n g
* u s i n g c g e t s a n d d i s p l a y s t h e s i z e a n d t e x t of t h a t s t r i n g .
*I
i
v o i d ma i n { )
{ I
r
char bufff r [82] = { 80 J ; / * M a x i mum c h a r a c t e r s i n f i r s t by t e * /
char *res l t ;
· t nput
l
p r i ntf ( l i n e of text , fol l owed by c a r r i a g e r e t u r n : \ n " ) ;
r e s u l t = f g et s ( b u f f e r ) ; / * I np u t a l i n e of text * /
p r i n t f ( " n l i ne l e n g t h = %d\ nText = % s \ n " , buffe r [ l ] , res u l t ) ;
t
Output ;
L i n e l en g t h 17t
T h i s i s s ome t e x t
j
T e x t = T h i s s s ome t ext
143 _chain_intr
#include <dos.h>
Remarks The _chain_intr routine passes control from one interrupt handler to another. The stack
and the registers of the first routine are passed to the second, allowing the second routine
to return as if it had been called directly.
The _chain_intr routine is generally used when a user-defined interrupt handler begins
processing, then chains to the original interrupt handler to finish proces�ing.
Chaining is one of two techniques, listed below, that can be used to transfer control from a
new interrupt routine to an old one:
1. Call _chain_intr with the interrupt routine as an argument. Do this if your routine is
fmished and you want the second interrupt routine to terminate the interrupt call.
++_d i ; / * I n i t i a l p r o c es s i ng h e r e * /
_c h a i n_i n t r ( ol d_i nt l ; / * N ew D I pa s s ed t o o l d_i n t * /
- -_d i ; / * T h i s i s n e v e r e x e c u t ed */
2 . Call the interrupt routine (after casting it to an interrupt function if necessary). Do this
if you need to do further processing after the second interrupt routine finishes.
++_d i ; I* I n i t i a l proces s i ng h e r e */
( * o l d_i nt l ( ) ; I * N ew D I pa s s ed t o ol d_i nt */
_a s m mov _d i , d i I * P u t rea l D I f rom o l d_i nt */
I* i n t o _d i f o r r e t u r n */
Note that the real registers set by the old interrupt function are not automatically set to the
pseudoregisters of the new routine.
_chain_f'' 144
Use the _chain_intr function when you do not want to replace the default interrupt han
dler, but you do need to see its input. An example is a TSR (terminate-and-stay-resident)
program that checks all keyboard input for a particular "hot key" sequence.
The _chain_intr function should be used only with C functions that have been declared
with type _interrupt. The _interrupt declaration ensures that the procedure's entry/exit
sequence is appropriate for an interrupt handler.
Return Value The _chain_intr function does not return to the caller.
I
Compatlb/llty 0 ANSI • DOS 0 OS/2 0 UNIX 0 XEN IX
Remarks The chdir function changes the current working directory to the directory specified by
dirname. The dirname argument must refer to an existing directory.
This function can change the current working directory on any drive; it cannot be used to
change the default drive itself. For example, if A: is the default drive and \BIN is the
current working directory, the following call changes the current working directory for
drive C:
c h d i r ( " c : \ \ t emp " ) ;
Notice that you must place two backslashes ( \\ ) in a C string in order to represent a single
backslash ( \ ) ; the backslash is the escape character for C strings and therefore requires
special handling.
This function call has no apparent immediate effect. However, when the _chdrive function
is called to change the default drive to C:, the current working directory becomes
C:\TEMP.
In OS/2 protected mode, the current working directory is local to a process rather than
system-wide. When a process terminates, the current working directory is restored to its
original value. Under DOS, the new directory set by the program becomes the new current
working directory.
Return Value The chdir function returns a value of 0 if the working directory is successfully changed. A
return value of -1 indicates an error, in which case errno is set to ENOENT, indicating
that the specified path name could not be found.
I * CHGD I R . 9 : T h i s p r o g r a m u s e s t h e c h d i r f u n c t i on to v e r i fy t h a t a
l
v o i d ma i n { 1 n t a rg c , c h a r *a rgv [ J )
i f { c h d il r c
( I
p r i n �f (
a rg v [ l ] > )
" Un a b l e t o l oc a t e t h e d i rec t o ry : % s \ n " , a rg v [ l ] l ;
I
s y s t �m C " d i r * . c • > :
el se
I
i
I
I
Output
[C : \ LI BREF � c h g d i r \ tmp
I
i
Remarks The _chdrive function changes the current working drive to the drive specified by drive.
The drive argument uses an integer to specify the new working drive ( l =A, 2=B, etc.).
This function changes only the working drive; the chdir function changes the working
directory.
In OS/2 protected mode, the working drive is local to a process rather than system-wide.
When a process terminates, the working drive is restored to its original value. Under DOS,
the new drive set by the program becomes the new working drive.
Return Value The _chdrive function returns a value of 0 if the working drive is successfully changed. A
return value of - 1 indicates an error.
See Also chdir, _dos_setdrive, _fullpath, _getcwd, _getdrive, mkdir, rmdir, system
I * GETD R I V E . C i l l u s t r a t e s d r i ve f u n c t i on s i n c l ud i n g :
* _g etd r i v e _c h d r i v e _g etd cwd
*I
v o i d ma i n ( ) i
( i
i n t c h , d r i v e , c u rd r i v e ;
�
s t a t i c c a r p a t h [_MAX_PATH J ;
I
I * S a v e � u r rent d r i v e . * /
c u rd r i v e l = _g etd r i v e ( ) ;
i >;
ti
printfC Av a i l a b l e d r i ves a re : \ n "
I * I f we c a n swi t c h t o t h e d r i v e , i t exi s t s . * /
for( dri e = 1 ; d r i v e < = 2 6 ; d r i ve++ )
i f( ! chdri veC dri ve ) l
pr n t f ( " %c : • , d r i v e + ' A ' - 1 > ;
whi l e( 1 I )
1 �
,
p r i n t ( " \ nTy pe d r i v e l et t e r t o c h e c k o r ESC t o q u i t : • );
c h = �etch ( ) ;
i f ( c � == 27 )
br a k ;
i f ( i a l pha ( c h > l
pu c h ( ch l ;
i f ( - 1 etd cwd ( t o u p pe r ( c h ) - ' A ' + 1 , pa t h , _MAX_PATH ) ! = N U L L
p r l n t f ( " \ n C u r r e n t d i r e c t o ry o n t h a t d r i v e i s % s \ n " , p a t h ) ;
t
* t h e c � rrent d r i v e of t h e c a l l i n g p r o c e s s i s a l ways restored .
/ * Res t o e o r i g i n a l d r i ve . T h i s i s on l y n e c e s s a ry f o r DOS . U n d e r O S / 2
I
_c hd r i v e \ c u r d r i ve ) ;
*I
printf( i \n" ) ;
I
°"""'
Av a i l a b l e d f i v e s a r e :
A: B: C: I
Type d r i v e J e t t e r t o c h e c k o r E S C t o q u i t : q
Ty p e d r i v e 1 e t t e r t o c h e c k or ESC t o q u i t : a
C u r r ent d i r�c t o ry on t h a t d r i v e i s A : \
I
Type d r i v e � e t t e r t o c h e c k o r ESC to q u i t : c
C u r rent d i r r c t o ry on t h a t d r i v e i s C : \ L I B R E F
#include <Sys\types.h>
#include <Sys\stat.h>
#include <errno.h>
#include <io.h> Required only for function declarations
Rematks The chmod function changes the pennission setting of the file specified by filename. The
pennission setting controls read and write access to the file. The constant expression
pmode contains one or both of the manifest constants S_IWRITE and S_IREAD, defined in
SYS\STAT.H. Any other values for pmode are ignored. When both constants are given,
they are joined with the bitwise-OR operator ( I ) . The meaning of the pmode argument is
as follows:
Value Meaning
S_IWRITE Writing pennitted
If write pennission is not given, the file is read-only. Under DOS and OS/2, all files are
readable; it is not possible to give write-only pennission. Thus the modes S_IWRITE and
S_IREAD I S_IWRITE are equivalent
Rllllrl n Value The chmod function returns the value 0 if the pennission setting is successfully changed.
A return value of -1 indicates an error; in this case, ermo is set to ENOENT, indicating
that the specified file could not be found.
ch mod 150
I*I** CHMOD.
read-on�C�, yThis. I t progra then attem usmeptss chtomodmodito fychangethe filthee . mode of a file to
#i#i#i nnnclude
clude
i
<
< �ys\tys\sytpes.at . h>h>
#i#i nnclude
clude
clude <"o.
<�t
<Ftdli d h >
io. b h. >h>
voi dI*maiMaken ( �j·) file read-onl y : */
I
S_IREAD ); )
sIy*spritChan�e
emnc tf(l • echoback" Mode/*tochange
Enread ofd/dwfileritote:read-o
*/*/ nCHMDD.
l y \n" C);"
) � -1
if(elseperrorC
chmpdC ""FCHMOD.i le notC ", found\n" S_IWRITE )
» >:
:
#include <errno.h>
Rematks The chsize function extends or truncates the file associated with handle to the length
specified by size. The file must be open in a mode that pennits writing. Null characters
('\0') are appended if the file is extended. If the file is truncated, all data from the end of
the shortened file to the original length of the file is lost.
In DOS, the directory update is done when a file is closed. Consequently, while a program
is running, requests to detennine the amount of free disk space may receive inaccurate
results.
Retum Value The chsize function returns the value 0 if the file size is successfully changed. A return
value of -1 indicates an error, and ermo is set to one of the following values:
Value Meaning
EACCES Specified file is locked against access (OS/2 and DOS
versions 3.0 and later only).
fi l e beforeThisandprogra
I * CHS I ZE . C :
*
*I
aftermmodiusesfyfii ngl eli tengthwi thtochsirezpore. t the si ze of a
chsize
clude
clude
clude
I
<f�ntl.
<s
<s �
� s\
s\sta t y h >
pes.
t . h h
> >
#ivoindcludemai n<s�di() o . h>
I
I
�
1 I I
I* */
priclose(prntl1 nC fhtf("File);"Prolength
blem inafchangi
ter: n%lgdthe\n ", sifilelengthC
ze\n " fh ) );
329678 > == 0 >
I
> :
length �fter: I
0
329678
153 _clear87
#include <float.h>
Remarks The _clear87 function gets and clears the floating-point status word. The floating-point sta
tus word is a combination of the 8087 /80287 status word and other conditions detected by
the 8087/80287 exception handler, such as floating-point stack overflow and underflow.
Retum Value The bits in the value returned indicate the floating-point status. See the FLOAT.ff include
file for a complete definition of the bits returned by _clear87.
Many of the math library functions modify the 8087/80287 status word, with unpredict
floating-point operations are perfurmed between known states of the floating-point status
able results. Return values from clear87 and status87 become more reliable as fewer
word.
I*
thenCLEAR8us7.eCs :_clear
This 8progra7 to mreporcreatteson thesvari eousprofloatiblems.ng-point probl ems,
#i#ivoinndclude
clude <stdi<floaot .. hh>>
*
*/
( doublfloatmain()ex,a = le-40, b;
pri Store
ntf( " Si tatus:
y;
/*
Y
y
underflow\n", _clear87()
*/
> :
i s 1 enor m al:
154
i
.
!
*/
Status:
StaStattus:us: --- denor
Output
00�0
00�0
00�2
clear
i nexact,mal underflow
I
I
155 clearerr
#include <Stdio.h>
indicator8 are not automatically cleared; once the error indicator for a specified stream is
Rematlls The clearerr function resets the error indicator and end-of-file indicator for stream. Error
set, operations on that stream continue to return an error value until clearerr, fseek,
fsetpos, or rewind is called.
I* � */
�
n
11 ) ;
n
l l
(
�
I
l ;
� l ;
I
I
I
I
#include <graph.h>
Remarks The _clearscreen function erases the target area, filling it with the current background
color. The area parameter can be one of the following manifest constants (defined in
GRAPH.H):
Constant Action
_GCLEARSCREEN Oears and fills the entire screen
_GVIEWPORT Clears and fills only within the current view port
_GWINDOW Oears and fills only within the current text window
#i#i#i nnnclude
clude <coni o . h >
Exampm ������-
clude <gra
<s t
1 * C L RSC RN . C * /
p
dlih.b h
. >
h >
voi( dshormain()t xhalf, yhalf, xquar, yquar;
struct vi deoconfi g vc;
158
I*
i f(
Fiexi! _ndtse�vi( valideomdode(graphicsMA REmode.MODE
� *I
f
yhalf yc. n u m y pi x els
>:
xquar fhalf
.
I
= y
yquar half
I
=
2;
1
I
=
r
2;
_setvi e w
_r_elecl ti angpse eCort(GF_GBLLIORDTERIER,xhalxhalfORf xquar
- xhyhala lf f- yquar
- yhalf -
I
=
2;
r
I 2;
getchCl;
0, 0, 1, 1 >:
r
_setvi de�mode( _DEFAULTMODE
>:
l
I
l :
) ;
I
159 clock
#include <time.h>
Rematks The clock function tells how much processor time has been used by the calling process.
The time in seconds is approximated by dividing the clock return value by the value of the
CLOCKS_PER_SEC constant.
In other words, the clock function returns the number of processor timer ticks that have
elapsed. A timer tick is approximately equal to 1/CLOCKS_PER_SEC seconds.
Return Value The clock function returns the product of the time in seconds and the value of the
CLOCKS_PER_SEC constant. If the processor time is not available, the function returns
the value - I , cast as clock_t.
In both DOS and OS/2, clock returns the time elapsed since the process started. This may
not be equal to the actual processor time used by the process.
clock_t durati
double start , on;fi n i s h;
= 600000 L :
clock
durprifi nnaishtitf(o=nr=%clock();
2.C dlouble) ( finish dur- starati ton) ); CLOCK·S_PER_SEC ;
f seconds\n", I
�00000
i
I
I
161 close
#include <errno.h>
Rematics The close function closes the file associated with handle.
Return Value The close function returns 0 if the file was successfully closed. A return value of -1 indi
cates an error, and ermo is set to EBADF, indicating an invalid file-handle argument.
I**I* OPEN.and aCfile: Thisnamprograed OPEN.m usOeUTs openfor output. to openTha efilefilesnamarede OPEN.then Cclosfored.input
#i#i#i nnnclude
clude
clude <fcntl.
<s
<s y
y s\
s\sta t y h >
pes.
t . h h
> >
#i/voii nnclude
clude <io. h> h>
<stdio.
dintmaifhl,n () fh2 :
{
f h 2 = ope p ( " O P E N . OUT " , O_WRON LY I O_C R EAT , S_I READ I S_I W R I T E l :
i f < f h 2 =r - 1 >
p e r r o r ( " open fa i l ed on output f i l e " l :
el se
(
l :
cl ose< I fh2 l :
p r i n t f � " open s u c c eeded on output fi l e \ n "
I
Output
i
I
�
open s u c c e ed e d on i np u t f i l e
open s uc c e e d d o n o u t p � t f i l e
163 _contro/87
#include <float.h>
Remalb The _control87 function gets and sets the floating-point control word. The floating-point
control word allows the program to change the precision, rounding, and infinity modes in
the floating-point-math package. Floating-point exceptions can also be masked or un
masked using the _control87 function.
If the value for mask is equal to 0, then control87 gets the floating-point control word. If
mask is nonzero, then a new value for the control word is set in the following manner: for
fpcntrl C C fpcntri I C n ew
any bit that is on (equal to 1 ) in mask, the corresponding bit in new is used to update the
control word. To put it another way,
The possible values for the mask constant (mask) and new control values (new) are shown
in Table R. 1 .
MCW_EM Ox003F
(lntelTUpt
exception)
EM_INVALID OxOOOl
EM_DENORMAL Ox0002
EM_ZERODIVIDE Ox0004
EM_OVERFLOW Ox0008
EM_UNDERFLOW OxOO I O
EM_INEXACT Ox0020
I
_control,, II
164
I
1 Table R.1 (co11ti11ued)
MCW_IC Ox l OOO
(Infinity
contml)
IC_AFFiNE Ox l OOO
IC_PROJECTIVE OxOOOO
MCW_RC OxOCOO
(Rounding
control)
RC_CHOP OxOCOO
RC_UP Ox0800
RC_DOWN Ox0400
RC_NEAR OxOOOO
MCW_PC Ox0300
(Precision
control)
PC_24 (24 bits) OxOOOO
PC_S3 (53 bits) Ox0200
PC_64 (64 bits) Ox0300
i
Return Value
I
l The bits in the value returned indicate the floating-point control state. See the FLOAT.H
I
include file for a complete definition of the bits returned by _control87.
I
Campal/blllty i
I
D ANSI 8 DOS • OS/2 D U N IX D XENIX
Exampm
1* CNseTtRLthe87. recisi
----����-
�
f
: Thisoprogra n to m biusetss,_canodntrroels8et7 totheoutputstatustheto thcontrole defaulwortd. ,
//ttii ncncl udeude <s<f dioaot .. hh>>
* 24
*I ,
!
1 t
)
I
t
I I
!
_contro/87
t* : %1.0x%.lfand4x\%.nre1",calcula
pripriI* nnRetf(tf(store"" %Defaul1.tolfdefault
=
=
t e. */
5e\n", a, a,7( aCW*_aDEF);AULT , 0xffff ) );
_contr o l 8
0.0.Ori24-11gb**it:i n0.0.al:11 0x10x19.1.3303293200000000000000e- 0 02
Output
Default:
=
0x1
0. 1 * 0. 1 1. 000000000000000e-002
=
=
0 32 999997764825 8 2e- 0 03
cos Funct ans f 166
Description Calculate the cosine (cos and cosl) or hyperbolic cosine (cosh and coshl).
#include <math.h>
x Angle in radians
Remarks The cos and cosh functions return the cosine and hyperbolic cosine, respectively, of x.
The cosl and coshl functions are the 80-bit counterparts and use the 80-bit, 10-byte co
processor fonn of arguments and return values. See the reference page on the long double
functions for more details on this data type.
Return Value If x is large, a partial loss of significance in the result may occur in a call to cos, in which
case the function generates a PLOSS error. If x is so large that significance is completely
lost, cos prints a TLOSS message to stderr and returns 0. In both cases, errno is set to
ERANGE.
If the result is too large in a cosh call, the function returns HUGE_VAL and sets errno to
ERANGE.
cosl, coshl
S1111 Alsa acos functions, asin functions, atan functions, matherr, sin functions, tan functions
I*I** and hyperbThisolic cosiprogranemofdi pisplaIy2.s the si ne, hyperboli c si ne, cosi ne,
S I N C OS . C :
#i#i nnclude
clude <<smath.tdi oh. >h>
voi( ddoublemai n ()pi = 3. 1415926535;
double x, y;
yyxpri===npisisitf(nnIhC( " xs2;xi n);(>: %f ) = %f\n", x, y );
pripri nntf(tf( "• scos(i n) h( %f%f ) )==%f\n"%f\n",, x,x , yy );>:
ypri=ncoshCtf( "cxosh(>: %f > = %f\n " , x , y >;
Y = COS ( X ;
COS ( 00000
cprintf 168
Remarks The cprintf function formats and prints a series of characters and values directly to the
console, using the putch function to output characters. Each argument (if any) is con
verted and output according to the corresponding format specification informat. The for
mat has the same form and function as theformat argument for the printf function; see
printf for a description of the format and arguments.
Note that unlike the fprintf, printf, and sprintf functions, cprintf does not translate line
feed characters into carriage-return-line-feed combinations on output.
Return Value The cprintf function returns the number of characters printed.
CPRI N TF.
#ivoindcludemai n<c ni o . h>
I*
p
C : This progra m di s pla y s s o m e vari a bles to the cons o l e . */
(
= -16 , 29 ;
625 1 1 ;
=
cprinff
Notestandarthatd output
consoledoes.outputUsedoes\r\nnoti nsttransla te \n as
169
Output
Remarks The cputs function writes the null-tenninated string pointed to by string directly to the con
sole. Note that a carriage-return-line-feed (CR-LF) combination is not automatically ap
pended to the string.
Return Value If successful, cputs returns a 0. If the function fails, it returns a nonzero value.
C P UTS . C :
�
voi dI*maiStnring() to pri nt at console. Note the \r ( return } character. */
i
i
{
!
�
I
r
I
°*'
I
#include <Sys\types.h>
#include <Sys\stat.h>
#include <errno.h>
#include <io.h> Required only for function declarations
Remarks The creat function either creates a new file or opens and truncates an existing file. If the
file specified by filename does not exist, a new file is created with the given permission set
ting and is opened for writing. If the file already exists and its permission setting allows
writing, creat truncates the file to length 0, destroying the previous contents, and opens it
for writing.
The permission setting, pmode, applies to newly created files only. The new file receives
the specified permission setting after it is closed for the first time. The integer expression
pmode contains one or both of the manifest constants S_IWRITE and S_IREAD, defined in
SY�TAT.H. When both of the constants are given, they are joined with the bitwise-OR
operator ( I ). The pmode argument is set to one of the following values:
Value Meaning
S_IWRITE Writing permitted
S_IREAD Reading permitted
S_IREAD I S_IWRITE Reading and writing permitted
If write permission is not given, the file is read-only. Under DOS and OS/2, it is not
possible to give write-only permission. Thus, the S_IWRITE and S_IREAD I S_IWRITE
modes are equivalent. Under DOS versions 3.0 and later, files opened using creat are al
ways opened in compatibility mode (see sopen).
The creat function applies the current file-permission mask to pmode before setting the
permissions (see umask).
Note that the creat routine is provided primarily for compatibility with previous libraries.
A call to open with 0_CREAT and 0_TRUNC in the oflag argument is equivalent to creat
and is preferable for new code.
creat 172
Return Value If successful, creat returns a handle for the created file. Otherwise, it returns -1 and sets
errno to one of the following constants:
Value Meaning
EACCES Path name specifies an existing read-only file or specifies a
directory instead of a file
EMFILE No more handles available (too many open files)
ENOENT Path name not found
See Also chmod, chsize, close, dup, dup2, open, sopen, umask
/* CREexistiAT. Cng: �hislfil e ) progranamedmdausteas andcreatopento itcrforeatewritithe fileng. < or truncate the
#i#i#i nnnclude <s y lss\\ts ytapes. h >
*
clude I
<s y t . h >
*I
#i#i nnclude
clude
clude \
�
<io
<st
<st . h
i
li>
ob. h. >h>
voi( di nmait fh:n ()
r
I
i
) ata", tS_crIREeaAtDe dataS_I WfilRITeE" );
fhif( perrfhcreoar{�1 C " C" douldn'
j
I
(
cl ose< fh !
1
I
>:
>:
I
I
Remam The cscanf function reads data directly from the console into the locations given by
argument. The getche function is used to read characters. Each optional argument must be
a pointer to a variable with a type that corresponds to a type specifier in format. The for
mat controls the interpretation of the input fields and has the same form and function as the
format argument for the scanf function; see scanf for a description offormat.
While cscanf normally echoes the input character, it will not do so if the last call was to
ungetch.
Return Value The cscanf function returns the number of fields that were successfully converted and as
signed. The return value does not include fields that were read but not assigned.
The return value is EOF for an attempt to read at end-of-file. This may occur when key
board input is redirected at the operating system command-line level. A return value of 0
means that no fields were assigned.
inandthetheresprograThiponse.smprogra
I * C S CAN F . C :
* Thdispenlamycsprscathonmfptsat returns
fornumber.a thstringe numandber ofusesi tcscanf
ems mattoched,read
#i#i nnclude
clude <stdi<conio.o . hh>>
*
*I
'
I
{ :
cpricprintf(
result ntf(=1cscanf(
f
"E" \nr\ternYouthr" %enterei e%iintegers:
I
I
e %i",
d • &i[
); "):
0 J, &i[ l ], &i[ 2 ] ) ;
while( nrt
sult-
f<
1
" % -
i )
cprintf( " \ r\n" ) ; i[resul t J.>;
cpri ",
I
YouEnterenterthreede integers:43 34 34 43
Output
987 k
987
175 clime
Rematits The ctime function converts a time stored as a time t value to a character string. The
timer v alue is usually obtained from a call to time, which returns the number of seconds
elapsed since 00:00:00 Greenwich mean time, January 1 , 1 970.
Wed Jan
The string result produced by ctime contains exactly 26 characters and has the form of the
following example:
02 02 : 03 : 5 5 1 980 \ n \ 0
A 24-hour clock i s used. All fields have a constant width. The newline character (\n) and
the null character ('\0') occupy the last two positions of the string.
Calls to the ctime function modify the single statically allocated buffer used by the
gmtime and the localtime functions. Each call to one of these routines destroys the result
of the previous call. The ctime function also shares a static buffer with the asctime func
tion. Thus, a call to ctime destroys the results of any previous call to asctime, localtime,
or gmtime.
Retum Value The ctime function returns a pointer to the character string result. If time represents a date
before 1 980, ctime returns NULL.
I*
*
ASCTItransl
M E.
a C
tes: This
i t i n progra
to the m s pla
t c es
ructurethe
ne s
w y
ti
stri ng form for output, usi ng the ascti me functi on. s t
m e
e m ti
and m e i
thenn the long
converts i
i n
t teger
to aclock,
#i#i nnclude
clude <ti<stdime.oh. >h>
*
*I
clime
�
!
(
tinemwe(ti m&ae locklocalti); me( &aclock ); //** GetConvertti metiinmesetoconds.struct*/ tm form . */
�
I
pri/ * nPritf(nt Thlocale currti meentasdatea striandng.ti m*/e are : %s\n", ascti me( newti me ) );
f
!
�
!
I
!
1 5 0 6 : 5 7 : 5 9 1 989
177 cwait
#include <process.h>
Rematks The cwait function suspends the calling process until the specified child process
tenninates.
If not NULL, termstat points to a buffer where cwait will place the tennination-status word
and the return code of the tenninated child process.
The tennination-status word indicates whether or not the child process tenninated nor
mally by calling the OS/2 DosExit function. (Programs that terminate with exit or by
"falling off the end of main" use DosExit internally.) If the process did terminate nor
mally, the low-order and high-order bytes of the tennination-status word are as follows:
Byte Contents
High order Contains the low-order byte of the result code that the child
code passed to-DosExit. The DosExit function is called if the
child process called exit or _exit, returned from main, or
reached the end of main. The low-order byte of the result
code is either the low-order byte of the argument to _exit or
exit, the low-order byte of the return value from main, or a
random value if the child process reached the end of main.
Low order 0 (normal tennination).
cwait 178 !
If the child process terminates without calling DosExit, the high-order and low-order bytes
of the termination-status word are as follows:
Byte Contents
High order 0
Low order Termination code from DosCWait:
Code Meaning
Hard-error abort
2 Trap operation
3 SIGTERM signal not intercepted
The procid argument specifies which child-process termination to wait for. This value is re
turned by the call to the spawn function that started the child process. If the specified child
process terminates before cwait is called, the function returns immediately.
The action argument specifies when the parent process resumes execution, as shown in the
following list:
Value Meaning
WAIT_CHILD The parent process waits until the specified child process has
ended.
WAIT_GRANDCHILD The parent process waits until the specified child process and
all child processes of that child process have ended.
Return Value! If the cwait function returns after normal termination of the child process, it returns the
child's process ID.
If the cwait function returns after abnormal termination of the child process, it returns -1
and sets errno to EINTR.
Otherwise, the cwait function returns - 1 immediately and sets errno to one of the follow
ing error codes:
Value Meaning
Note that the OS/2 DosExit function allows programs to return a 1 6-bit result code. How
ever, the wait and cwait functions return only the low-order byte of that result code.
I*I** CWAIfor Ta . Csp: ecifie This dprograprocessm launchto fiesn i severals h. child processes and waits
#defi#define
#defi nnee III NNNCLCLCL___DNNOOOCOMMON
PSPRM OCESS
#i#i#i nnnclude
clude
clude <os2.
<pr
<stdli o h
cess. >
b . h h
> > /*
/ * Dos
c w S
ai l
t e ep */
*/
#i#include
nclude <stdi<ti me.oh. >h>
I* Macrneogetrato getndom(a raminndo, mmai xnteger) ((rwia nd()thi n a ( si pnt){((eci fi medaxra) nge1) */- ( mi n ))) ( mi n ))
#defistruct
( charint CHILpinaD mde[; 10];
% + +
>:
>:
0118Ctlpnan Convert between IEEE double value and Microsoft (MS) binary double value.
#include <math.h>
These routines allow C programs (which store floating-point numbers in the IEEE format)
to use numeric data in random-access data files created with those versions of Microsoft
BASIC that store floating-point numbers in MS binary format, and vice versa.
The argument srcB is a pointer to the double value to be converted. The result is stored at
the location given by dstB.
These routines do not handle IBEE NANs ("not a number") and infinities. IBEE denormals
are treated as 0 in the conversions.
Return Value These functions return 0 if the conversion is successful and 1 if the conversion causes an
overflow.
Remarks The difftime function computes the difference between the supplied time values, timerO
and timerl.
Return Value The difftime function returns, in seconds, the elapsed time from timerO to timerl . The
value returned is a double-precision number.
pripri nntf(tf( ""TWorkihis progra m wi);l l do a fl oati ng poi nt mul tipl y ti mes\n" );
1
n g ... \n"
tifor(me(reslo&ujl tartp ==t ); loop < loop++ )
50000
I
difflime
= >:
>:
WorkiThisProgranprogra
gm takesm will do aseconds.
fl oati ng poi nt mul t i p l y ti mes
Oulput
50000
• • •
4 . 00
_disable!
II
184
I #include <dos.h>
Remarks The _disable routine disables interrupts by executing an 8086 CLI machine instruction.
Use _disable before modifying an interrupt vector.
#include <graph.h>
Remarks Upon entry into each graphic routine, the screen cursor is turned off. The _displaycursor
function determines whether the cursor will be turned back on when programs exit graphic
routines. If toggle is set to _GCURSORON, the cursor will be restored on exit. If toggle is
set to _GCURSOROFF, the cursor will be left off.
Return Value The function returns the previous value of toggle. There is no error return.
_displa
_outtext(
=
y cursor( _G E
C A RSCREEN
URSOR O N
" \ nOl d cursor shape: " ); );
);
getchCl;
I_sette
* Changextcursor(cursor shanewcursor
pe */sha);pe:
_outtext(
getchC); " \ nNe w cursor " > :
R_setteestx,cursorC
Cre "\orin " g i);nolaldcursor
cursor shape
186
_outtex
/*
> ;
*/
187 div
Description Computes the quotient and the remainder of two integer values.
#include <Stdlib.h>
numer Numerator
denom Denominator
Remarks The div function divides numer by denom, computing the quotient and the remainder. The
div_t structure contains the following elements:
Element Description
The sign of the quotient is the same as that of the mathematical quotient. Its absolute value
is the largest integer that is less than the absolute value of the mathematical quotient. If the
denominator is 0, the program will terminate with an error message.
Return Value The div function returns a structure of type div_t, comprising both the quotient and the re
mainder. The structure is defined in STDLIB.H.
I*** twodisplaarygThisuments
Example
s the exaresults
monplethetakcoofmemanthes twdoi nliteger
i nnteger
__________________________________________________________________�
s as
divisi oco
n. m mand-line
This pr o ar
gr a g
m u m ents
accepts a n d
first arquotegumentfollandowbyi nrethegm.thesecond.programFi nanallme,y , then
**/* callsit pri divnts theto divistrduecturethe members
DIV .C:
#i#i#i nnnclude
clude <stdli
<stdio.
clude <math. h> b .
h h
> >
voi di nmait x,ny<[ : int argc, char *argv[J
divx =_tatod\lii v(_arregsult;v[l] );
l
{ .
l
y l :
l:
l:
876 13
876 , 13
67 , 5
189 _dos_allocmem
#include <dos.h>
#include <errno.h>
Remarks The dos allocmem function uses DOS service Ox48 to allocate a block of memory size
paragraphs long. (A paragraph is 1 6 bytes.) Allocated blocks are always paragraph
aligned. The segment descriptor for the initial segment of the new block is returned in the
word that seg points to. If the request cannot be satisfied, the maximum possible size (in
paragraphs) is returned in this word instead.
Retum Value If successful, the dos allocmem returns 0. Otherwise, it returns the DOS error code and
sets errno to ENOMEM, indicating insufficient memory or invalid arena (memory area)
headers.
See Also alloca, calloc functions, _dos_freemem, _dos_setblock, halloc, malloc functions
/* 20 */
failed\n" ) );
priI n ern asef( " aallocation
llocati on tosuccessful\n" );
20 , != 0
if(elsepri_don _setblock(
I*
�
allocation
free memor i nsuccessful
allocati
Output
o n successful
crease successful
191 _dos_ close
#inclu.de <dos.h>
#include <errno.h>
Rematks The _dos_close function uses system call Ox3E to close the file indicated by handle. The
file's handle argument is returned by the call that created or last opened the file.
Return Value The function returns 0 if successful. Otherwise, it returns the DOS error code and sets
errno to EBADF, indicating an invalid file handle.
Do not use the DOS interface 1/0 routines with the console, low-level, or stream 1/0
routines.
See Also close, creat, _dos_creat functions, _dos_open, _dos_read, _dos_write, dup, open
I*#i nDOPEN.
Exampm
C : This progra m us e s DOS
_________________________________________________________________
>:
if(el sClperre_doos1_closrfile( " CelosewiC tfhhfailed\n"
_dos_close functi �n
192
I
'
!= 0
/* */
�
l ;
OpenFile succe
Output
input file
193 t
_das_crea Functions
#include <dos.h>
#include <errno.h>
Remarks The _dos_creat and _dos_creatnew routines create and open a new file namedfilename;
this new file has the access attributes specified in the attrib argument. The new file's
handle is copied into the integer location pointed to by handle. The file is opened for both
read and write access. If file sharing is installed, the file is opened in compatibility mode.
The _dos_creat routine uses system call INT Ox3C, and the _dos_creatnew routine uses
system call INT Ox5B. If the file already exists, _dos_creat erases its contents and leaves
its attributes unchanged; however, the _dos_creatnew routine fails if the file already exists.
Return Value If successful, both routines return 0. Otherwise, they return the DOS error code and set
errno to one of the following values:
Constant Meaning
EACCES Access denied because the directory is full or, for _dos_creat
only, the file exists and cannot be overwritten
EEXIST File already exists (_dos_creatnew only)
EMFILE Too many open file handles
ENOENT Path or file not found
II
_dos_c at Functions � 194
Compallblllty I
I
DCREbecaAuseT.mCi annot
** progra eadyatexiemastcrs.neewatesfilea filusi engusingthe _dosthe__doscrea_tcrneweatfunctifunction.on The
Thit alrs ecrprogra
Exampm �-+-�����
I* j
s
l
#i#i/fi nnncclude
*I
I
I
(
elsepripri nntt1'(( ""CCouldn'
�
�
r e a t ed
t create data fil e\n"
data fil e . \ n " );
>:
!= 0
I*
* h eata•,fi l e_Aexists
_ RD O NL Y , &fh 2
elsepri,ntf( " C reated data fil e . \n" );
pri � tf( " C oul d n' t create data file\ n "
*I I
) != 0 )
I
_do 1 s
_dos_cll ose( fhl _ cl ose(
•
fh2 )
>;
:
>:
I
CrCouldn'eatedtdatacre tefil edata. file I
I
Output
Lr
i
195 _ dos_ find Functions
Description Find the file with the specified attributes or find the next file with the specified attributes.
#include <dos.h>
#include <errno.h>
Remarks The _dos_findfirst routine uses system call INT Ox4E to return information about the first
instance of a file whose name and attributes match filename and attrib.
Thefllename argument may use wildcards {* and ?). The attrib argument can be any of the
following manifest constants:
Constant Meaning
_ A ARCH
_ Archive. Set whenever the file is changed, and cleared by the
DOS BACKUP command.
_ A HIDDEN
_ Hidden file. Cannot be found with the DOS DIR command.
Returns information about normal files as well as about files
with this attribute.
_A NORMAL
_ Normal. File can be read or written without restriction.
_A RDONLY
_ Read-only. File cannot be opened for writing, and a file with
the same name cannot be created. Returns information about
normal files as well as about files with this attribute.
_A SUBDIR
_ Subdirectory. Returns information about normal files as well
as about files with this attribute.
_A SYSTEM
_ System file. Cannot be found with the DOS DIR command.
Returns information about normal files as well as about files
with this attribute.
_A VOLID
_ Volume ID. Only one file can have this attribute, and it must
be in the root directory.
_dos_fin Functions 196
Multiple constants can be combined (with the OR operator), using the vertical-bar ( I )
character.
Information is returned in a find-t structure, defined in DOS.ff. The find t structure con-
tains the following elements: -
Element Description
The formats for the wr time and wr date elements are in DOS format and are not usable
by any other C run-time function. The time format is shown below:
Bits Contents
Bits Contents
Do not alter the contents of the buffer between a call to dos findfirst and a subsequent
call to the dos findnext function. Also, the buffer shoUtd not be altered between calls to
_dos_findiiext-
197 _ dos_ find Functions
The _ dos_findnext routine uses system call Ox4F to find the next name, if any, that
matches the filename and attrib arguments specified in a prior call to _dos_findfirst The
fileinfo argument must point to a structure initialized by a previous call to _dos_findfirst
The contents of the structure will be altered as described above if a match is found
Return Value If successful, both functions return 0. Otherwise, they return the DOS error code and set
errno to ENOENT, indicating that filename could not be matched.
I**I DFItheND..cCextensi : This pron.ogram fi nds and prints all files i n the current directory wi th
#iIi nnccludeude <stdio. h>
*
<dos.
mai( nstr() uct fi nd_t c_file;
1 h >
_dosI*pri nfi_tf(nfidnfirst
dfirst< . c " *file. c ", i _An _currNORMentAL , dir&c_efilectory */
printf( "Listi ng%sofis .c%ldfi bl yes\n\n"
"File: tes\n",
>:
>:
Fi l e: FWRITE. C is bytes
2674
258
577
1 123
,
I
_ dos f msm
_ 198
#include <dos.h>
#include <errno.h>
Rematics The _dos_freemem function uses system call Ox49 to release a block of memory pre
viously allocated by _dos_allocmem. The seg argument is a value returned.by a previous
call to _dos_allocmem The freed memory may no longer be used by the application
program.
Return Value If successful, dos freemem returns 0. Otherwise, it returns the DOS error code and sets
errno to ENOMEM, indicating a bad segment value (one that does not correspond to a seg
ment returned by a previous _dos_allocmem call) or invalid arena headers.
�
f
#i n c l ude < d o . h >
#i n c l ude < s t i o . h >
I
t
v o i d ma i n ( )
f egment :
(
u n s i g n ed
u n s i g n ed axs i ze :
/ * Al l o c a e ?0 pa r a g r a p h s * /
i f ( _d os_ l l o cmem C 20 , & s egment J ! = 0
p r i n t f " a l l o c a t i on fa i l ed \ n " l :
el se
p r i n t f " a l l oc a t i o n s u c c e s s fu l \ n " l :
dos freemem
*/
199 _ _
!= 0
I * I n c re a s e a l l oca t i o n t o 40 p a r a g r a p h s
i f ( _do s_s e t b l o c k C 40 , s egmen t , &ma x s i ze )
p r i n t f ( " a l l oc a t i on i n c rea s e fa i l ed \ n " ) ;
el se
p r i n t f C " a l l oca t i o n i n c rea s e s uc c e s s f u l \ n " ) ;
!=
I * Free memo ry * I
i f ( _do s_f reemem ( s egment ) 0 )
p r i n t f ( " f ree memo ry fa i l ed \ n " ) ;
el se
p r i n t f C " f ree memo ry s u cc e s s fu l \ n " ) ;
Output
a l l o c a t i on s u c c e s s fu l
a l l o c a t i on i nc re a s e s u c c e s s f u l
f ree memo ry s u c c e s s f u l
I
I
_ das g tdate
_ 200
Oescr/pl/an Gets current system date using system call INT Ox2A.
#include <dos.h>
Rematb The _dos_getdate routine uses system call Ox2A to obtain the current system date. The
date is returned in a dosdate_t structure, defined in DOS.ff.
-
Element Description
&m -+---------------------------------------------------�------
DGTIME . CI: T h i s p ro g r a m
___
r
I* gets a n d d i s p l a y s c u r r ent d a t e a n d t i me v a l ues . * /
v o i d ma i n ( )
�
{
l
I
s t r u c t d s d a t e_t d a t e ;
s t ru c t d s t i me_t t i me ;
I
201 _ das getdate
_
I * Get c u r re n t d a t e a n d t i me v a l ues * /
Output
#include <dos.h>
#include <errno.h>
Remades The _dos_getdiskfree routine uses system call Ox36 to obtain information on the disk
drive specified by drive. The default drive is 0, drive A is 1 , drive B is 2, and so on.
Information is returned in the diskfree_t structure (defined in DOS.H) pointed to by
diskspace.
The struct diskfree�t structure contains the following elements:
Element Description
Retum Value If successful, the function returns 0. Otherwise, it returns a nonzero value and sets ermo to
EINV AL, indicating that an invalid drive was specified.
t
#i n c l u d e < s t d i o . h>
Ii i n c 1 ude < d . h >
I
I
203 _ dos getdiskfree
_
ma i n ( )
(
s t ruct d i s k f r e e_t d r i v e ;
I * Get i n fo rma t i on on d e fa u l t d i s k d ri v e 0 * /
Output
Daer/pt/an Gets the current disk drive using system call INT Ox19.
#include <dos.h>
Remarks The _dos_getdrive routine uses system call Ox 19 to obtain the current disk drive. The cur
rent drive is returned in the word that drive points to: 1 = drive A, 2 = drive B, and so on.
I * D G D R I V E . C : T h i s p r o g r a m p r i n t s t h e l et t e r of t h e c u r r e n t d r i v e ,
* c h a n g e s t e d e fa u l t d r i v e t o A , t h e n r et u r n s t h e n umbe r o f d i s k d r i v e s .
*I
�
,
#i n c l ude < s t i o . h >
#i n c l u d e < d o . h >
�
v o i d ma i n ( )
(
u n s i gned l dd r i v e , newd r i ve ;
u n s i gned numb e r_of_d r i v e s ;
J
I * P r i nt u r rent d e f a � l t d r i v e i n f o rma t i on * /
_d o s_g e t d � i v e ( & o l d d r i v e l ;
p r i n t f { · � h e c u r re n t d r i ve i s : % c \ n " , ' A ' + o l d d r i v e -
�
1 );
I
I * Set d e a u l t d r i v e to be d r i v e A * /
j
p r i n t f { " C h a n g i ng d e fa u l t d r i v e t o A \ n " ) ;
_d o s_s etd i v e < 1 , & n umb e r_of_d r i v e s l ;
Output
T h e c u r re n t d r i v e i s : C
C h a n g i n g d e fa u l t d r i v e t o A
The cu rrent d r i ve i s : A
N umbe r of l og i c a l d r i v e s : 2 6
_ das_ge 1eattrf 206
Description Gets the current attributes of a file or directory, using system call INT Ox43.
#include <dos.h>
#include c;::errno.h>
Remarks The _dos_getflleattr routine uses system call Ox43 to obtain the current attributes of the
file or directory pointed to by pathname . The attributes are copied to the low-order byte of
the attrib word. Attributes are represented by manifest constants, as described below:
Constant Meaning
Return Value If successful, the function returns 0. Otherwise, it returns the DOS error code and sets
errno to ENOENT, indicating that the target file or directory could be found.
207 _ dos getfileattr
_
Exampm _________________________________________________________________
I * D G F I L EAT . C : T h i s p r o g r a m c re a t e s a f i l e w i t h t h e s pec i f i ed a t t r i b u t e s ,
* t h en p r i n t s t h i s i n fo rma t i o n b e f o r e c h a n g i ng t h e f i l e a t t r i butes b a c k
* t o n o rma l .
*/
#i n c l u d e < s t d i o . h >
Iii n c 1 u d e < d o s . h >
v o i d ma i n ( )
(
u n s i gned o l d a t t r i b , n ewa t t r i b ;
i n t fh ;
I * Get a nd d i s p l ay f i l e a t t r i b u t e * /
_d os_getfi l ea t t r C " DG F I LEAT . C " , &ol d a tt r i b ) ;
p r i n t f ( " At t r i b u t e : 0x% . 4x \ n " , o l d a t t r i b ) ;
i f ( ( o l d a t t r i b & _A_RDON LY ) ! = 0 )
p r i n t f ( " Re a d on l y f i l e \ n " ) ;
el se
pri ntf ( " Not a r e a d onl y fi l e . \ n " ) ;
/ * Re s e t f i l e a t t r i b u t e t o n o rma l f i l e * /
_d o s_s e t f i l ea t t r ( " DG F I L EAT . C " , _A_RDON LY ) ;
_d o s_g et f i l e a t t r C " DG F I L EAT . C " , &newa tt r i b ) ;
p r i n t f C " A t t r i b u t e : 0x% . 4x \ n " , n ewa tt r i b ) ;
/ * Res t o r e fi l e a t t r i b u t e * /
_d o s_s e t f i l ea t t r ( " DG F I LEAT . C " , o l d a t t r i b ) ;
_d o s_g et f i l e a t t r ( " DG F I L EAT . C " , & n ewatt r i b ) ;
p r i n t f ( " A t t r i b u t e : 0x% . 4x \ n " , n ewa t t r i b ) ;
Output
Att r i b u t e : 0x0020
Not a read onl y fi l e .
Att r i b u t e : 0x000 1
Att r i b u t e : 0x0020
208
Description Gets the date and time a file was last written, using system call INT Ox57.
#include <dos.h>
#include <errno.h>
Remarks The _dos_getftime routine uses system call Ox57 to get the date and time that the specified
file was last written. The file must have been opened with a call to _dos_open or
_dos_creat prior to calling _dos_getftime. The date and time are returned in the words
pointed to by date and time. The values appear in the DOS date and time format:
0- 4 Day ( 1-3 1 )
5- 8 Month (1-12)
9-15 Year (1980-2099)
Return Value If successful, the function returns 0. Otherwise, it returns the DOS error code and sets
errno to EBADF, indicating that an invalid file handle was passed.
209 _ dos getftime
_
I * D G FT I M E . C : T h i s p r o g r a m d i s p l ays a nd mod i f i e s t h e d a t e a nd t i me
* f i e l d s of a f i l e .
*/
v o i d ma i n ( )
{
I * FEDC BA98 7 6 54 3 2 1 0 */
u n s i gned n ew_d a t e = 0 x l 84 f ; I * 000 1 1000 0 1 00 1 1 1 1 2/ 15/92 */
u n s i g n ed n ew_t i me = 0x48e0 ; I * 0 1 00 1000 1 1 1 0 0000 9 : 07 AM */
u n s i gned o l d_d a t e , o l d_t i me ;
i n t fh ;
I * Get f i l e d a t e a n d t i me * /
_d o s_g et ft i me ( f h , & o l d_d a t e , &ol d_t i me ) ;
p r i n t f ( " O l d d a t e f i e l d : 0x% . 4x \ n " , o l d_d a t e ) ;
p r i n t f ( " O l d t i me f i e l d : 0x% . 4x \ n " , o l d_t i me ) ;
s y s t e m ( " d i r d g f t i me . ob j " ) ;
I * Mod i fy f i l e d a t e a n d t i me * /
i f ( ! _dos_s et ft i me ( f h , new_d a t e , n ew_t i me > >
{
_d os_g e t ft i me ( f h , &n ew_d a t e , &new_t i me ) ;
p r i n t f ( " N ew d a t e f i e l d : 0x% . 4x \ n " , new_d a t e ) ;
p r i n t f ( " N ew t i me f i e l d : 0x% . 4x \ n " , n ew_t i me > :
s y s t e m ( " d i r d g ft i me . ob j " > :
I * R e s t o r e d a t e a n d t i me * /
_d os_s et ft i me C f h , o l d_d a t e , o l d_t i me > :
)
_d o s_c l o s e ( fh > :
_ dos g lflime
_ 210
Output
Ol d date f el d : 0x12cf
O l d t i me f e l d : 0x94bb
V o l ume i n d r i v e C i s 052
D i r ec t o ry of C : \ L I B R E F
D G FT I M E 0 J 3923 6 - 1 5 -89 6 : 37 p
1 i l e C s > 1 3 6 7 6 544 by t e s free
�
N ew date f e l d : 0 x 1 84f
N ew t i me f e l d : 0x48e0
V o l ume i n d r i v e C i s 052
D i r ec t o ry o f C : \ L I B R E F
D G FT I M E 0 J 3923 2- 15-92 9 : 07 a
1 i l e C s ) 1 3 6 7 6 544 by t e s f ree
211 _dos_gettime
DeBt:tlpllon Gets the current system time, using system call INT Ox2C.
#include <dos.h>
Remarks The _dos_gettime routine uses system call Ox2C to obtain the current system time. The
time is returned in a dostime_t structure, defined in DOS.H.
The dostime_t structure contains the following elements:
Element Description
#i n c l u d e < s t d i o . h >
#i n c l u d e < d o s . h >
v o i d ma i n ( )
{
s t r u c t d o s d a t e_t d a t e :
s t r u c t d o s t i me_t t i me ;
212
Output
I
Today ' s d a t e i s 6 - 1 5 - 1 989
The t i me i s l 1 8 : 07
213 _dos_getvect
Out:rlptlan Gets the current value of the interrupt vector, using system call INT Ox35.
#include <dos.II>
Rematlcl The _dos_getvect routine uses system call INT Ox35 to get the current value of the inter
rupt vector specified by intnum.
This routine is typically used in conjunction with the _dos_setvect function. To replace an
interrupt vector, first save the current vector of the interrupt using _dos_getvect Then set
the vector to your own interrupt routine with _dos_setvect The saved vector can later be
restored, if necessary, using _dos_setvect The user-defined routine may also need the orig
inal vector in order to call that vector or chain to it with _chain_intr.
Retum Value The function returns a far pointer for the intnum interrupt to the current handler, if there
is one.
#include <dos.h>
The routine first exits the calling process, leaving it in memory. It then returns the low
order byte of retcode to the parent of the calling process. Before returning execution to
the parent process, _dos_keep sets the allocated memory for the now-resident process to
memsize 1 6-byte paragraphs. Any excess memory is returned to the system.
The _dos_keep function calls the same internal routines called by exit. It therefore takes
the following actions:
• Restores interrupt vectors replaced by the C start-up code. The primary one is interrupt
0 (divide by zero). If the emulator math library is used and there is no coprocessor,
interrupts Ox34 through Ox3D are restored. If there is a coprocessor, interrupt 2 is
restored.
The _dos_keep function does not automatically close files; you should do this specifically
unless you want files opened by the TSR installation code to remain open for the TSR.
Do not use the emulator math library in TSRs unless you are familiar with the C start-up
code and the coprocessor. Use the alternate math package (not supplied with Microsoft
QuickC) if the TSR must do floating-point math.
Do not run programs that use _dos_keep from inside the Microsoft Programmer's
WorkBench environment, since doing so causes subsequent memory problems. The
_dos_keep function terminates the program when executed in the Programmer's
WorkBench environment.
#include <dos.h>
#include <errno.h>
Rematks The _dos_open routine uses system call INT Ox3D to open the existing file pointed to by
filename. The handle for the opened file is copied into the integer pointed to by handle.
The mode argument specifies the file's access, sharing, and inheritance modes by combin
ing (with the OR operator) manifest constants from the three groups shown below. At
most, one access mode and one sharing mode can be specified at a time.
Do not use the DOS interface 1/0 routines in conjunction with the console, low-level, or
stream 1/0 routines.
217 _ dos_ open
Return Value If successful, the function returns 0. Otherwise, it returns the DOS error code and sets
errno to one of the following manifest constants:
Constant Meaning
v o i d ma i n ( )
(
i nt fh ;
I * Open f i l e w i t h _d o s_open f u n c t i on * /
i f ( _d os_open ( " d a t a l " , O_RDON LY , & f h ) ! = 0 )
p e r ro r C " Open fa i l ed on i n p u t fi l e\ n " ) ;
el se
p r i n t f C " Open s u c c e eded o n i n put fi l e \ n " ) ;
I * C l o s e f i l e wi t h _d os_c l o s e f u n c t i on * /
i f ( _d o s_c l o s e C f h > ! = 0 >
p e r ro r C " C l o s e fa i l ed \ n " ) ;
el se
p r i n t f ( " Fi l e s u c c e s s f u l l y c l o s ed \ n " ) ;
218
I
Output I
b
Open s u c c eect ct o n i np u t f i l e
Fi l e s u c c e s s r u l l y c l o s ed
219 _ dos re d
_ a
Description Reads data from a file, using system call INT Ox3F.
#include <dos.h>
Remarks The _dos_read routine uses system call INT Ox3F to read count bytes of data from the file
specified by handle. The routine then copies the data to the buffer pointed to by buffer.
The integer pointed to by numread will show the number of bytes actually read, which
may be less than the number requested in count. If the number of bytes actually read is 0, it
means the routine tried to read at end-of-file.
Do not use the DOS interface 1/0 routines in conjunction with the console, low-level, or
stream 1/0 routines.
Return Value If successful, the function returns 0. Otherwise, it returns the DOS error code and sets
errno to one of the following constants:
Constant Meaning
/**I* ofDREAa D.filC : eThis. program uses the DOS 1 /0 opera ti ons to read the contents
220
�
v o i d ma i n ( )
! I
i nt fh : I
c h a r b u f e r [ 50 ] ;
u n s i g n e d n umber_rea d ;
!=
/ * Open i l e wi t h _d o s_open f u n c t i on * /
i f ( _d o s�o p e n C " d re a d . c " , O_RDO N LY , &fh ) 0
p e r ro' C " Open fa i l ed on i n put f i l e \ n " > :
el se
pri nt " Open s u c c eeded on i n put f i l e \ n " > :
I * R e a d a t a wi t h _d o s_re a d f u n c t i on * /
_d os_rea C f h , buffe r , 50 , & n umber_re a d > :
p r i n t f C F i r s t 40 c h a r·a c t e r s a re : % . 40 s \ n \ n " , b u f f e r ) :
l
/ * C l o s e f i l e w i t h _d o s_c l o s e f u n ct i on * /
_d os_c l o e C fh > :
Output I
II
O p e n s u c c e e ed on i n put f i l e
F i r s t 40 c h r a c t e r s a re : / * D R EAD . C : T h i s p r o g r a m u s e s t h e D O S
221 _das_setblack
Ducrlpllan Changes the size of a memory segment, using system call INT Ox4A.
#include <dos.h>
Remarks The _dos_setblock routine uses system call INT Ox4A to change the size of seg, pre
viously allocated by _dos_allocmem, to size paragraphs. If the request cannot be satisfied,
the maximum possible segment size is copied to the buffer pointed to by maxsize.
Return Value The function returns 0 if successful. If the call fails, it returns the DOS error code and
sets ermo to ENOMEM, indicating a bad segment value was passed. A bad segment value
is one that does not correspond to a segment returned from a previous _dos_allocmem
call, or one that contains invalid arena headers.
I* DALOCMEM . C : T h i s p r o g r a m a l l o c a t e s 20 pa r a g ra p h s of
* t h e a l l o c a t i on t o 40 p a r a g ra p h s , a n d t h e n frees t h e
memo ry , i n c re a s e s
*I
memo ry s p a c e .
#i n c l u d e < d o s . h>
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
{
u n s i gned s egment ;
u n s i gned ma x s i z e ;
I
_ _ ,
dm; s lblock 222
I
I * Al l o ¢ a t e 2 0 p a r a g ra p h s * /
i f ( _d o , _a l l ocmem ( 20 , &s egment > ! = 0
p r i n f ( " a l l oc a t i on fa i l ed \ n " ) ;
el se
p r i n f ( " a l l oc a t i on s u c c e s s f u l \ n " ) ;
I* I ner a s e a l l oc a t i o n to 40 pa r a g r a p h s * /
i f ( _d o _s etbl oc k ( 40 , s e gme n t , &ma x s i z e ) ! = 0
pri n f ( " a l l o c a t i on i n c r e a s e fa i l ed \ n " ) ;
el s e
pri n f ( " a l l oc a t i on i n c r e a s e s u c c e s s fu l \ n " ) ;
I * Free memory * I
i f ( _d o _f reemem ( s egment ) ! = 0 )
pri n f ( " f ree memo ry fa i l ed \ n " l ;
el se
pri n f C . " f ree memo ry s u c c e s s f u l \ n " ) ;
Output
a l l oc a t i on s u c c e s s f u l
a l l oc a t i o n i n c r ea s e s u c c e s s f u l
free memo r s u c c e s s f u l
223 _ dos
_ setdate
Description Sets the current system date, using system call INT Ox2B.
#include <dos.h>
Element Description
unsigned char day 1 -3 1
unsigned char month 1 -12
unsigned int year 1980- 2099
unsigned char dayofweek 0 - 6 (0 = Sunday)
Return Value If successful, the function returns 0. Otherwise, it returns a nonzero value and sets errno to
EINVAL, indicating an invalid date was specified.
*
I * D ST I M E . C : T h i s p r o g r a m c h a n g e s t h e t i me a n d d a t e v a l ues a n d d i s p l a y s t h e
n e w d a t e a n d t i me v a l u e s .
*I
_ das se a te
_ 224
v o i d ma i n ( ) I
1 �
s t ruct d s d a t e_t o l d d a t e , n ewd a t e = 4 }
3 }
• { 7 }
( 45 }
• ( 1 984 } } :
{ 30 } { 0 } }:
J�
s t ru c t d s t i me_t o l d t i me , n ewt i me = • • •
cha r d a t eb u f [ 40 ] , t i mebu f [ 40 J :
I * Get c r r e n t d a t e a n d t i me v a l u e s * /
_d os_g e t dja t e C &ol d d a t e ) :
•1
�
_d os_g e t t me C & o l d t i me > :
p r i nt f ( s % s \ n " , _st rd a t e ( d a tebuf ) , _s t rt i me C t i meb uf ) > :
l
I * Mod i fy d a t e a nd t i me s t r u c t u res * /
_d os_s etd t e C &newd a t e > :
_d o s_s e t t " me C &n ewt i me > :
pri ntfC •s % s \ n " , _s t rd a t e C d a tebuf ) , _s t rt i me C t i meb u f ) > :
'
I * Re s t o r o l d d a t e a nd t i me * /
_d o s_s etd t e e &ol d d a t e > :
_d os_s e t t " me C &ol d t i me > :
Output [
0 6 / 1 5 / 89
0 7 / 04 / 84
&1 8 : 2 6 : 09
3 : 4 5 : 30
I
225 _dos_setdrive
Description Sets the default drive, using system call INT OxOE.
#include <dos.h>
Remarks The _dos_setdrive routine uses system call INT OxOE to set the current default drive to the
drive argument: 1 = drive A, 2 = drive B, and so on. The numdrives argument indicates the
total number of drives in the system. If this value is 4, for example, it does not mean the
drives are
designated A, B, C, and D; it means only that four drives are
in the system.
Return Value There is no return value. If an invalid drive number is passed, the function fails without in
dication. Use the _dos_getdrive routine to verify whether the desired drive has been set.
I * D G D R I V E . C : T h i s p r o g r a m p r i n t s t h e l et t e r of t h e c u r r e n t d ri v e ,
* c h a n g e s t h e d e fa u l t d r i ve to A , t h e n r e t u r n s t h e number of d i s k d r i v e s .
*I
v o i d ma i n ( )
{
u n s i gned o l d d r i ve , newd r i ve ;
u n s i gned n umbe r_of_d r i v e s ;
I * P r i n t c u r r ent d e fa u l t d r i ve i n f o rma t i on * /
_d o s_g et d r i v e C &ol d d r i v e ) ;
p r i ntf ( " T h e c u r rent d r i ve i s : % c \ n " , ' A ' + o l d d r i ve - 1 );
I * Set d e fa u l t d r i v e t o be d r i v e A * /
p r i n t f ( " C h a n g i ng d e fa u l t d r i v e t o A \ n " ) ;
_d o s_s etd r i v e C 1 , & n umb er_o f_d r i ves ) ;
I
_dos_+rive 226
� ew defa u l t
i
I * Get d r i v e i n fo rma t i on a n d t o t a l n umbe r of d r i v e s */
_d os_ge� d r i v e ( &newd r i v e ) ;
p r i n t f ( l • T h e c u rrent d r i v e i s : %c \ n " , ' A ' + newd r i v e - 1 );
p r i n t f ( ! " N umbe r of l og i c a l d r i v e s : % d \ n " , n umbe r_of_d r i v e s ) ;
/ * R e s t d r e d e f a u l t d r i ve * /
,
_do s_s e d r i v e < o l d d r i v e , &n umbe r_of_d r i v e s ) ;
�
Output
T h e c u r ren ' d r i v e i s : C
Changi ng d faul t dri ve to A
T h e c u r rent d r i v e i s : A
N umber of l p g i c a l d r i v e s : 26
227 _dos_setfi/eattr
Description Sets the attributes of the file or directory, using system call INT Ox43.
#include <dos.h>
Remarks The _dos_setfileattr routine uses system call INT Ox43 to set the attributes of the file or
directory pointed to by pathname. The actual attributes are contained in the low-order byte
of the attrib word. Attributes are represented by manifest constants, as described below:
Constant Meaning
_A A C
_ R H Archive. Set whenever the file is changed, or cleared by the
DOS BACKUP command.
_A HIDDEN
_ Hidden file. Cannot be found by a directory search.
_A NORMAL
_ Normal. File can be read or written to without restriction.
_A RD ONLY
_ Read-only. File cannot be opened for writing, and a file with
the same name cannot be created.
_ U DIR
A S B
_ Subdirectory.
_A SYSTEM
_ System file. Cannot be found by a directory search.
_A VOLID
_ Volume ID. Only one file can have this attribute, and it must
be in the root directory.
Return Value The function returns 0 if successful. Otherwise, it returns the DOS error code and sets
errno to one of the following:
Constant Meaning
EACCES Access denied; cannot change the volume ID or the
subdirectory.
ENOENT No file or directory matching the target was found.
I
_dos_ + leattr 228
Compatibility
I
D ANSI • DOS D OS/2 D UNIX 0 XENIX
Example �-+-����
�� � �����
I * D G F I L EA � . C : Th i s p r o g r a m c re a t e s a f i l e w i t h t h e s pec i f i ed a t t r i butes ,
: e s t h i s i n f o rma t i o n before c h a ng i n g t h e f i l e a tt r i b u t e s b a c k
0
*/
I
I
l
#i n c l ude < �t d i o . h >
#i n c l ude <d o s . h >
'
v o i d ma i n ( >
(
'
u n s i g n e d o l d a t t r i b , n ewa t t r i b ;
i nt fh ;
I * Get a n d d i s p l a y f i l e a t t r i b u t e * /
_d os_g et � i l e a t t r < " DG F I LEAT . C " , & o l d a t t r i b > ;
p r i n t f ( [ Att r i b u t e : 0x% . 4x \ n " , o l d a t t r i b ) ;
i f ( ( o l r. a t t r i b & _A_RDON LY ) ! = 0 )
el s e
�
p r i n t ( " Re a d on l y fi l e \ n " ) ;
f
p r i n t ( " N ot a r e a d on l y f i l e . \ n " ) ;
I * Reset I f i l e a t t r i b u t e t o n o rma 1 fi l e * I
_d o s_s et i l e a t t r ( " DG F I LEAT . C " , _A_RDON LY ) ;
l
_d o s_g et i l e a t t r < " DG F I LEAT . C " , & n ewa t t r i b ) ;
p r i n t f ( ' A t t r i b u t e : 0x% . 4x \ n " , n ewa t t r i b l ;
I * Res t o e f i l e a t t r i bute * /
_d os_s et i l e a t t r ( " DG F I LEAT . C " , o l d a t t r i b l ;
_d o s_get i l e a t t r ( " DG F I L EAT . C " , & n ewa t t r i b ) ;
pri ntf( Att ri b u t e : 0x% . 4x \n " , n ew a t t r i b l ;
l
!
Output
l
;
Att r i b u t e : x0020
A t t r i b u t e : � x000 1
Not a read n l y fi l e .
Description Sets the date and time for a file, using system call INT Ox57.
#include <dos.h>
Remarks The _dos_setftime routine uses system call INT Ox57 to set the date and time at which the
file identified by handle was last written to. These values appear in the DOS date and time
fonnat, described in the following lists:
5- 10 Minutes (0 -59)
1 1-15 Hours (0 -23)
5 -8 Month (1-12)
Return Value If successful, the function returns 0. Otherwise, it returns the DOS error code and sets
errno to EBADF, indicating that an invalid file handle was passed.
_dos_se!ltime 230
Exampm __ -+��������������������������������
I * D G FT I M E . d : T h i s p r o g r a m d i s p l a y s a n d mod i f i e s t h e d a t e a nd t i me
!
ff
* f i el d s o a f i l e .
*/
{fi n c l ude
{fi n c l ude
q
<f ntl . h>
< s tjd i o . h>
{fi n c l ude < s tj d l i b . h >
#i n c l ude tj
<d s . h >
I
v o i d ma i n ( )
[
I * FEDC BA98 7 6 54 3 2 1 0 */
u n s i g n e d 1n ew_d a t e 0x 1 84f ; = I * 000 1 1 000 0 1 00 1 1 1 1 2/ 15/92 */
I * 0 1 00 1 000 1 1 1 0 0000 9 : 0 7 AM * /
p
u n s i g n ed r ew_t i me - 0x48e0 ;
u n s i gned l d_d a t e , o l d_t i me ;
I
i nt fh :
�
I * Open f l e wi t h _d os_open f u n c t i o n * /
i f ( _d os_ p pen ( " d g ft i me . obj " , O_RDO N LY , &fh ) ! = 0 )
exi t ( � > :
!
�
·�,
I * Get f i e d a t e a n d t i me * /
_d os_getft i me ( fh , &ol d_d a t e , &ol d_t i me ) ;
pri ntf( l d d a t e fi e l d : 0x% . 4x \ n " , o l d_d a t e ) ;
,
p r i n t f ( • l d t i me fi e l d : 0x% . 4 x \ n " , o l d_t i me ) ;
s y s t e m ( " i r dgft i me . obj " ) ;
I
\
I * Mod i fy fi l e d a t e a nd t i me * /
i f ( ! _d o s Ts e t ft i me ( fh , new_d a t e , new_t i me ) )
[
_d os_g + t ft i me ( fh , &n ew_d a t e , &n ew_t i me ) ;
p r i n t f ( " N ew d a t e fi e l d : 0x% . 4x \ n " , n ew_d a t e > ;
�
p r i n t f " N ew t i me f i e l d : 0x% . 4x \ n " , n ew_t i me > :
sy s t em , " d i r d g f t i me . obj " ) ;
t�
I * Res o r e d a t e a n d t i me * /
_d o s_s t ft i me ( f h , o l d_d a t e , o l d_t i me l ;
i
_d o s_c l o s C f h ) ; ,I
I
231 _dos_setflime
Output
Ol d date fi el d : 0x12cf
O l d t i me f i e l d : 0x94bb
V o l ume i n d r i v e C i s OS2
D i rectory of C : \ L I B R E F
V o l ume i n d r i v e C i s OS2
D i rectory o f C : \ L I B R E F
DIBl:l'/pl/an
\ Sets the current system time, using system call INT Ox2D.
#include <dos.h>
R1matlt1 The _dos_settime routine uses system call INT Ox2D to set the current system time to the
value stored in the dostime_t structure that time points to, as defined in DOS.H. The
dostime_t structure contains the following elements:
Element Description
unsigned char hour 0 -23
unsigned char minute 0 -59
unsigned char second 0 -59
unsigned char hsecond Hundredths of a second; 0 -99
RBlurn Value If successful, the function returns 0. Otherwise, it returns a nonzero value and sets ermo to
EINVAL, indicating an invalid time was specified.
Exampm �--+����---
I
1 * D ST I M E . c : T h i s p ro g r a m c h a n g e s t h e ti me a n d d a t e v a l ues a n d d i s p l a y s t h e
* n ew d a t e a nd t i me v a l u e s .
*/
/Ji n c 1 ude
#i n c l ude
#i n c l ude
�
< d o1 s . h >
< c i o . h>
< s t i o . h>
#i n c l ude <ti e . h>
233 _dos_ settime
v o i d ma i n ( )
(
s t r u c t d o s d a t e_t ol d d a t e , n ewd a t e 4 l , ( 7 l , ( 1 984 l l ;
3 l , ( 45 l , ( 30 l , ( 0 l l ;
=
s t r u c t d o s t i me_t o l d t i me , n ewt i me =
cha r d a t e b u f [ 40 J , t i meb u f [ 40 J ;
I * Get c u r r e n t d a t e a n d t i me v a l ues * /
_d o s_get d a t e ( & o l d d a t e ) ;
_d o s_g et t i me ( & o l d t i me ) ;
pri ntf( "%s % s \ n " , _s t rd a t e ( d a t e b u f ) , _s t rt i me ( t i mebuf ) ) ;
I * M o d i fy d a t e a nd t i me s t r u c t u res * /
_d o s_s e td a t e ( &newd a t e ) ;
_d o s_s e t t i me ( &newt i me ) ;
p r i n t f ( " %s % s \ n " , _s t rd a t e ( d a tebuf ) , _s t rt i me ( t i mebuf ) ) ;
I * R e s t o r e o l d d a t e a nd t i me * /
_d o s_s e t d a t e ( & o l d d a t e ) ;
_d os_sett i m� ( &ol d t i me ) ;
Output
06/ 15/89 1 8 : 2 6 : 09
0 7 / 04 / 84 03 : 4 5 : 30
234
Description Sets the current value of the interrupt vector, using system call INT Ox25.
#include <dos.h>
rupt vector intnum to the function pointed to by handler. Subsequently, whenever the
Remarks The dos setvect routine uses system call INT Ox25 to set the current value of the inter
intnum interrupt is generated, the handler routine will be called. If handler is a C function,
it must have been previously declared with the interrupt attribute. Otherwise, you must
make sure that the function satisfies the requirements for an interrupt-handling routine. For
example, if handler is an assembler function, it must be a far routine that returns with an
IRET instead of a RET.
The interrupt attribute indicates that the function is an interrupt handler. The compiler
generates appropriate entry and exit sequences for the interrupt-handling function, includ
ing saving and restoring all registers and executing an IRET instruction to return.
The _dos_setvect routine is generally used with the _dos_getvect function. To replace an
interrupt vector, first save the current vector of the interrupt using _dos_getvect. Then set
the vector to your own interrupt routine with _dos_setvect. The saved vector can later be
restored, if necessary, using _dos_setvect. The user-defined routine may also need the orig
inal vector in order to call it or to chain to it with _chain_intr.
When you call an interrupt function, the DS register is initialized to the C data segment.
This allows you to access global variables from within an interrupt function.
In addition, all registers except SS are saved on the stack. You can access these registers
within the function if you declare a function parameter list containing a formal parameter
for each saved register. The following example illustrates such a declaration:
2as dos_setvect
The formal parameters must appear in the opposite order from which they are pushed onto
the stack. You can omit parameters from the end of the list in a declaration, but not from
the beginning. For example, if your handler needs to use only DI and SI, you must still
provide ES and OS, but not necessarily BX or DX.
You can pass additional arguments if your interrupt handler will be called directly from C
rather than by an INT instruction. To do this, you must declare all register parameters and
then declare your parameter at the end of the list.
The compiler always saves and restores registers in the same, fixed order. Thus, no matter
what names you use in the formal parameter list, the first parameter in the list refers to ES,
the second refers to DS, and so on. If your interrupt routines will use in-line assembler,
you should distinguish the parameter names so that they will not be the same as the real
register names.
If you change any of the register parameters of an interrupt function while the function is
executing, the corresponding register contains the changed value when the function re
turns. For example:
_d i = -1;
This code causes the DI register to contain -1 when the handler function returns. It is not a
good idea to modify the values of the parameters representing the IP and CS registers in in
terrupt functions. If you must modify a particular flag (such as the carry flag for certain
DOS and BIOS interrupt routines), use the OR operator ( I ) so that other bits in the flag
register are not changed.
Since DOS is not reentrant (a DOS interrupt cannot be called from inside a DOS interrupt),
it is usually not safe to call from inside an interrupt function any standard library function
that calls DOS INT 2 1 H. Similar precautions apply to many BIOS functions. Functions
that rely on INT 2 1 H calls include 1/0 functions and the _dos family of functions. Func
tions that rely on the machine's BIOS include graphics functions and the _bios family of
functions. It is usually safe to use functions that do not rely on INT 2 1 H or BIOS, such as
string-handling functions. Before using a standard library function in an interrupt function,
be sure that you are familiar with the action of the library function.
#include <dos.h>
Remarks The _dos_write routine uses system call INT Ox40 to write data to the file that handle ref
erences; count bytes of data from the buffer to which buffer points are written to the file.
The integer pointed to by numwrt will be the number of bytes actually written, which may
be less than the number requested.
Do not use the DOS interface routines with the console, low-level, or stream 1/0 routines.
Retum Value If successful, the function returns 0. Otherwise, it returns the DOS error code and sets
errno to one of the following manifest constants:
Constant Meaning
EACCES Access denied (handle references a file not open for write
access)
EBADF Invalid file handle
I* DW R I T E . C : T h i s p r o g r a m u s e s DOS I / O f u n c t i o n s t o w r i t e t o a f i l e . * /
0
_das_wri e 2aa
v o i d ma i n ( )
{ l
c h a r o u t buffer [ J = " H e l l o " ;
i nt fh ;
u n s i g n e d n_w r i t t e n ;
1
�
I * Open i l e wi t h _d o s_c r e a t funct i on * /
f ( _d o s 1 c r e a t ( " d a t a " , _A_N O RMA L , &fh ) == 0 )
�
_d os_ r i t e ( f h , out =buff e r , 5 , &n_w r i t t e n > :
/ * W r i t e da t a wi t h d o s w r i t e f u n c t i on * /
I
p r i n t n < " N umber of c h a r a c t e r s w r i t t e n : % d \ n " , n_w r i tten > :
_d o s_cp o s e ( f h > :
p r i n t fi( " C onten t s of fi l e a re : \ n " > :
s y s t e ( " type d a t a " ) ;
Output
N umber of c h ra c t e r s w r i t t e n : 5
C o n t e n t s o f i l e a re :
Hel l o
239 dosexterr
#include <dos.h>
Remarks The dosexterr function obtains the extended error information returned by the DOS sys
tem call INT Ox59 and stores the values in the structure pointed to by errorinfo. This func
tion is useful when making system calls under DOS versions 3.0 or later, which offer
extended error handling.
The structure type DOSERROR is defined in DOS.ff. The DOSERROR structure contains
·
Element Description
Giving a NULL pointer argument causes dosexterr to return the value in AX without
filling in the structure fields. See MS-DOS Encyclopedia (Duncan, ed.; Redmond, WA:
Microsoft Press, 1 988) or Programmer's PC Sourcebook (Hogan; Redmond, WA:
Microsoft Press, 1988) for more information on the register contents.·
Return Value The dosexterr function returns the value in the AX register (identical to the value in the
exterror structure field).
The dosexterr function should be used only under DOS versions 3.0 or later.
dosexte r 240
Exampm �+-������-
1 * DOS E X E R . C : T h i s p r o g r a m t r i e s t o open t h e fi l e t e s t . d a t . I f t h e
* a ttempt d open opera t i on fa i l s , t h e p r o g r a m u s e s d o s e x t e r r t o d i s p l ay
* extende e r r o r i n fo rma t i o n .
*I
1
/ti n c l u d e < os . h>
/ti n c l u d e < o . h>
#i n c l u d e < cntl . h>
#i n c l ude < tdi o . h>
v o i d ma i n (
{ I
s t r u c t � O S E RRO R d o s e r r o r ;
i nt fd ; I
I
1
I * Atte � pt to open a n o n - ex i s t e n t fi l e * /
1
,
f ( C fd = open ( " N O S U C H F . I L E " , O_RDO N LY l l � -1
el s e
{
p r i n f ( " Open s u c c eeded s o n o extended i n forma t i on p r i n t ed \ n " l ;
c l o s ( fd l ;
Output I
E r ro r : 2 � l ass : 8 Ac t i o n : 3 Locus : 2
I
I
241 dup, dup2
Description Create a second handle for an open file (dup), or reassign a file handle (dup2).
Remadts The dup and dup2 functions cause a second file handle to be associated with a currently
open tile. Operations on the file can be carried out using either file handle. The type of
access allowed for the file is unaffected by the creation of a new handle.
The dup function returns the next available file handle for the given file. The dup2 func
tion forces handle2 to refer to the same file as hand/el . If handle2 is associated with an
open file at the time of the call, that file is closed.
Retum Value The dup function returns a new file handle. The dup2 function returns 0 to indicate
success. Both functions return -1 if an error occurs and set ermo to one of the following
values:
Value Meaning
EBADF Invalid file handle
EMFILE No more file handles available (too many open files)
I* D U P . C : T h i s p r o g r a m u s e s t h e v a r i a b l e o l d t o s a v e t h e o r i g i n a l
* I t t h en o p e n s a n ew f i l e named n ew a nd f o r c e s s t d o u t to refer
stdout .
* t o i t . Fi n a l l y , i t r e s t o res s t d out t o i t s o r i g i n a l s t a t e .
*I
//i n c l u d e < i o . h >
#i n c l u d e < s t d l i b . h >
#i n c l u d e < s t d i o . h >
242
v o i d ma i n < > •
!
i n t o l d ; I;
FI LE *ne · ; l
ol d = du ( 1 l ; / * " o l d " n ow refe rs t o " s t d o u t " * /
I * Note : fi l e h a n d l e 1 � " s tdout " * /
i f ( ol d += -1 >
f
(
'
I
p e r r o ( " d up ( 1 > fa i l u re " l ;
exi t ( l l l ;
(
p ut s ( " C a n ' t open f i l e ' d a t a ' \ n " ) ;
exi t ( 1 l ;
{
I * s t d o u n ow refe r s t o fi l e " d a t a " * /
i f ( - 1 =t d u p 2 ( f i l eno ( new ) , 1 ) )
(
1
I
p e r r o r. ( " C a n ' t d u p 2 s t d o u t " > :
ex i t ( 1 ) ;
I
puts ( "T�i s goes to fi l e ' data ' \ r\ n " ) ;
i
/ * Fl u s h i s t d o u t s t r e a m buffer s o i t goes t o c o r rect f i l e * /
ffl u s h ( � t d o u t > :
fc l o s e < � ew l ;
:!
Output
I
243 ecvt
Description Converts a double number to a string.
char *ecvt( double value, int count, int *dee, int *sign );
Remarks The ecvt function converts a floating-point number to a character string. The value argu
ment is the floating-point number to be converted. The ecvt function stores up to count
digits of value as a string and appends a null character ('\0'). If the number of digits in
value exceeds count, the low-order digit is rounded. If there are fewer than count digits,
the string is padded with zeros.
Only digits are stored iQ the string. The position of the decimal point and the sign of value
can be obtained from dee and sign after the call. The dee argument points to an integer
value giving the position of the decimal point with respect to the beginning of the string. A
0 or negative integer value indicates that the decimal point lies to the left of the first digit.
The sign argument points to an integer indicating the sign of the converted number. If the
integer value is 0, the number is positive. Otherwise, the number is negative.
The ecvt and fcvt functions use a single statically allocated buffer for the conversion. Each
call to one of these routines destroys the result of the previous call.
Return Value The ecvt function returns a pointer to the string of digits. There is no error return.
I* E C VT . C : T h i s p ro g r a m u s e s e c v t
* n umber t o a c h a ra c t e r s t r i ng .
t o c o n v e rt a fl oa t i n g - p o i nt
*I
#i n c l ude < s t d l i b . h >
#i n c l ude < s t d i o . h >
ecvt 2u
l
v o i d ma i n ( )
(
i nt ec i ma l , s i g n ;
char b u f fe r :
j
i
i nt r ec i s i on = l fil ;
doubl e ource = 3 . 141 5926535 ;
I
,
Output
#include <graph.h>
short _far _ellipse( short control, short xl, short yJ, short x2, short y2 );
short _far _ellipse_w( short control, double wxl, double wyl, double wx2,
double wy2 ) ;
short _far _ellipse_wxy( short control, struct _wxycoord _far *pwxyl,
struct _wxycoord _far *pwxy2 );
Remarks The _ellipse functions draw ellipses or circles. The borders are drawn in the current color.
In the _ellipse function, the center of the ellipse is the center of the bounding rectangle de
fined by the view-coordinate points (xl , yl) and (x2, y2).
In the _ellipse_w function, the center of the ellipse is the center of the bounding rectangle
defined by the window-coordinate points (wxl, wyl) and (wx2, wy2).
In the _ellipse_wxy function, the center of the ellipse is the center of the bounding rec
tangle defined by the window-coordinate pairs (pwxyl) and (pwxy2).
Constant Action
_GFILLINTERIOR Fills the ellipse using the current fill mask
_GBORDER Does not fill the ellipse
I
I
Relum Value The _ellipse functions return a nonzero value if the ellipse is drawn successfully; other
wise, they return 0.
See A/sa · _arc functions, _floodml, _grstatus, _lineto functions, _pie functions,
_polygon functions, _rectangle functions, _setcolor, _settillmask
Exam�• ---+---
v o i d ma i n ( )
{
I* Fi nd l
v a l i d g r a p h i c s mod e . * I
\
i f ( ! _s e v i d eomod e C _MA X RESMOOE )
ex i t ( 1 ) ;
_e l l i ps e _G F I L L I NT E R I O R , 80 , 50 , 240 , 1 50 ) ;
r
/ * S t r i k a ny key to c l ea r s c reen . * /
getc h C ) ;
_s e t v i d e mod e ( _O E FAU LTMO O E ) ;
247 _enable
#include <dos.h>
Rsmatks The _enable routine enables interrupts by executing an 8086 STI machine instruction.
The OS/2 function DosE:xit should not be used to tenninate threads created by the
_beginthread function. If DosE:xit is used, the results are unpredictable.
Remades The eof function determines whether the end of the file associated with handle has been
reached.
Retum Value The eof function returns the value 1 if the current position is end-of-file, or 0 if it is not. A
return v alue of -1 indicates an error; in this case, errno is set to EBADF, indicating an
invalid file handle.
/ * E O F . C : T h i s p r o g r a m r e a d s d a t a from a f i l e ten by t e s a t a t i me
* u n t i l t h e e n d of t h e f i l e i s rea c h ed o r a n e r r o r i s e n c o u n t e red .
*I
v o i d ma i n ( )
{
i n t f h , c o u n t , t ota l = 0 ;
c h a r b u f [ 10 ] ;
t
p e r o r ( " Re a d e r r o r • ) ;
bre k ;
I* Tot up a c t u a l bytes r e a d * /
tot a 1 count ;
Output
int execl( char *cmdname, char *argO, ... char *argn, NULL );
int execle( char *cmdname, char *argO, ... char *argn, NULL, char **envp ) ;
int execlp( char *cmdname, char *argO, . char *argn, NULL );
..
int execlpe( char *cmdname, char *argO, . . char *argn, NULL, char **envp );
.
Remarks The exec functions load and execute new child processes. When the call is successful in
DOS, the child process is placed in the memory previously occupied by the calling
process. Under OS/2, calling an exec function is equivalent to calling the corresponding
function with the P_NOWAITO argument specified, followed by a call to the exit function.
Sufficient memory must be available for loading and executing the child process.
All of the exec functions use the same operating system function. The letter(s) at the end
of the function name determine the specific variation, as shown in the following list:
Letter Variation
e An array of pointers to environment arguments is explicitly
passed to the child process.
Command-line arguments are passed individually to the exec
function.
p Uses the PATH environment variable to find the file to be
executed
v Command-line arguments are passed to the exec function as
an array of pointers.
252
I The cmdname argument specifies the file to be executed as the child process. It can specify
II
a full path (from the root), a partial path (from the current working directory), or just a file
name. If cmdname does not have a file-name extension or does not end with a period (.),
1 the exec function searches for the named file; if the search is unsuccessful, it tries the same
base name, first with the extension .COM, then with the extension .EXE. If cmdname has
an extension, only that extension is used in the search. If cmdname ends with a period, the
exec calls search for cmdname with no extension. The execlp, execlpe, execvp, and
execvpe routines search for cmdname (using the same procedures) in the directories
specified by the PATH environment variable.
If cmdname contains a drive specifier or any slashes (i.e., if it is a relative path name), the
exec call searches only for the specified file and no path searching is done.
Arguments are passed to the new process by giving one or more pointers to character
strings as arguments in the exec call. These character strings form the argument list for the
child process. The combined length of the strings forming the argument list for the new
process must not exceed 1 28 bytes (in real mode only). The terminating null character
('\0') for each string is not included in the count, but space characters (inserted automat
ically to separate the arguments) are counted.
The argument pointers can be passed as separate arguments (execl, execle, execlp, and
execlpe) or as an array of pointers (execv, execve, execvp, and execvpe). At least one ar
gument, argO, must be passed to the child process; this argument is argv[O] of the child
process. Usually, this atgument is a copy of the cmdname argument. (A different value
will not produce an error.) Under versions of DOS earlier than 3.0, the passed value of
argO is not available for use in the child process. However, under OS/2 and under DOS
versions 3.0 and later, cmdname is available as argO.
The execl, execle, execlp, and execlpe calls are typically used when the number of argu
ments is known in advance. The argument argO is usually a pointer to cmdname. The argu
ments argl through argn point to the character strings forming the new argument list. A
null pointer must follow argn to mark the end of the argument list.
The execv, execve, execvp, and execvpe calls are useful when the number of arguments to
the new process is variable. Pointers to the arguments are passed as an array, argv. The ar
gument argv[O] is usually a pointer to cmdname. The arguments argv[ l ] through argv[n]
point to the character strings forming the new argument list. The argument argv[n+ 1 ] must
be a NULL pointer to mark the end of the argument list.
Files that are open when an exec call is made remain open in the new process. In the execl,
execlp, execv, and execvp calls, the child process inherits the environment of the parent.
The execle, execlpe, execve, and execvpe calls allow the user to alter the environment for
the child process by passing a list of environment settings through the envp argument. The
argument envp is an array of character pointers, each element of which (except for the
final element) points to a null-terminated string defining an environment variable. Such a
string usually has the form
253 exec Functions
NAME=value
where NAME is the name of an environment variable and value is the string value to which
that variable is set. (Note that value is not enclosed in double quotation marks.) The final
element of the envp array should be NULL. When envp itself is NULL, the child process in
herits the environment settings of the parent process.
A program executed with one of the exec family of functions is always loaded into
memory as if the "maximum allocation" field in the program's .EXE file header is set to
the default value of OFFFFH. You can use the EXEMOD utility to change the maximum
allocation field of a program; however, such a program invoked with one of the exec func
tions may behave differently from a program invoked directly from the operating-system
command line or with one of the spawn functions.
The exec calls do not preserve the translation modes of open files. If the child process
must use files inherited from the parent, the setmode routine should be used to set the
translation mode of these files to the desired mode.
You must explicitly flush (using mush or flushall) or close any stream prior to the exec
function call.
Signal settings are not preserved in child processes that are created by calls to exec
routines. The signal settings are reset to the default in the child process.
Return Value The exec functions do not normally return to the calling process. If an exec function re
turns, an error has occurred and the return value is - 1 . The errno variable is set to one of
the following values:
Value Meaning
E2BIG The argument list exceeds 128 bytes, or the space required for
the environment information ex"eeds 32K.
EACCES The specified file has a locking or sharing violation
(OS/2, and DOS versions 3.0 or later).
EMFILE Too many files open (the specified file must be opened to de
termine whether it is executable).
ENOENT File or path name not found.
ENOEXEC The specified file is not executable or has an invalid
executable-file format.
ENOMEM Not enough memory is available to execute the child process;
or the available memory has been corrupted; or an invalid
block exists, indicating that the parent process was not allo
cated properly.
exec Fu ctions 254
Because of differences in DOS versions 2.0 and 2. 1 , child processes generated by the exec
family of functions (or by the equivalent spawn functions with the P_OVERLAY argu
ment) may cause fatal system errors when they exit. If you are running DOS 2.0 or 2. 1 ,
you must upgrade to DOS version 3.0 or later to use these functions.
Bound programs cannot use the exec family of functions in real mode.
See Also abort, atexit, exit, _exit, onexit, spawn functions, system
!
/ * E X E C . C : T h i s p r o g r a m a c cepts a n umbe r i n t h e r a n g e 1 t h ro u g h 8 f rom t h e
* c omma n d l i n e . B a s ed on t h e n umb e r i t r e c e i ves , i t executes one of t h e
* e i g h t d i f f e rent p r o c ed u re s t h a t s pawn t h e p r o c e s s n a med c h i l d . For
* s ome of these p r o c e d u r e s , t h e c h i l d . exe f i l e must be i n t h e s a m e
* d i r e c t o y ; for o t h e r s , i t need o n l y be i n t h e s a me p a t h .
*I
�
'!
c h a r *my_e v [ J = (
" TH I S=e n v i ronment wi l l be " ,
" PASS E D=to c h i l d . ex e by t h e " ,
" EX EC L E=a nd " ,
" EX E C L P E=a nd " ,
" E X E C V E=a n d " ,
" EX E C V P E=funct i on s • ,
NULL
I:
v o i d ma i n ( i n t a rg c , c h a r *a r g v [ J )
( I
T�
cha r *a s [4] :
i nt r e s u l t ;
I
I I
255 exec FuncUons
Remal'ks The exit and _exit functions tenninate the calling process. The exit function first calls, in
LIFO (last-in-first-out) order, the functions registered by atexit and onexit, then flushes
all file buffers before tenninating the process. The _exit function tenninates the process
without processing atexit or onexit functions or flushing stream buffers. The status value
is typically set to 0 to indicate a nonnal exit and set to some other value to indicate an
error.
Although the exit and _exit calls do not return a value, the low-order byte of status is
made available to the waiting parent process, if one exists, after the calling process exits.
The status value is available to the operating-system batch command ERRORLEVEL.
The behavior of the exit, _exit, _cexit, and _c_exit functions is as follows:
Function Action
Compatibility exit
exit
See Also abort, atexit, _cexit, exec functions, onexit, spawn functions, system
I * E X I T E R . C : T h i s p r o g r a m p rompts t h e u s e r f o r a y e s o r n o a n d re t u r n s
* a DOS e r r o r c o d e o f 1 i f t h e u s e r a n swers Y o r y ; o t h e rw i s e i t
* r e t u r n s 0 . T h e e r r o r code c o u l d be tested i n a b a t c h f i l e .
*/
v o i d ma i n ( )
(
char ch ;
exp, ex / �I 258
#include <math.h>
x Floating-point value
Remarks The exp and expl functions return the exponential function of their floating-point argu
ments (x).
The expl function is the 80-bit counterpart; it uses an 80-bit, 10-byte coprocessor form of
arguments and return values. See the reference page on the long double functions for more
details on this data type.
Return Value These functions return ex. The functions return HUGE_VAL on overflow and set errno to
ERANGE; on underflow, they return 0 but do not set errno.
Compatibility exp
expI
i
I* EXP . C */
#i n c l u d e <ma t h . h>
#1 n c 1 " d e < d 1 o . h>
259 exp, exp/
v o i d ma i n ( )
(
d o u b l e x = 2 . 30258509 3 , y;
y = ex p ( x l ;
p r i n t f ( • ex p ( % f l = % f \ n " , x , y l;
Output
Remarks The _expand family of functions changes the size of a previously allocated memory block
by attempting to expand or contract the block without moving its location in the heap. The
memblock argument points to the beginning of the block. The size argument gives the new
size of the block, in bytes. The contents of the block are unchanged up to the shorter of the
new and old sizes.
The memb/ock argument can also point to a block that has been freed, as long as there has
been no intervening call to calloc, _expand, malloc, or realloc. If memblock points to a
freed block, the block remains free after a call to one of the _expand functions.
The seg argument is the segment address of the _based heap.
In large data models (compact-, large-, and huge-model programs), _expand maps to
_fexpand. In small data models ( tiny-, small-, and medium-model programs), expand
maps to _nexpand.
The various _expand functions change the size of the storage block in the data segments
shown in the list below:
Function Data Segment
Return Value The _expand family of functions returns a void pointer to the reallocated memory
block. Unlike realloc, _expand cannot move a block to change its size. This means the
memblock argument to _expand is the same as the return value if there is sufficient
memory available to expand the block without moving it.
With the exception of the _bexpand function, these functions return NULL if there is in
sufficient memory available to expand the block to the given size without moving it. The
_bexpand function returns _NULLOFF if insufficient memory is available. The item
pointed to by memblock will have been expanded as much as possible in its current
location.
The storage space pointed to by the return value is guaranteed to be suitably aligned for
storage of any type of object. The new size of the item can be checked with the _msize
function. To get a pointer to a type other than void, use a type cast on the return value.
See Also calloc functions, free functions, malloc functions, _msize functions, realloc functions
Exampm ��
��
/ * EX PAND . C * /
#i n c l u d e < s t d i o . h >
#i n c l u d e <ma l l oc . h>
#i n c l u d e < s t d l i b . h>
v o i d ma i n ( )
(
c h a r *bufc ha r ;
I * Free memo ry * /
f r e e ( b u fc h a r ) ;
exi t ( 0 ) :
1 I
_expan Functions 262
Output
�
Al l o c a t e a 1 2 el ement buffer
Al l o c a t e d 5 2 by tes a t 0067 : 142A
Expa nded bl c k to 1024 by tes a t 0067 : 142A
263 labs, labs/
#include <math.h>
x Floating-point v alue
Remalks The fabs and fabsl functions calculate the absolute value of their floating-point arguments.
The fabsl function is the 80-bit counterpart; it uses an 80-bit, 1 0-byte coprocessor form of
arguments and return values. See the reference page on the long double functions for more
details on this data type.
Relum Value These functions return the absolute value of their arguments. There is no error return.
Campallbillty fabs
fabsl
I
v o i d ma i n ( ) I
1 XI = - 4 , 1 y ;
1 ·
.
·
1 nt
h
l ong
j -41567 L , l y ;
=
d o u b l e d = - 3 . 1 4 1 5 9 3 , dy ;
t
i y = abs ( i x l ;
p r i n t f ( T h e a b s o l ute v a l ue o f %d i s % d \ n " , i x , i y ) ;
p r i n t f ( h h e a b s o l ute v a l ue o f % l d i s %l d \ n " , l x , l y l ;
l y = l a b$ < l x l :
l
dy = f a b� ( dx l ;
p r i n t f ( T h e a b s o l ute v a l ue of %f i s %f\ n " , dx , d y l ;
Output
I
T h e a b s o l ut � v a l ue o f -4 i s 4
t
T h e a bs o l ute v a l ue o f - 4 1 567 i s 4 1 5 6 7
T h e a bs o l u t v a l ue o f - 3 . 1 4 1 5 9 3 i s 3 . 1 4 1 5 9 3
265 fclose, fcloseall
#include <Stdio.h>
Remarks The fclose function closes stream. The fcloseall function closes all open streams except
stdio, stdout, stderr (and in DOS, stdaux and stdprn). It also closes and deletes any tem
porary files created by tmpfile.
In both functions, all buffers associated with the stream are flushed prior to closing.
System-allocated buffers are released when the stream is closed. Buffers assigned by the
user with setbuf and setvbuf are not automatically released.
Return Value The fclose function returns 0 if the stream is successfully closed. The fcloseall function re
turns the total number of streams closed. Both functions return EOF to indicate an error.
Compallblllty fclose
fcloseall
#i n c l u d e < s t d i o . h >
!close, �closeall 266
1I
F I L E * s t r a m , * s t ream2 ;
C1
v o i d ma i n >
{ I
i nt n ull!c l o s ed ;
1
i f ( < s � ream
I * Ope f o r r e a d ( w i l l fa i l i f ' d a t a d o e s not e x i s t ) * /
fopen < " d a t a • , • r • ) )
= NULL )
=
J
p r i t f ( " T h e f i l e ' d a ta ' wa s not opened \ n " > :
el s e
1
p r i t f ( " T h e fi l e ' d a t a ' w a s opened \ n " ) ;
1
I * Ope for wri te * /
i f ( < s r e a m2 = fopen ( " da t a 2 " , • w+• ) ) == N U L L
p r i t f ( " T h e f i l e ' da t a 2 ' wa s n o t opened \ n " > :
el s e
l
p r i ntf ( " T h e f i l e ' d a t a 2 ' wa s opened \ n " > :
/ * C l o � e s t re a m * /
i f ( f c ' os e ( s t re a m )
p r i t f ( " T h e f i l e ' d a ta ' wa s not c l o s ed \ n " > :
I * Al l ot h e r f i l e s a re c l o s e d : * /
�
numc l o sed f c l o s ea l l ( ) ;
=
I
I
Output
�
T h e fi l e · a t a ' wa s opened
T h e f i l e ' d a t a 2 ' wa s opened
N umber o f , f i l e s c l o s e d by f c l o s e a l l : 1
267 fcvt
char *fcvt( double value, int count, int *dee, int *sign );
Remarks The fcvt function converts a floating-point number to a null-terminated character string.
The value argument is the floating-point number to be converted. The fcvt function stores
the digits of value as a string and appends a null character ('\0'). The count argument speci
fies the number of digits to be stored after. the decimal point. Excess digits are rounded off
to count places. If there are fewer than count digits of precision, the string is padded with
zeros.
Only digits are stored in the string. The position of the decimal point and the sign of value
can be obtained from dee and sign after the call. The dee argument points to an integer
value; this integer value gives the position of the decimal point with respect to the begin
ning of the string. A zero or negative integer value indicates that the decimal point lies to
the left of the first digit. The argument sign points to an integer indicating the sign of
value. The integer is set to 0 if value is positive and is set to a nonzero number if value is
negative.
The ecvt and fcvt functions use a single statically allocated buffer for the conversion. Each
call to one of these routines destroys the results of the previous call.
Return Value The fcvt function returns a pointer to the string of digits. There is no error return.
3 . 1415926535
268
�
#i n c l ude < t d l i b . h >
J
#i n c l ude < t d i o . h >
v o i d ma i n O
(
i n t d e i ma l , s i g n :
c h a r *b ffe r :
doubl e ource = 3 . 141 5926535 :
Output
#include <Stdio.h>
Remarks The fdopen func�ion associates an input/output stream with the file identified by handle,
thus allowing a file opened for "low-level" 1/0 to be buffered and fonnatted. (See Section
2.7, "Input and Output," for an explanation of stream 1/0 and low-level 1/0.) The mode
character string specifies the type of access requested for the file, as shown below. The fol
lowing list gives the mode string used in the fopen and fdopen functions and the corre
sponding oflag arguments used in the open and sopen functions. A complete description
of the mode string argument is given in the remarks section of the fopen function.
In addition to the values listed above, one of the following characters can be included in
the mode string to specify the translation mode for newlines. These characters correspond
to the constants used in the open and sopen functions, as shown below:
If t or b is not given in the mode string, the translation mode is defined by the default
mode variable _fmode.
fdapen 270
The t option is not part of the ANSI standard for fopen and fpopen, but is instead a
Microsoft extension and should not be used where ANSI portability is desired.
Return Value The fdopen function returns a pointer to the open stream. A null pointer value indicates an
error.
I * FDO P E N . C 1 T h i s p r o g r a m opens a f i l e u s i ng l ow - l e v e l I / O , t h e n u s e s
* fdopen t swi t c h t o s t ream a c c e s s . I t c o u n t s t h e l i n e s i n t h e f i l e .
*I
�oi d ma i n ( )
I
F I L E * s t e a rn :
i nt f h , c o u n t = 0 ;
c h a r i nb f [ 128J ;
I * Open f i l e h a nd l e . */
i f ( ( fh open ( " fdopen . c " , O_RDON LY ) ) == - 1
exit ( 1 ) :
I * C h a n g h a n d l e a c c e s s to s t r e a m a c c e s s . * /
i f ( C s t r a m = fdopen ( f h , • r • ) ) � NULL )
exi t ( 1 ) :
tt s (
[
whi l e( f i n b u f , 1 28 , s t ream ) ! = N U L L
count :
I
271 fdopen
I * Aft e r f d o p e n , c l o s e w i t h fc l o s e , n o t c l o s e . */
fc l os e { s t ream > :
Output
Li nes i n fi l e : 31
feat 272
#include <stdio.h>
Remarks The feof routine (implemented as a macro) determines whether the end of stream has been
reached. Once the end of the file is reached, read operations return an end-of-file
indicator until the stream is closed or until rewind, fsetpos, fseek, or clearerr is called
i
against it.
I
Return Vala � The feof function returns a nonzero value after the first read operation that attempts to read
past the end of the file. It returns 0 if the current position is not end-of-file. There is no
I
error return.
Exampre ___.���
I
*I
#i n c l u d e � s t d i o . h >
#i n c l u d e f s t d l i b . h >
v o i d ma i n ( )
i I
i nt crunt , tota l = 0;
c h a r b � f fe r [ 1 0 0 J ;
F I LE *� tream ;
I * Tot a l u p a c t u a l byt e s r e a d * /
t ot a l +- c ount :
)
p r i n t f { " N umb e r o f byt e s read = Sd \ n " , tota l > ;
f c l o s e < s t ream > :
Output
Numb e r of byt e s r e a d = 6 9 7
terror 274
#include <Stdio.h>
Remarks The ferror routine (implemented as a macro) tests for a reading or writing error on the file
associated with stream. If an error has occurred, the error indicator for the stream remains
set until the stream is closed or rewound, or until clearerr is called against it.
Return Value If no error has occurred on stream, ferror returns 0. Otherwise, it returns a nonzero value.
Output
#include <Stdio.h>
Remarks If the file associated with stream is open for output, mush writes to that file the contents
of the buffer associated with the stream. If the stream is open for input, mush clears the
contents of the buffer. The mush function negates the effect of any prior call to ungetc
against stream.
Buffers are automatically flushed when they are full, when the stream is closed, or when a
program terminates normally without closing the stream.
The stream remains open after the call. The mush function has no effect on an unbuffered
stream.
Return Value 1 The mush function returns the value 0 if the buffer was successfully flushed. The value 0
is also returned in cases in which the specified stream has no buffer or is open for reading
only. A return value of EOF indicates an error.
/ * FFLUSH . C */
#i n c l ude < s d i o . h >
#i n c l ude < c n i o . h >
; ' ' ; :; : ; ; 1 : 1 . 1 :
211 fflush
/ * Read ea c h word a s a s t r i ng . * /
p r i n t f C " En t e r a s e n t e n c e of f o u r words w i t h s c a n f : • > :
fo r e i n t e g e r 0 ; i n t e g e r < 4 ; i n teger++ >
(
=
I*
pri ntfC "%s\n " , stri ng > :
Output
E n t e r a s e n t e n c e of f o u r w o r d s w i t h s c a n f : T h i s i s a t e s t
Thi s
is
a
test
E n t e r t h e s a me s entence w i t h gets : T h i s i s a t e s t
Thi s i s a test
tgett:, fgttt:har I
218
#include <Stdio.h>
Rematits The fgetc function reads a single character from the current position of the file associated
with stream. The character is converted and returned as an int The function then incre
ments the associated file pointer (if any) to point to the next character. The fgetchar func
tion is equivalent to fgetc(stdin).
The fgetc and fgetchar routines are identical to getc and getchar, but they are functions
rather than macros.
Retum Value The fgetc and fgetchar functions return the character read. They return EOF to indicate an
error or end-of-file. Use feof or ferror to distinguish between an error and an end-of-file
condition. ·
Campallbll/ly fgetc
fgetchar
l
Exampm
!
__ -+------------------------------------------------------------------------------------------------------------------------ -
I
279 fgetc, fgetchar
v o i d ma i n ( )
{
F I L E * s t re a m ;
c h a r buffe r [ 8 1 ] ;
i nt i , ch ;
Output
#include <Stdio.h>
Rematks The fgetpos function gets the current value of the stream argument's file-position indicator
and stores it in the object pointed to by pos. The fsetpos function can later use infonnation
stored in pos to reset the stream argument's pointer to its position at the time fgetpos was
called.
The pos v alue is stored in an internal fonnat and is intended for use only by the fgetpos
and fsetpos functions.
Return Value If successful, the fgetpos function returns 0. On failure, it returns a nonzero value and sets
errno to one of the following manifest constants (defined in STDIO.H):
Constant Meaning
v o i d ma i n ( )
(
FI LE * s t rea m ;
f p o s_t p o s ;
i nt val ;
cha r b u f fe r [ 20 ] ;
I * S e t a n ew p o s i t i o n a n d r e a d mo r e d a t a * /
p o s = 140 ;
i f ( fsetpo s ( s t ream , &pos ) ! = 0 )
p e r ro r < " fsetpos e r ro r " > :
f r e a d ( b u f fe r , s i z e o f ( c h a r ) , 1 0 , s t r e a m > :
p r i n t f ( " 1 0 by t e s a t by t e % l d : % . 1 0 s \ n " , p o s , b u f f e r > :
f c l o s e ( s t re a m ) ;
Output
1 0 by t e s a t by t e 1 0 : .C: Thi s p
10 bytes a t byte 140 : FI LE *
fgets 282
#include <Stdio.h>
RemalkB The fgets function reads a string from the input stream argument and stores it in string.
Characters are read from the current stream position up to and including the first newline
character ('\n '), up to the end of the stream, or until the number of characters read is equal
to n 1 , whichever comes first. The result is stored in string, and a null character ('\0') is
-
appended. The newline character, if read, is included in the string. If n is equal to l , string
is empty ( " "). The fgets function is similar to the gets function; however, gets replaces the
newline character with NULL.
Retum Value If successful, the fgets function returns string. It returns NULL to indicate either an error or
end-of-file condition. Use feof or ferror to determine whether an error occurred.
F I L E * s t re a m ;
v o i d ma i n ( )
{
c h a r l i n e [ 0 0 ] , * res u l t ;
283 !gets
i f ( ( st r e a m = fopen C " fg e t s . c • , • r • ) ) ! = N U L L
(
i f ( fget s ( l i n e , 100 , s t re a m l == NU L L )
p r i n t f ( " fgets e r r o r \ n " > :
el se
pri ntf( " %s " , 1 i ne l :
fc l o s e ( s t ream > :
Output
Dest:rlplion Convert floating-point numbers between IEEE and Microsoft binary fonnats.
I
I
#include <math.h>
I
int fieeetomsbin( float *src4, float *dst4 );
int fmsbintoieee( float *src4, float *dst4 );
Remades The fieeetomsbin routine converts a single-precision floating-point number in IEEE (Insti
tute of Electrical and Electronic Engineers) fonnat to Microsoft (MS) binary fonnat.
These routines allow C programs (which store floating-point numbers in the IEEE fonnat)
to use numeric data in random-access data files created with Microsoft BASIC (which
stores floating-point numbers in the Microsoft binary fonnat), and vice versa.
The argument src4 points to the float value to be converted. The result is stored at the loca
tion given by dst4.
These routines do not handle IEEE NANs ("not a number") and infinities. IEEE denonnals
are treated as 0 in the conversions.
Retum Value These functions return 0 if the conversion is successful and 1 if the conversion causes an
overflow.
Remarks The filelength function returns the length, in bytes, of the target file associated with
handle.
Return Value The filelength function returns the file length in bytes. A return value of - I L indicates an
error, and an invalid handle sets errno to EBADF.
I * C H S I Z E . C : T h i s p r o g r a m u s e s f i l e l ength t o report t h e s i z e of a
* f i l e before a nd a ft e r mod i fy i n g i t w i t h c h s i z e .
*I
v o i d ma i n ( )
(
i n t f h , res u l t ;
u n s i gned i nt n by t e s = BUFSI Z :
286
�
open ( " d a ta " , O_RDWR I O_C R EAT , S_I READ I S_I W R I T E ) ) ! = - 1 )
1
I * Open fi l e */
i f ( ( fh r
1 pri nt �< " F i l e l en g t h before : z 1 d \ n " , f i l e l en gt h < fh ) ) ;
f
if( c s i ze( fh , 329678 ) � 0 >
pr n t f { " S i z e s u c c e s s f u l l y c h a n g ed \ n " > ;
el se
pr n t f ( " P robl em i n c h a n g i n g t h e s i z e \ n " ) ;
pri nt ( " Fi l e l en g t h a ft e r : % l d \ n " , f i l e l engt h ( fh ) ) ;
cl ose fh > ;
) I
I
r\
Output
F i l e l en g t h before : 0
S i z e s u c c e s f u l l y c h a nged
F i l e l en g t h a ft e r : 329678
I
I
287 fileno
#include <Stdio.h>
Remal'ks The fileno routine returns the file handle currently associated with stream. This routine is
implemented as a macro.
Retum Value The fileno routine returns the file handle. There is no error return. The result is undefined
if stream does not specify an open file.
I * F I L E N O . C : T h i s p r o g r a m u s e s fi l eno to obta i n t h e f i l e h a n d l e f o r
* s ome s t a n d a rd C s t reams .
*I
v o i d ma i n ( )
{
p r i ntf C " T h e fi l e h a n d l e f o r s t d i n i s % d \ n " , f i l en o C s td i n ) ) ;
p r i ntf ( " T h e f i l e h a n d l e f o r s t d o u t i s %d \ n " , f i l e n o C s t d o u t > ) ;
p r i n t f ( " T h e f i l e h a n d l e f o r s t d e r r i s %d \ n " , f i l eno ( s t d e r r ) ) ;
Output
T h e f i l e h a n d l e for s td i n i s 0
T h e f i l e h a n d l e fo r s t d o u t i s 1
T h e f i l e h a n d l e fo r s t d e r r i s 2
_floodfill, floodfill_w 288
Descrlpllan Fill an area of a display using the current color and fill mask
#include <graph.h>
x, y Start point
Remarks The functions in the _floodfill family fill an area of the display, using the current color and
fill mask. The _ftoodfill routine begins filling at the view-coordinate point (x, y). The
_floodfill_w routine begins filling at the window-coordinate point (wx, wy).
If this point lies inside the figure, the interior is filled; if it lies outside the figure, the back
ground is filled. The point must be inside or outside the figure to be filled, not on the fig
ure boundary itself. Filling occurs in all directions, stopping at the color of boundary.
Retum Value The floodfill functions return a nonzero value if the fill is successful. It returns 0 if the fill
could not be completed, the starting point lies on the boundary color, or the start point lies
outside the clipping region.
See Also _ellipse functions, _getcolor, _getfillmask, _grstatus, _pie functions, _setfillmask,
_setcliprgn, _setcolor
i
*I
I
I
#i n c l u d e < c on · o . h >
#i n c l u d e < s t d l i b . h >
#i n c l u d e < g ra h . h >
I
I
289 _lloodfill, _lloodfill_w
v o i d ma i n ( )
(
i n t l oop ;
i nt xva r , yva r ;
I * f i n d a v a l i d g r a p h i c s mod e * /
i f ( ! _s et v i d eomod e ( _MA X C O LO RMODE l l
exi t ( 1 l ;
#include <math.h>
x Floating-point value
Remarks The floor and floorl functions return a floating-point value representing the largest integer
that is less than or equal to x.
The floorl function is the 80-bit counterpart, and it uses the 80-bit, I O-byte coprocessor
fonn of arguments and return values. See the reference page on the long double functions
for more details on this data type.
Return Value These functions return the floating-point result. There is no error return.
Compal/blllty floor
floorI
{
#i n c l u d e <ma h . h >
# i n c l u d e < s t� i o . h >
291 floor, floor/
v o i d ma i n ( }
(
doubl e y ;
y = fl oo r ( 2 . 8 > :
p r i ntf( "The fl oor of 2 . 8 i s %f\n " , y > :
y = fl oo r c · - 2 . 8 > :
p r i ntf ( " T h e fl oor o f - 2 . 8 i s %f\ n " , y } ;
y = cei 1 ( 2 .8 ) :
p r i n t f ( " T h e c e i l of 2 . 8 i s % f \ n � . y > :
y = cei l ( -2 . 8 > :
p r i n t f ( " T h e c e i l of - 2 . 8 i s % f \ n " , y > :
Output
The fl o o r of 2 . 8 i s 2 . 000000
The fl o o r o f - 2 . 8 i s - 3 . 000000
The c e i l o f 2 . 8 i s 3 . 000000
The c e i l o f - 2 . 8 i s - 2 . 000000
llushall 292
#include <Stdio.h>
Rematits The flushall function writes to its associated files the contents of all buffers associated
with open output streams. All buffers associated with open input streams are cleared of
their current contents. The next read operation (if there is one) then reads new data from
the input files into the buffers.
Buffers are automatically flushed when they are full, when streams are closed, or when a
program terminates normally without closing streams.
All streams remain open after the call to flushall
Retum Value The flushall function returns the number of open streams (input and output). There is no
error return.
f.
I * F L U S HA L L . : T h i s p ro g r a m u s e s fl u s h a l l t o fl u s h a l l open buffe r s . * /
#i n c l u d e < s t i o . h >
v o i d ma i n ( )
(
i n t n umfl s h ed ;
n umfl u s h e =fl u s h a l l ( ) ;
p r i n t f ( • h e r e w e r e Sd s t reams fl u s he d \ n " , n umfl u s hed ) ;
Output
#include <math.h>
x, y Floating-point values
Remarks The fmod and fmodl functions calculate the floating-point remainderf of x I y such that
x = i * y + f, where i is an integer, f has the same sign as x, and the absolute value of f is
Return Value These functions return the floating-point remainder. If y is 0, the function returns 0.
Compatibility fmod
fmodl
I * FMOD . C : T h i s p r o g r a m d i s p l a y s a f l o a t i n g - p o i nt rema i n d e r . */
v o i d ma i n ( )
(
I'
doubl e x = - 10 . 0 , y = 3.0, z;
z = fmod ( x , y ) ;
p r i ntfC " T h e rema i nd e r of % . 2 f I % . 2f i s %f\ n " , x , y , z ) ;
Output ,
J
T h e rema i n d r of - 1 0 . 00 I 3 . 00 i s - 1 . 000000
295 fopen
#include <Stdio.h>
Remalks The fopen function opens the file specified by filename. The character string mode speci
fies the type of access requested for the file, as follows:
Description
" r" Opens for reading. If the file does not exist or cannot be
found, the fopen call will fail.
" w" Opens an empty file for writing. If the given file exists, its
contents are destroyed
" a" Opens for writing at the end of the file (appending); creates
the file first if it doesn't exist.
" r+" Opens for both reading and writing. (The file must exist.)
" w+" Opens an empty file for both reading and writing. If the given
file exists, its contents are destroyed.
" a+" Opens for reading and appending; creates the file first if it
doesn't exist.
When a file is opened with the " a " or " a+ " access type, all write operations occur at the
end of the file. Although the file pointer can be repositioned using fseek or rewind, the file
pointer is always moved back to the end of the file before any write operation is carried
out. Thus, existing data cannot be overwritten.
When the " r+" , " w+" , or " a+ " access type is specified, both reading and writing are al
lowed (the file is said to be open for "update"). However, when you switch between read
ing and writing, there must be an intervening fsetpos, fseek, or rewind operation. The
current position can be specified for the fsetpos or fseek operation, if desired.
fopen 296
In addition to the values listed above, one of the following characters can be included in
mode to specify the translation mode for newline characters:
Mode Meaning
lf t or b is not given in mode, the translation mode is defined by the default-mode variable
_fmode. If t or b is prefixed to the argument, the function will fail and return NULL.
See Section 2. 7, "Input and Output," for a discussion of text and binary modes.
Return Value The fopen function returns a pointer to the open file. A null pointer value indicates an
error.
Note that the t option is not part of the ANSI standard for fopen; it is a Microsoft exten
sion and should not be used where ANSI portability is desired.
See Also fclose, fcloseall, fdopen, ferror, fileno, freopen, open, setmode
1
I
I * FO P EN . C : h i s p r o g r a m opens f i l e s n a med " d a t a " a n d " d a t a 2 " . I t u s e s
* f c l o s e to c l o s e " d a t a " a nd fcl o s ea l l to c l o s e a l l rema i n i ng f i l e s .
*I
F I L E * s t ream , * s t ream2 :
v o i d ma i n C l
{
i nt n umc l o s ed ;
I * Open f o r w r i t e * /
i f ( C s t r eam2 = fope n C " d a t a 2 " , • w+ • l l == N U L L
p r i n t f ( " T h e fi l e ' d a t a 2 ' wa s n o t ope n ed \ n� l :
el se
p r i n t f ( " T h e f i l e ' d a t a 2 ' w a s opened \ n " l :
I * C l o s e s t re a m * /
i f ( fcl o s e C s t ream l
p r i n t f C " T h e fi l e ' d a t a ' wa s not c l o s ed \ n " l :
I * Al l o t h e r f i l e s a re c l osed : * /
n u mc l o s e d = f c l o s ea l l ( l :
p r i n t f ( " N umb e r of f i l e s c l o s e d by f c l o s e a l l : % u \ n " , n umc l o s ed l :
(
FP_OFF, FP_SEG 298
Description Get or set a far-pointer offset (FP OFF) or a far-pointer segment (FP SEG)
_ _
.
#include <dos.h>
Remarks The FP OFF and FP SEG macros can be used to set or get the offset and segment, respec
_
_
Return Value The FP OFF macro returns an offset. The FP SEG macro returns a segment address.
_
_
I
D XENIX
I
Campaliblllty D ANSI • DOS • OS/2 D U N IX
Examp� �--����-
1 * F P _S EG . C : T h i s p r o g r a m u s e s F P_S EG a n d F P_O F F t o obta i n
* t h e s e g e n t a n d offset of t h e l ong p o i n t e r p .
* /'
v o i d ma i n ( )
{
v o i d _fa r *p ;
f.
u n s i g n ed i nt s e g_v a l ;
u n s i g n e d i n t off_v a l ;
.
299 FP_OFF, FP_SEG
Output
Segment i s 00C7 ; O f f s e t i s 00 1 6
_Ipreset 300
#include <float.h>
Remarks The _fpreset function reinitializes the floating-point-math package. This function is usu
ally used in conjunction with signal, system, or the exec or spawn functions.
If a program traps floating-point error signals (SIGFPE) with signal, it can safely recover
from floating-point errors by invoking _fpreset and using longjmp.
In DOS versions prior to 3.0, a child process executed by exec, spawn, or system may
affect the floating-point state of the parent process if an 8087 or 80287 coprocessor is
used. If you are using either coprocessor, the following precautions are recommended:
• The exec, spawn, and system functions should not be called during the evaluation of a
floating-point expression.
• The _fpreset function should be called after these routines if there is a possibility of
the child process performing any floating-point operations.
�
I * F P R E S ET . C : T h i s p r o g r a m u s e s s i g n a l to s e t up a r o u t i n e f o r h a n d l i n g
* fl o a t i n g poi nt e r rors .
Il
*'
�
#i n c l ude < s td i o . h>
#i n c l ude < s i gna l . h>
#i n c l ude < s �t j mp . h >
#i n c l ude <s dl i b . h>
#i n c l ude < f l o a t . h>
#i n c l u d e <ma t h . h >
#i n c l ude <s ri ng . h>
301 _Ipreset
v o i d f p h a n d l e r ( i n t s i g , i n t n um ) ; / * P r ototy p e s * /
voi d fpchec k ( vo i d ) ;
v o i d ma i n ( )
[.
d o ub l e n l , n 2 , r ;
i n t j mp ret ;
I * Set u p f l oa t i n g p o i nt e r r o r h a n d l er . * /
i f ( s i g n a l ( S I G F P E , fph a nd l e r ) � S I G_ E R R
(
f p r i n t f ( s t d e r r , " Co u l dn ' t s e t S I G F P E \ n " ) ;
a b o rt ( ) ;
r = n l I n2 ;
I * T h i s won ' t b e r e a c hed i f e r ror o c c u r s . * /
p r i n t f ( " \ n \ n %4 . 3 g I %4 . 3 g %4 . 3 g \ n " , n l , n2 , r ) ;
=
r = n l * n2 ;
I * T h i s won ' t be r e a c h e d i f e r r o r o c c u r s . * /
p r i n t f ( " \ n \ n %4 . 3g * %4 . 3 g %4 . 3 g \ n " , n l , n2 , r ) ;
=
)
el se
fpc h e c k ( ) ;
I
I
_ !preset !
voiI* dHanIfphand
dles Ier(GFPEi nt( floating poinumnt ) error) i nterrupt. */
302
1
I
sig, i n t
**/* Sethand1l1·lobale r. for outsi de check since we don' t want to do I/O in the
fperrI* I n i=1tialize
num; floati ng-poi nt package. */
_fI*presReste 1 r();e calling environment and jump back to setjmp. Return
*Ilongj* so·mtp(l[atmark,setjmp will return false for condi ti onal test . -1
switch(cas]fperrFPE_I NVALI D :
strcpy C fpstr " I nvali d number"
>
case�trrFPEecak;pyUNDERFL
( fpstOr,W: " Underflow "
l;
cas� FPE_ZERODI V I D E:
>:
> :
5
303 fprinff
#include <Stdio.Ii>
Remades The fprintf function formats and prints a series of characters and values to the output
stream. Each argument (if any) is converted and output according to the corresponding
format specification informal.
Theformat argument has the same form and function that it does for the printf function;
see the Remarks section for the printf function for more information onformat and
argument.
Retum Value The fprintf function returns the number of characters printed, or a negative value in the
case of an output error.
I*
*
*
pritheFPRIFPRInDOStNNTF.TF.thTYPEOCemU: TThistooncothemthemaprnfilod.scrgraemenaenusmeedusis nfprintf
FPRIg thNTF.e syOtoUsTtfore. mImtfunctiatthenvariousodin stopladai yntsvoka eand
#i#i nnclude
clude <stdi<process.o . h> h>
*
*I
I
fprintf 1
*str a m ;
304
voi di nmaint i = 10 ;
F I LE
"w" >:
fclose
system str" typeeamfpri); ntf. out• ); > ;
this11.0500000is a string
Output
305 fputc, fputchar
#include <Stdio.h>
c Character to be written
stream Pointer to FILE structure
Remarks The fputc function writes the single character c to the output stream at the current posi
tion. The fputchar function is equivalent to fputc(c, stdout).
The fputc and fputchar routines are similar to putc and putchar, but are_functions rather
than macros.
Return Value The fputc and fputchar functions return the character written. A return value of EOF indi
cates an error.
Compatibility fputc
fputchar
/*
arraFPUTC.y toC : Thistdout.s program uses fputc and fputchar to send a character
#i nclude <stdi o . h>
*
*I
voi dcharmai nst() ptrl[ ] "This i s a test of fputc!! \ n";
306
pwhile( && EO F
fputcha ! !
Output
�
a I
r
I I
II
(
307 fputs
#Include <Stdio.II>
\
int fputs( const char *string, FILE *stream );
The fputs function copies string to the output stream at the current position. The tenninat
ing nuil character ('\0') is not copied.
Rsmalks
Rstum Va/us The fputs function returns a nonnegative value if it is successful. If an error occurs, it re
tums .EOF.
I * FPUTS . C : T h i s p r o g r a m u s e s fputs to w r i t e a s i n g l e l i n e to t h e
s td o u t s t ream .
*I
*
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
{
f p u t s ( " H e l l o w o r l d from fputs . \ n " , s td o u t ) ;
Output
H e l l o w o r l d f rom fputs .
tread 308
#include <Stdio.h>
size t fread( void *buffer, size t size, size t count, FILE *stream );
- - -
Remarks The fread function reads up to count items of size bytes from the input stream and stores
them in buffer. The file pointer associated with stream (if there is one) is increased by the
number of bytes actually read.
If the given stream is opened in text mode, carriage-return-line-feed pairs are replaced
with single line-feed characters. The replacement has no effect on the file pointer or the re
turn value.
The file-pointer position is indeterminate if an error occurs. The value of a partially read
item cannot be determined.
Return Value The fread function returns the number of full items actually read, which may be less than
count if an error occurs or if the file end is encountered before reaching coullt.
The feof or ferror function should be used to distinguish a read error from an end-of-file
condition. If size or coullt is 0, fread returns 0 and the buffer contents are unchanged.
I * F R EA D . C : T h i s p r o g r a m o p e n s a f i l e n a me d F R EA D . O UT a n d w r i t e s 25
* c h a r a c t e s t o t h e f i l e . I t t h e n t r i e s t o o p e n F R EAD . O U T a n d
* r e a d i n 5 c h a r a c t e r s . I f t h e a t t empt s u c c e e d s , t h e p r o g r a m
* d i s p l a y s t h e n u mb e r o f a c t u a l i t ems r e a d .
*I
809 tread
v o i d ma i n ( )
(
F I L E * s t r ea m ;
c h a r l i s t [ 30 ] ;
i nt i , numrea d , numw r i t t e n ;
Output
W r o t e 2 5 i t ems
N umber of i t ems r e a d = 2 5
C o n t e n t s o f b u f f e r = zyxwv u t s rqponml kj i hgfedcb
r
free Fun lions 310
Remalks The free family of functions deallocates a memory block. The argument memblock points
to a memory block previously allocated through a call to calloc, malloc, or realloc. The
number of bytes freed is the number of bytes specified when the block was allocated (or
reallocated, in the case of realloc}. After the call, the freed block is available for
allocation.
The seg argument specifies the based heap containing the memory block to be freed by the
_bfree function.
Attempting to free an invalid pointer may affect subsequent allocation and cause errors.
An invalid pointer is one not allocated with the appropriate call.
The following restrictions apply to use of the free, _bfree , _ffree, and _nfree functions:
The various free functions deallocate a memory block in the segments shown in the list
below:
Function Data Segment
Compat/blllly free
oi dcharmain(>*st[li ng;
312
�
i
f.
I
313 _freect
Rematks The _freect function tells you how much memory is available for dynamic memory alloca
tion in the near heap. It does so by returning the approximate number of times your pro
gram can call _nmalloc (or malloc in small data models) to allocate an item size bytes
long in the near heap (default data segment).
Return Value The _freect function returns the number of calls as an unsigned integer.
See Also calloc functions, _expand functions, malloc functions, _memavl, _msize functions,
realloc functions
I*
*
FREEintegersCT.inCt: egersinThistheprogra aulmtdeterdatthea msegmen
defand checks i nsespacehotwagai. muchThenn, freeusii t nalloca
spacet is
es
g _freect. s availabl
p ace for e for
#i#ivoinnclude <malloc. h>
* 1 , 000
( dintmaii:n ()
I*
pri nFtf(i rst_fr"Irnetegers
poreect(t onsizeof( ( athepproxifrei mnetate)space:avai l able on heap: %u\n\n ",
*/
>:
) ) >:
*/
_lreect
nallocati
pripriI* nnReportf(tf( _1tt·•]�l agaifternrtegers */availablei nontegers:heap: \%u\n " n);\n",
on ( theapproxinfrgemespate)space:
314
eect( si zeof( i nt ) ) ) ;
a c e for
1 000
e on heap:
I ntegers < apfroxi mate) foravai l ablei nontegers:heap:
15212
1000
1 4084
315 treapen
#include <Stdio.h>
FILE lllfreopen( const char *filename, const char *mode, FILE *stream );
Remarks The freopen function closes the file currently associated with stream and reassigns stream
to the file specified by filename. The freopen function is typically used to redirect the pre
opened files stdio, stdout, and stderr to files specified by the user. The new file associ
ated with stream is opened with mode, which is a character string specifying the type of
access requested for the file, as follows:
Description
" r" Opens for reading. If the file does not exist or cannot be
found, the freopen call fails.
" w" Opens an empty file for writing. If the given file exists, its
contents are destroyed.
"a" Opens for writing at the end of the file (appending); creates
the file first if it does not exist.
" r+ " Opens for both reading and writing. (The file must exist.)
" w+" Opens an empty file for both reading and writing. If the given
file exists, its contents are destroyed.
"a+ " Opens for reading and appending; creates the file first if it
does not exist.
Use the " w" and " w+ " types with care, as they can destroy existing files.
When a file is opened with the "a" or "a+ " access type, all write operations take place at
the end of the file. Although the file pointer can be repositioned using fseek or rewind, the
file pointer is always moved back to the end of the file before any write operation is car
ried out. Thus, existing data cannot be overwritten.
!reopen 316
When the " r+" , " w+" , or " a+ " access type is specified, both reading and writing are al
lowed (the file is said to be open for "update"). However, when you switch between read
ing and writing, there must be an intervening fsetpos, fseek, or rewind operation. The
current position can be specified for the fsetpos or fseek operation, if desired.
In addition to the values listed above, one of the following characters may be included in
the mode string to specify the translation mode for newlines.
Mode Meaning
If t or b is not given in the mode string, the translation mode is defined by the default
mode variable _fmode.
See Section 2.7, "Input and Output," for a discussion of text and binary modes.
Retum Va/ue The freopen function returns a pointer to the newly opened file. If an error occurs, the orig
inal file is closed and the function returns a NULL pointer value.
The t option is not part of the ANSI standard for freopen; it is a Microsoft extension that
should not be used where ANSI portability is desired.
-·
*
*/
named Thi s prograand wrim rteesassignsa linesttodauthatx to thefi l efile.
/ * FREO P E N . , :
F R O P E N . OUT
!reopen
#i#include
nclude <s<stdlitdio.bh. >h>
317
*str
voi d mai n ()
FI LE e a m ;
strif(I* eRaestrmassi=eamgfrn==eopen(" stdaux" f" rtoeopen." freoopen.ut", o"wut":", s*/tdaux
{
NULL )
I
Dsscrlptlon
I Get the mantissa and exponent of a floating-point number.
#include <math.h>
x Floating-point value
Remarks The frexp and frexpl functions break down the floating-point value (x) into a mantissa (m)
and an exponent (n), such that the absolute value of m is greater than or equal to 0.5 and
less than 1 .0, and x = m *2 ". The integer exponent n is stored at the location pointed to by
expptr.
The frexpl function is the 80-bit counterpart and uses an 80-bit, l 0-byte coprocessor form
of arguments and return values. See the reference page on the long double functions for
more details on this data type.
Return Value These functions return the mantissa. If x is 0, the function returns 0 for both the mantissa
and the exponent. There is no error return.
Compatibility I frexp
frexpl
{I/ii nnclcludeude
*
*I I
frexp, frexpl
intx n; y;
y =
pri nfrtf(exp(" frexpCx, &n%f,); &n ) %f, n %d\n", x, n
= 16 . 4 ;
= = y, >:
frexpC &n
Output
1 6 . 400000 , > = n
0 . 5 1 2 500 , = 5
tscanf 320
#include <Stdio.h>
Remarks The fscanf function reads data from the current position of stream into the locations given
by argument (if any). Each argument must be a pointer to a variable with a type that corre
sponds to a type specifier informal. The format controls the interpretation of the input
fields and has the same form and function as theformat argument for the scanf function;
see scanf for a description offormat.
Return Value The fscanf function returns the number of fields that were successfully converted and as
signed. The return value does not include fields that were read but not assigned.
The return value is EOF for an error or end-of-file on stream before the first conversion. A
return value of 0 means that no fields were assigned.
LEvoi d mai*strne()am;
321
( floatong fp;;
FI
charcharint rs[c;esul81];t ;
1 1
;
fsI*I*eSetek(Readpoistrdataneteramback, to0L, befrSEEKgomi n_ningfiSEl Te : of*I fi l e : */
65000 , 3 . 14 1 5 9 , ' x ' )
fsfscanf
fsfscccanf(aannf(f( strstrstrstream,eeeaaammm ,,, """"%%%%f",cs",l d ".&c&fps&l) ); ););
l;
Ipri* Output
nntf(tf( """ %%%das\f\n",l dtn\an",",reasfpd) :););; */
C
priprintf(
•,
l;
a-stri ng
Output
6 5000
3 . 1 4 1 590
x
lseek 322
#include <Stdio.h>
Remadts The fseek function moves the file pointer (if any) associated with stream to a new location
that is offset bytes from origin. The next operation on the stream takes place at the new lo
cation. On a stream open for update, the next operation can be either a read or a write.
The argument origin must be one of the following constants defined in STDIO.ff:
Origin Definition
The fseek function can be used to reposition the pointer anywhere in a file. The pointer
can also be positioned beyond the end of the file. However, an attempt to position the
pointer in front of the beginning of the file causes an error.
The fseek function clears the end-of-file indicator and negates the effect of any prior
ungetc calls against stream.
1/0 operation, not by where the next write would occur. If no I(O operation has yet oc
When a file is opened for appending data, the current file position is determined by the last
curred on a file opened for appending, the file position is the start of the file.
For streams opened in text mode, fseek has limited use because carriage-return-line-feed
translations can cause fseek to produce unexpected results. The only fseek operations
guaranteed to work on streams opened in text mode are the following:
Return Value If successful, fseek returns 0. Otherwise, it returns a nonzero value. On devices incapable
of seeking, the return value is undefined.
1***/movesFSEEK. theC : Thispoi nprogra ter tomtheopensfile'thes fibegil enniFSEEK.ng. OUT and
Exampm ������-
include <stdi
voi( dFILEmai n*strea() m :
# o . h >
chi natr reine[sult:81J:
stri f ( epriasmtnr-etf(amfopenC=="The file" fseek.fsoeut",ek. out"w+"was >not: opened\n" >:
1
resi f( perrultresul=o r(tfse") ekCFseekstr"Tfaiehisaml ed", is the>: SEEKfile_SE' Tfs):eek. out'. \n " >:
•
else( pri ntf( " Fi le poi nter is set to mi ddle of first line. \n " >:
23L ,
fgets(
pri n tf( li"%ne,s", 80,linestr);eam >:
)
fcl oseC. stream l:
#include <Stdio.h>
Remarks The fsetpos function sets the file-position indicator for stream to the value of pos, which is
obtained in a prior call to fgetpos against stream.
The function clears the end-of-file indicator and undoes any effects of the ungetc function
on stream. After calling fsetpos, the next operation on stream may be either input or
output.
Return Value If successful, the fsetpos function returns 0. On failure, the function returns a nonzero
value and sets ermo to one of the following manifest constants (defined in ERRNO.H):
Constant Meaning
EBADF The object that stream points to is not a valid file handle, or
the file is not accessible.
EINVAL An invalid stream value was passed.
* d i fferent h o c a t i o n s .
/ * FGETPOS . C : 1 T h i s p r o g r a m opens a f i l e a n d rea d s byt e s a t s e v e r a l
*I
�
#i n c l ude < s t d o . h >
fsetpos
fposcharint _t buffer[
FI LE
pos;val; 20];
if(elsepri( strntf(eam"=Trofopen(uble opening " fgetpos.file\n"c ", " rb);" )) )
== N U L L
friI*fe( perrad(Readfgetpos(obuffer,
some dastrtsieazameof(an, d&posthcharen ) check),! = 010th, estrposieamt i);on. */
el( sfread(e r( buffer, " fgetpos error" ); >
.C:
FI LE
_fsopen 326
#include <Stdio.h>
#include <Share.h> sliflag constants
FILE "'_fsopen( const char "'filename, const char •mode, int shflag );
R1matlcs The _fsopen function opens the file specified byfilename as a stream and prepares the
file for subsequent shared reading or writing, as defined by the mode and shflag
arguments.
The character string mode specifies the type of access requested for the file, as follows:
Description
" r" Opens for reading. If the file does not exist or cannot be
found, the _fsopen call will fail.
" w" Opens an empty file for writing. If the given file exists, its
contents are destroyed.
"a" Opens for writing at the end of the file (appending); creates
the file first if it does not exist.
" r+ " Opens for both reading and writing. (The file must exist.)
" w+" Opens an empty file for both reading and writing. If the given
file exists, its contents are destroyed.
"a+ " Opens for reading and appending; creates the file first if it
does not exist.
Use the " w" and " w+ " types with care, as they can destroy existing files.
When a file is opened with the " a" or " a+ " access type, all write operations occur at the
end of the file. Although the file pointer can be repositioned using fseek or rewind, the file
pointer is always moved back to the end of the file before any write operation is carried
out. Thus, existing data cannot be overwritten.
327 _lsopen
When the " r+ " , " w+ " , or "a+ " access type is specified, both reading and writing are al
lowed (the file is said to be open for "update"). However, when switching between reading
and writing, there must be an intervening fsetpos1 fseek, or rewind operation. The current
position can be specified for the fsetpos or fseek operation, if desired.
In addition to the values listed above, one of the following characters can be included in
mode to specify the translation mode for newlines:
Mode Meaning
the file.
b Open in binary (untranslated) mode; the above translations are
suppressed.
If t or b is not given in mode, the translation mode is defined by the default-mode variable
_fmode. If t or b is prefixed to the argument, the function will fail and will return NULL.
See Section 2. 7, "Input and Output," for a discussion of text and binary modes.
The argument shflag is a constant expression consisting of one of the following manifest
constants, defined in SHARE.H. If SHARE.COM -or SHARE.EXE for some versions of
DOS- is not installed, DOS ignores the sharing mode. (See your system documentation
for detailed information about sharing modes.)
Constant Meaning
SH_COMPAT Sets compatibility mode (not available in OS/2)
SH_DENYNO Permits read and write access
SH_DENYRD Denies read access to file
SH_DENYRW Denies read and write access to file
SH_DENYWR Denies write access to file
The _fsopen function should be used oniy under OS/2 and DOS versions 3.0 and later.
Under earlier versions of DOS, the shflag argument is ignored.
_lsapen 328
Retum Value The _fsopen function returns a pointer to the stream. A NULL pointer value indicates an
error.
S11 Alsa fclose, fcloseall, fdopen, ferror, tileno, fopen, freopen, open, setmode, sopen
fclose str e a m );
sIy*stNoewm( ot· rypeers outfile" can wri te );to the file while we read i t .
>:
*/
I
No one else n the network can write to this fi l e until we are done.
Output
329 fstat
#include <Sys\types.h>
#include <Sys\stat.h>
Remarks The fstat function obtains infonnation about the open file associated with handle and
stores it in the structure pointed to by buffer. The structure, whose type stat is defined in
SYS\C>TAT.H, contains the following fields:
Field Value
If handle refers to a device, the size and time fields in the stat structure are not
meaningful.
!stat 330
Retum Value The fstat function returns the value 0 if the file-status infonnation is obtained. A return
value of -1 indicates an error; in this case, ermo is set to EBADF, indicating an invalid file
handle.
In OS/2, the st_dev field does not contain meaningful infonnation. In fact, it is set to zero.
OS/2 provides no way to recover the host drive from just the open file handle.
I#iI#incl//ii nclude
nclude
n#include l
<i
<f 1 0 . h
cludeude <s<t<sli ms\ts\stat.
c ntl >
e. yh. >pes.h> h>h>
#i#i#i nnnclude
clude
clude <stdi
<s
<stri dli o
n b.
g. h
. >
hh>>
� oi dstructmain()s!�at buf:
charif(int fh,C buffer[
f h
resul]t : "A line to output":
open( " f stat. out", O _ CRE A T O _WRONL Y O _TRUNC >> >
exi t ( >:
=
I*
!= 0 )
ad file handle\n " */
%d\n",
%s", buf.
cti m e( s t _ dev
&buf. s t _
>:
ati m e
close( fh
>:
) >:
}
>:
16
0
15 2 1 : 38 : 46 1 989
Itel/ 332
#include <Stdio.h>
Remarks The ftell function gets the current position of the file pointer (if any) associated with
stream. The position is expressed as an offset relative to the beginning of the stream.
Note that when a file is opened for appending data, the current file position is detennined
by the last 1/0 operation, not by where the next write would occur. For example, if a file is
opened for an append and the last operation was a read, the file position is the point where
the next read operation would start, not where the next write would start. (When a file is
opened for appending, the file position is moved to end-of-file before any write operation.)
If no 1/0 operation has yet occurred on a file opened for appending, the file position is the
beginning of the file.
Return Value The ftell function returns the current file position. The value returned by ftell may not re
flect the physical byte offset for streams opened in text mode, since text mode causes
carriage-return-line-feed translation. Use ftell in conjunction with the fseek function to re
turn to file locations correctly. On error, the function returns -IL and errno is set to one of
the following constants, defined in ERRNO.H:
Constant Description
EBADF Bad file number. The stream argument is not a valid file
handle value or does not refer to an open file.
EINVAL Invalid argument. An invalid stream argument was passed to
the function.
On devices incapable of seeking (such as tenninals and printers), or when stream does not
refer to an open file, the return value is undefined.
333 Itel/
printf( >:
/
#include <Sys\types.h>
#include <Sys\timeb.h>
Remarks The ftime function gets the current time and stores it in the structure pointed to by timeptr.
The timeb structure is defined in SYS\TIMEB.H. It contains four fields (dstflag, millitm,
time, and timezone), which have the following values:
Field Value
Return Value The ftime function gives values to the fields in the structure pointed to by timeptr. It does
not return a value.
I * FT I M E . C : T h i s p r o g r a m u s e s ft i me to obta i n t h e c u r re n t t i me
* a n d t h en s t o re s t h i s t i me i n t i mebuffer .
*I
#i n c l u d e < s td i o . h>
#i n c l u d e < sy s \ t i meb . h >
#i n c l u d e <t i me . h>
v o i d ma i n ( )
(
s t r u c t t i meb t i meb u ff e r ;
c h a r * t i mel i n e ;
ft i me C & t i mebuffer ) ;
t i me l i ne = c t i me ( & C t i mebuffe r . t i me > > :
p r i n t f ( " T h e t i me i s % . 1 9 s . % h u %s " ,
t i mel i n e , t i mebuffer . mi l l i tm , &ti mel i n e [ 20 ] > :
Output
T h e t i me i s T h u J u n 1 5 2 1 : 40 : 34 . 87 0 1 989
tu I/pat, 336
#include <stdlib.h>
Remarks The _fullpath routine converts the partial path stored in pathname to a fully qualified path
that is stored in buffer. Unlike _makepath, the _fullpath routine can be used with .\ and \ ••
in the path.
If the length of the fully qualified path is greater than the value of max/en, then NULL is
returned; otherwise, the address of buffer is returned.
If the buffer is NULL, _fullpath will allocate a buffer of MAX_PATH size and the
max/en argument is ignored.
If the pathname argument specifies a disk drive, the current directory of this drive is com
bined with the path. If the drive is not valid, _full path returns NULL.
Return Valu 1I The _fullpath function returns a pointer to the buffer containing the absolute path
(buffer). If there is an error, _fullpath returns NULL.
I
I
See A/so ' getcwd, _getdcwd, _makepath, _splitpath
I * F U L L P A W H . C : T h i s p r o g r a m d em o n s t r a t e s h o w _f u l l p a t h c r e a t e s a f u l l
* p a t h f�om a p a r t i a l p a t h .
*I i
i< c on i o . h >
#i ncl ude �stdi o . h>
1fo i n c l u d e
#i ncl ude 1< s t d l i b . h >
#i n c l ude :< d i rect . h>
I
�fuHpath
( while(
gets(priif( nparbreak:
tf(part [" 0tEnJ ter== 0part i a l path or ENTER to qui t :
1
(
• >:
>:
to qui t :
FullFullEnterpapathpartht is:ii asl: C:paP: t\\hi norcludeENTER
ENTER to
to qui
qui . t
t •:
: p: \i n clude
Enter
FullEnterpathpartipartiis:aa ll C:pathpath\ LIorBorREF\ENTER
fENTERullpath.toto quiquictt :: full path. c
fwrite 338
#include <Stdio.h>
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );
Remarks The fwrite function writes up to count items, of length size each, from buffer to the output
stream. The file pointer associated with stream (if there is one) is incremented by the num
ber of bytes actually written.
If stream is opened in text mode, each carriage return is replaced with a carriage-return
line-feed pair. The replacement has no effect on the return value.
Return Value The fwrite function returns the number of full items actually written, which may be less
than count if an error occurs. Also, if an error occurs, the file-position indicator cannot be
determined.
f
*
* 25
v o i d ma i n ( )
(
F I L E * s t r ea m ;
c h a r l i s t [ 30 J ;
i nt i , numrea d , n umw r i t t e n ;
el se
p r i n t f ( " P ro b l em open i n g t h e f i l e \ n " ) ;
el se
p r i n t f ( " Wa s n o t a b l e t o open t h e f i l e \ n " ) ;
Output
Wrote 2 5 i t ems
Numb e r of i t ems read = 2 5
C o n t e n t s of b u f f e r = zyxwv u t s rqponml kj i hgfedcb
gcvt 340
Remarks The gcvt function converts a floating-point value to a character string and stores the string
in buffer. The buffer should be large enough to accommodate the converted value plus a
terminating null character ('\0'), which is appended automatically. There is no provision
for overflow. ·
The gcvt function attempts to produce digits significant digits in decimal format. If this is
not possible, it produces digits significant digits in exponential format. Trailing zeros may
be suppressed in the conversion.
Return Value / The gcvt function returns a pointer to the string of digits. There is no error return.
lib/II,
I
I
I
See A/so atof, atoi, atol, ecvt, fcvt
GCV
I
Exampre ��
T . C J This progra m converts -3. 1 4 15e5 to i t s stri n g repres e ntati o n.
�������������������������������
#i#i nnclude
clude 1stdli
{stdi ob. h. >h>
I* */
i
I
341 gcvt
v o i d ma i n ( )
(
c h a r b u f f e r [ 50 l :
doubl e source - - 3 . 141 5e5 :
g c v t C s o u r c e , 7 , buffe r > :
p r i n t f C " s o u r c e : %f b u f fe r : ' % s ' \ n " , s o u r c e , buffe r ) ;
Output
#include <graph.h>
Remarks The _getactivepage function returns the number of the current active page.
Return Value The function returns the number of the current active page. All hardware combinations sup
port at least one page (page number 0). In OS(l, only page 0 is valid.
_setvideomode, _setvisualpage
char_gstreutvictdluf[ioconfig(
tj
deoconfi
80]; g&vcvc;);
if(ol dapagvc.exi umvi _getactivepa
d);eopages < 4ge();) Fa il for OS/2 or monochrome.
ol dvpagIcursor(_getvisual
_displa
C 1
=
=
_GCURSORpagOe();FF );
/* */
I
_getacttvepage
I * D r a w a r rows i n d i fferent p l a c e o n e a c h p a g e . * /
fo r ( p a g e = 1 ; p a g e < 4 ; p a g e++ >
(
_s et a c t i v epa ge ( p a g e > :
_s ettextpos i t i on ( 1 2 , 1 6 * pa ge > :
_ou t t ex t ( " > > > > >> > > " > :
w h i l e ( ! kb h i t ( ) )
I * Cyc l e t h ro u g h p a g e s 1 t o 3 to s h ow mo v i n g i ma g e . * I
fo r ( p a g e= 1 ; p a g e < 4 ; p a g e++
_s et v i s u a l pa g e ( p a g e > :
getch C > :
I * Re s t o r e o r i g i n a l p a g e ( n o rma l l y 0 ) to r e s t o r e s c reen . * I
_s e t a c t i v epa g e ( o l d a p a ge > :
_s e t v i s u a l p a g e ( o l d v p a g e > :
_d i s pl a y c u rs o r ( _GC U RSORON > :
getarcin 344
Description Detennines the endpoints in viewport coordinates of the most recently drawn arc or pie.
#include <graph.h>
short _far _getarcinfo( struct xycoord _far *start, struct xycoord _far *end,
struct xycoord _far *fillpoint );
Rematits The _getarcinfo function detennines the endpoints in viewport coordinates of the most re
cently drawn arc or pie.
If successful, the _getarcinfo function updates the start and end xycoord structures to con
tain the endpoints (in viewport coordinates) of the arc drawn by the most recent call to one
of the _arc or _pie functions.
In addition,fillpoint specifies a point from which a pie can be filled. This is useful for
filling a pie in a color different from the border color. After a call to _getarcinfo, change
colors using the _setcolor function. Use the color, along with the coordinates infillpoi11t,
as arguments for the _floodfill function.
Retum Value The _getarcinfo function returns a nonzero value if successful. If neither the _arc nor the
_pie function has been successfully called since the last time the screen was cleared or a
new graphics mode or viewport was selected, the _getarcinfo function returns 0.
#include <graph.h>
Remarks The _getbkcolor function returns the current background color. The default i s 0.
In a color text mode such as _TEXTC80, _setbkcolor accepts, and _getbkcolor returns, a
color index. For example, _setbkcolor(2L) sets the background color to color index 2. The
actual color displayed depends on the palette mapping for color index 2. The default for
color index 2 is green in a color text mode.
In a color graphics mode such as _ERESCOLOR, _setbkcolor accepts and _getbkcolor re
turns a color value (as used in _remappalette). The value for the simplest background
colors is given by the manifest constants defined in the GRAPH.ff include file. For ex
ample, _setbkcolor( _GREEN) sets the background color in a graphics mod<? to green.
These manifest constants are provided as a convenience in defining and manipulating the
most common colors. In general, the actual range of colors is much greater.
In most cases, whenever an argument is long, it refers to a color value, and whenever it is
short, it refers to a color index. The two exceptions are _setbkcolor and _getbkcolor, de
scribed above. For a more complete discussion of colors, see _remappalette.
Retum Value The function returns the current background color value. There is no error return.
Description Reads a character from a stream (getc), or gets a character from stdio (getchar).
#include <Stdio.h>
Remarks The getc macro reads a single character from the stream position and increments the as
sociated file pointer (if there is one) to point to the next character. The getchar macro is
identical to getc(stdin).
The getc and getchar routines are similar to fgetc and fgetchar, respectively, but are mac
ros rather than functions.
Return Value The getc and getchar macros return the character read. A return value of EOF indicates an
error or end-of-file condition. Use ferror or feof to determine whether an error or end-of
file occurred.
Compatibility getc
getchar
!
I * G ETC . C : 1 h i s p r o g r a m u s e s get c h a r to r e a d a s i n g l e l i n e of i n put
* f r om s t d n , pl a c e s t h i s i n put i n buffe r , t h en t e rmi n a t e s t h e
* s t ri n g b f o r e p r i n t i n g i t t o t h e s c reen .
*I
#i n c l u d e < s t d i o . h >
347 getc, getchar
v o i d ma i n < >
(
c h a r buffe r [ 8 1 ] ;
i nt i , c h ;
p r i ntf ( " E n t e r a l i n e : • ) ;
I * Termi n a t e s t r i n g w i t h n ul l c h a r a c t e r : * /
buffer [ i ] = ' \0 ' ;
p r i n t f ( " % s \ n " , buffe r ) ;
Output
E n t e r a l i n e : T h i s i s a l i n e of text .
T h i s i s a l i n e of text .
gstch, gs r:he 348
D11t:t/ptlon Get a character from the console without echo (getch) or with echo (getche).
Rematlts The getch function reads a single character from the console without echoing. The getche
function reads a single character from the console and echoes the character read. Neither
function can be used to read CTRL+C.
When reading a function key or cursor-moving key, the getch and getche functions must
be called twice; the first call returns 0 or OxEO, and the second call returns the actual key
code.
Retum Value The getch function returns the character read. There is no error return.
v o i d ma i n ( }
(
i nt ch ;
put c h ( c h > :
putch ( ' \ r ' > : / * C a r r i a g e ret u r n * /
putch ( ' \ n ' } : / * Li ne feed */
Output
#include <graph.h>
Remarks The _getcolor function returns the current graphics color index. The default is the highest
legal value of the current palette.
Return Value The _getcolor function returns the current color index.
I*
*
OUTTX_sett_gettT . C�r xtcolor
f
i
xtcolThisoexar m_setbk ple illustra
_getbk ccolorolor tes_s_gettextposi
textettextposioutputtt ii functi
oonn _outons:text
#include <cbni o . h >
*
#include I
<s�di o . h >>
*I
#include
charvoi d maibuffen r <g
1 [ 80 ] ;
aph. h
I
q
�
!
/* */
j
�
361 _getco/or
I * Fi r s t t i me n o b l i n k , s e c o n d t i me b l i n k i n g . * /
f o r ( b l i n k = 0 ; b l i n k <= 1 6 ; b l i n k += 1 6 )
{
/ * Loop t h ro u g h 8 b a c kground c o l o r s . * /
fo r < b g d = 0 ; b g d < 8 ; bgd++ )
{
_s e t b k c o l o r ( bgd > :
_s ettextpos i t i on ( C s h o rt ) bgd + ( ( b l i n k I 1 6 ) * 9 ) + 3 , 1 )�
_s ettextcol o r < 7 > :
s p r i n t f ( bu f fe r , " Ba c k : %d Fore : " , bgd ) ;
_o utt ext < b u f f e r ) ;
I * Loop t h r o u g h 1 6 f o r e g r o u n d col o r s . * /
fo r ( f g d = 0 ; f g d < 1 6 ; fgd++ )
{
_s ettextc o l o r ( fgd + b l i n k ) ;
s p r i n t f ( buffe r , • %2d " , fgd + b l i n k ) ;
_ou t t ext ( buffe r ) ;
)
getch < > :
i
Description I Get the current position and return it as a structure.
I #include <graph.h>
Remarks The _getcurrentposition functions return the coordinates of the current graphics output
position. The _getcurrentposition function returns the position as an xycoord structure,
defined in GRAPH.H.
Element Description
Element Description
The current position can be changed by the _lineto, _moveto, and _outgtext functions.
The default position, set by _setvideomode, _setvideomoderows, or _setviewport, is the
center of the viewport.
Only graphics output starts at the current position; these functions do not affect text output,
which begins at the current text position. (See _settextposition for more information.)
Return Value The _getcurrentposition function returns the coordinates of the current graphics output
position. There is no error return.
358 _getcurrentpasitian Functions
I * GCU RPOS . C : T h i s p r o g r a m s e t s a r a n d om c u r r e n t l oc a t i on , t he n g e t s t h a t
* l o c a t i on w i t h _g et c. u r rentpos i t i on .
*I
char buffe r [ 2 5 5 ] ;
v o i d ma i n ( )
(
s t ruct v i d e o c o n f i g v c ;
s t ruct xy c o o r d pos i t i on ;
I * Fi n d a v a l i d g r a p h i c s mode . * /
i f ( l _s e t v i d e omod e C _MAX RESMODE
exi t C 1 ) ;
_g etv i d e o c o n f i g C & v c l ;
I * Move t o r a n d om l o c a t i on a n d report t h a t l oc a t i on . * /
_mo v et o ( r a n d ( ) % v c . n umx p i x e l s , r a n d ( ) % v c . n umy p i x e l s l ;
pos i t i on = _get c u r re n t p o s i t i on C l ;
s p r i n t f C buffe r , • x = %d , y = %d " , pos i t i on . xcoord , po s i t i on . y c o o r d l ;
_s ettextpos i t i on C l , 1 l ;
_ou t t ex t C buffer l ;
getch C l ;
_s e t v i d eomod e C _D E FAU LTMO D E l ;
· getcwd 354
Remadts The getcwd function gets the full path name of the current working directory and stores it
at buffer. The integer argument max/en specifies the maximum length for the path name.
An error occurs if the length of the path name (including the terminating null character)
exceeds max/en.
The buffer argument can be NULL; a buffer of at least size max/en (more only if neces
sary) will automatically be allocated, using malloc, to store the path name. This buffer can
later be freed by calling free and passing it the getcwd return value (a pointer to the allo
cated buffer).
Retum Value The getcwd function returns a pointer to buffer. A NULL return value indicates an error,
and errno is set to one of the following values:
Value Meaning
f
I * T h i s p r o r a m pl a c e s t h e n a me of t h e c u r re n t d i rect o ry i n t h e b u f f e r
* a r ray , t e n d i s p l a y s t h e n a me of t h e c u r re n t d i r e c t o ry on t h e s c reen .
* Spec i fy i g a l en g t h o f MAX O I R l ea v e s room for t h e l on g e s t l eg a l
_ _
* d i rec t o r n a me .
*I
I
355 getcwd
v o i d ma i n ( )
(
c h a r buffer [_MAX_D I R J ;
I * Get t h e c u r rent w o r k i n g d i r e c t o ry : * /
i f ( get cwd C b u ffe r , _MAX_D I R ) == NULL )
p e r ro r C • g etcwd e r r o r • > :
el se
pri ntfC " Ss \ n " , buffer > :
Output
C : \ LI BREF
I
_getdcwd asB
DBScrlpllon Gets full path name of current working directory, including disk drive.
Rematks The _getdcwd function gets the full path name of the current working directory, Including
disk drive specification, and stores it at buffer. The argument max/en specifies the maxi
mum length for the path name. An error occurs if the length of the path name (including
the terminating null character) exceeds max/en.
The drive argument specifies the drive (0 = default drive, l=A, 2=B, etc.). The buffer argu
ment can be NULL; a buffer of at least size max/en (more only if necessary) will automat
ically be allocated, using malloc, to store the path name. This buffer can later be freed by
calling free and passing it the _getdcwd returri value (a pointer to the allocated buffer).
Return Value The _getdcwd function returns buffer. A NULL return value indicates an error, and errno
is set to one of the following values:
Value Meaning
i
See A/BO chdir, getcwd, _getdrive, mkdir, rmdir
I
!
Exampm ��I�������������������������������
I * G E T D R I V E . C i l l u s t r a t e � d r i v e func t i o n s i n c l u d i n g :
* _g � t d r i ve _c hd r i v e _g etd cwd
*I
as1 _getdcwd
v o i d ma i n ( )
(
i nt ch , dri ve , curdri ve ;
s t a t i c c h a r pa th [_MAX_PATH J ;
I * S a v e c u r re n t d r i v e . * /
c u rd r i v e = _getd r i v e C l ;
p r i n t f ( " A v a i l a bl e d r i v e s a re : \ n " l ;
I * I f we c a n swi t c h to t h e d r i v e , i t exi s t s . * /
fo r e d r i v e = 1 ; d r i v e <= 26 ; d r i v e++ )
i f ( ! _c h d r i v e C d r i v e l l
p r i ntf ( " %c : • , d r i ve + ' A ' 1 l ;
-
whi l e( 1 l
(
p r i n t f ( " \ nType d r i v e l et t e r t o c h e c k o r ESC to q u i t : " l ;
c h = getc h C l ;
i f( ch = 27 l
b r ea k ;
i f ( i sa l pha C c h l l
put c h ( c h l ;
i f ( _g etd cwd C touppe r C c h l - ' A ' + 1 , p a t h , _MAX_PATH l ! = N U L L
p r i n t f ( " \ n C u r re n t d i r e c t o ry o n t h a t d r i v e i s % s \ n " , p a t h l ;
/ * Re s t o r e o r i g i na l d r i v e . T h i s i s on l y n e c e s s a ry f o r DOS . U n d e r O S / 2
* t h e c u r r ent d r i v e of t h e c a l l i n g p r o c e s s i s a l ways r e s t o red .
*I
_c h d r i v e C c u rd r i v e l ;
pri ntf( " \ n " ) ;
I
_getdcw� 358
Output
�
Av a i l a bl e d r i v e s a re :
A: B: C:
Ty pe d r i v e l et t e r t o c h e c k o r ESC t o q u i t : q
Ty pe d r i v e l et t e r to c h e c k or ESC to q u i t : a
C u r rent d i r c t o ry on t h a t d r i v e i s A : \
Ty pe d r i v e l et t e r t o c h e c k o r E S C t o q u i t : c
C u r rent d i r c t o ry o n t h a t d r i v e i s C : \ L I B R E F
I
I
359 _getdrive
#include <direct.h>
Remarks The _getdrive function returns the current working drive ( l =A, 2=B, etc.).
Return Value The return value is stated above. There is no error return.
Rematts The getenv function searches the list of environment variables for an entry corresponding
to varname. Environment variables define the environment in which a process executes.
(For example, the LIB environment variable defines the default search path for libraries to
be linked with a program.) Because the getenv function is case sensitive, the varname vari
able should match the case of the environment variable.
The getenv function returns a pointer to an entry in the environment table. It is, however,
only safe to retrieve the value of the environment variable using the returned pointer. To
modify the value of an environmental variable, use the putenv function.
The getenv and putenv functions use the copy of the environment contained in the global
variable environ to access the environment. Programs th� use the envp argument to main
and the putenv function may retrieve invalid infonnation. The safest programming prac
tice is to use getenv and putenv.
Return Value The getenv function returns a pointer to the environment table entry containing the current
string value of varname. The return v alue is NULL if the given variable is not currently
defined.
The getenv function operates only on the data structures accessible to the run-time library
and not on the environment "segment" created for a process by DOS or OS/2.
jstdl i b . h>
j s td i o . h >
#i n c l u d e
#i n c l u d e
361 getenv
ma i n ( )
[
c h a r * l i b va r ;
I * Get t h e v a l u e o f t h e L I B e n v i ronment v a r i a b l e . * /
l i bv a r = getenv ( " L I B " ) ;
i f ( l i b va r ! = N U L L )
p r i n t f ( " O r i g i n a l L I B v a r i a b l e i s : % s \ n " , l i b va r ) ;
I * Get new va l u e . * /
l i bv a r = g e t en v < " L I B " ) ;
i f ( l i bv a r ! = N U L L )
p r i n t f ( " N ew L I B v a r i a b l e i s : % s \ n " , l i b va r ) ;
Output
O r i g i n a l L I B va r i a b l e i s : C : \ L I B
N ew L I B va r i a b l e i s : c : \ my l i b ; c : \ y o u r l i b
362
Dest:rlptlon Gets the current fill mask for some graphics routines.
#include <graph.h>
Remades Some graphics routines (_ellipse, _floodfill, _pie, _polygon, and _rectangle) can fill part
or all of the screen with the current color or background color. The fill mask controls the
pattern used for filling.
The _getfillmask function returns the current fill mask. The mask is an 8-by-8-bit array, in
which each bit represents a pixel. If the bit is 1 , the corresponding pixel is set to the current
color; if the bit is 0, the pixel is left unchanged. The mask is repeated over the entire fill
area. If no fill mask is set, or if mask is NULL, a solid ( unpatterned) fill is performed using
the current color.
See Also _ellipse functions, _floodfill, _pie functions, _polygon functions, _rectangle functions,
_setfillmask
v o i d ma i n ( )
[
i n t l oop ;
I * F i nd a v a l i d g r a p h i c s mod e . * /
i f ( ! _s et v i d eomod e ( _MAX RESMODE
exi t ( 1 l ;
I * Set f i r s t f i l l ma s k a n d d r a w rect a n g l e . * /
_s e t f i l l ma s k ( ma s k l l ;
_recta n g l e ( _G F I L L I NT E R I O R , 20 , 20 , 100 , 100 l ;
getc h ( l ;
I * C a l l rou t i n e t h a t s a v e s a n d r e s t o res ma s k . * /
e l l i p s ema s k ( 60 , 60 , 1 50 , 1 50 , ma s k 2 ) ;
getc h < l :
I * Ba c k t o o r i g i n a l ma s k . */
_rect a n g l e ( _G F I L L I NT E R I O R , 1 20 , 1 20 , 1 9 0 , 1 9 0 ) ;
getc h ( l ;
I * D r a w a n e l l i p s e wi t h a s p e c i f i ed f i l l ma s k . * /
v o i d e l l i p sema s k ( s h o rt x l , s ho r t y l , s h ort x 2 , s h o r t y 2 , c h a r _fa r *n ewma s k l
{
u n s i gned c h a r s a vema s k [ 8 ] ;
_g e t f i l l ma s k ( s a vema s k ) ; I* S a v e ma s k */
_s e t f i l l ma s k ( n ewma s k l ; /* Set n ew ma s k */
_e l l i p s e ( _G F I L L I NT E R I O R , x l , y l , x2 , y 2 l ; /* U s e n ew ma s k */
_s e t f i l l ma s k ( s a vema s k ) ; /* Re s t o r e o r i g i n a l */
_getfonti o ,, I
364
#include <graph.h>
Remarks The _getfontinfo function gets the current font characteristics and stores them in a
_fontinfo structure, defined in GRAPH.ff. ·
Element Contents
Return Value The _getfontinfo function returns a negative number if a font has not been registered or
loaded.
I
Compatibility 1 D ANSI • DOS D OS/2 D UNIX D XENIX
#include <graph.h>
Remarks The _getgtextextent function returns the width in pixels that would be required to print the
text string using _outgtext with the current font.
This function is particularly useful for determining the size of text that uses proportionally
spaced fonts.
Return Value The _getgtextextent function returns the width in pixels. It returns -1 if a font has not
been registered.
#include <graph.h>
Remarks The _getgtextvector function gets the current orientation for font text output. The current
orientation is used in calls to the _outgtext function.
The text-orientation vector, which detennines the direction of font-text rotation on the
screen, is returned in a structure of type xycoord. The xcoord and ycoord members of the
structure describe the vector. The text-rotation options are shown below:
Return Value The _getgtextvector function returns the current text-orientation vector in a structure of
type xycoord.
#include <graph.h>
void _far _getimage( short xl, short yl, short x2, short y2, char _huge *image );
void _far _getimage_w( double wxl , double wyl, double wx2, double wy2,
char _huge *image );
void _far _getimage_wxy( struct_wxycoord _far *pwxyl,
struct_wxycoord _far *pwxy2, char _huge *image );
Remarks The _getimage functions store the screen image defined by a specified bounding rectangle
into the buffer pointed to by image.
The _getimage function defines the bounding rectangle with the view coordinates (xl , y1 )
and (x2, y2).
The _getimage_w function defines the bounding rectangle with the window coordinates
(wxl , wyl) and (wx2, wy2).
The _getimage_wxy function defines the bounding rectangle with the window-coordinate
pairs pwxyl and pwxy2.
The buffer must be large enough to hold the image. You can determine the size by calling
the appropriate _imagesize function at run time, or by using the formula described on the
_imagesize reference page.
I * G I MA G E . C : T h i s e x a mp l e i l l u s t r a t e s a n i ma t i on rout i n e s i n c l ud i n g :
* _i ma ges i z e _g et i ma g e _p ut i ma g e
*I
);
n };
s ho r t a c t i n [ 5 J = ( _G P S ET , _G P R E S ET , _GX O R , _GO R , _GA N O
c h a r * d e s c i p [ 5 J = ( " P S ET " , " P R E S ET " , " X O R " , "OR " , " AN D
v o i d ex i t f e e ( c h a r _h u g e * b u f f e r ) ;
v o i d ma i n q
t
f'
(
cha r h u g e * b u f fe r ; I * Fa r po i n t e r C w i t h _fma l l o c ) c o u l d be u s ed . * /
l on g ms i z e ;
s hort x , y = 30 ;
i f ( ! _ e t v i deomod e ( _MA X R E SM O D E ) )
��
ex " t ( 1 l ;
T
j
_s e t c o r C 3 ) ;
: : : : : :: :� :
or i ;
r D a e l p n w po s i t i on a n d get a copy of i t . * /
x = 50 ; y += 40 ;
_ l l i p s e ( _G F I L L I NT E R I O R , x - 1 5 , y - 1 5 , x + 1 5 , y + 1 5 ) ;
_ et i ma g e ( x - 1 6 , y - 1 6 , x + 1 6 , y + 1 6 , b u f f e r ) ;
i ( _g r s t a t u s ( ) )
e x i t f re e ( b u f f e r ) ; I * Q u i t on e r ro r *I
aBs _getimage Functions
v o i d e x i t f r e e ( c h a r _h u g e * b u f f e r
(
h f re e C b u f f e r l ;
e x i t ( ! _s et v i d eomod e ( _D E FAU LTMO D E l ) ;
370
1
Description Gets the current line style.
#include <graph.h>
Remarks Some graphics routines (_lineto, _polygon, and _rectangle) output straight lines to the
screen. The type of line can be controlled with the current line-style mask.
The _getlinestyle function returns the current line-style mask. The mask is a 1 6-bit array
in which each bit represents a pixel in the line being drawn. If the bit is l , the correspond
ing pixel is set to the color of the line (the current color). If the bit is 0, the corresponding
pixel is left unchanged. The mask is repeated over the length of the line. The default mask
is OxFFFF (a solid line).
Return Value i If no mask has been set, _getlinestyle returns the default mask.
�
I * G L I N EST[Y . C : T h i s p r o g r a m i l l u s t r a t e s _s e t l i n estyl e a n d _get l i n e s tyl e . * /
#i n c l u d e coni o . h>
#i n c l u d e stdl i b . h>
#i n c l u d e g ra p h . h >
I
v o i d z i g z � g ( s h o rt x l , s h o r t y l , s h o r t s i z e ) ;
�oi d ma i n r
I * F i n h a v a l i d g r a p h i c s mode . * /
i f ( ! _� e t v i d eomod e ( _MAX C O L O RM O D E ) )
ex i � ( 1 ) ;
1
�
I * S e t i l i n e s ty l e a n d d ra w r e c t a ng l e . * /
_s e t l i e s tyl e ( 0x4d ) ;
_recta g l e ( _G B O RD E R , 1 0 , 1 0 , 60 , 60 ) ;
getch C) :
871 _getlinestyle
I * D r a w f i g u re w i t h funct i on t h a t c h a nges a nd r e s t o r e s l i n e s t y l e . * /
z i g z a g ( 100 , 100 , 90 > :
getc h ( ) ;
I * O r i g i n a l s ty l e r e u s e d . *I
_recta n g l e ( _GBORD E R , 1 9 0 , 1 90 , 130 , 130 > :
getch C > :
#include <graph.h>
Remarks The _getphyscoord function translates the view coordinates (x, y) to physical coordinates
and returns them in an xycoord structure, defined in GRAPH.H.
The xycoord structure contains the following elements:
Element Description
short xcoord x coordinate
short ycoord y coordinate
i
I
Return Value : None.
I
I
!
See Also _getviewcoord functions, _grstatus, _setvieworg, _setviewport
RemalkB The getpid function returns the process ID, an integer that uniquely identifies the calling
process.
Return Value The getpid function returns the process ID. There is no error return.
I * G ET P I D . C : T h i s p r o g r a m u s e s getpi d t o obta i n t h e p r o c e s s I D a n d
* then pri nts the I D .
*I
v o i d ma i n ( )
(
I * I f run f rom DOS , s h ow s d i fferent I D f o r DOS t h a n for DOS s h el l .
* I f execed o r s p a wned , s h ows I D o f pa rent .
*I
p r i n t f ( " \ n P ro c e s s i d of pa rent : % d \ n " , g e t p i d ( ) ) ;
Output
P ro c e s s i d o f p a rent : 828
_gstplxsl runctlons
I
374
I #include <graph.h>
xy
, Pixel position
Remarks The functions in the _getpixel family return the pixel value (a color index) at a specified
location. The _getpixel function uses the view coordinate (x, y) The _getpixel_w function
.
uses the window coordinate (wx, wy). The range of possible pixel values is detennined by
the current video mode. The color translation of pixel values is detennined by the current
palette.
Return Value If successful, the function returns the color index. If the function fails (for example, the
point lies outside the clipping region, or the program is in a text mode), it returns -1 .
1
ExampM ��������������������������������
I * G P I X E L . Ci: T h i s p r o g r a m a s s i g n s d i f f e r e n t c o l o r s to r a n d oml y
l
!
* s e l e c t e d p i x el s .
*I
v o i d ma i n ( )
i
�fI
s ho r t x a r , y v a r ;
s t r u c t i d eocon f i g v c ;
I
375 _getpixel Functions
I * Fi n d a v a l i d g r a p h i c s mod e . * I
i f ( ! _s et v i d eomod e ( _MA X C O L O RMODE ) )
exi t ( 1 l :
_g e t v i d e o c o n f i g ( & v c > :
I * D r a w f i l l ed e l l i p s e t o t u r n on c e rt a i n p i x e l s . * /
_el l i ps e ( _G F I L L I NT E R I O R , vc . numx p i xel s I 6 , vc . numy p i x e l s I 6 ,
vc . numx p i xel s I 6 * 5 , v c . n umyp i xel s I 6 * 5 ) ;
I * D ra w r a n d om pi x e l s i n r a n d om c o l o r s . . • */
w h il e ( ! kb h i t ( ) l
(
I * . . . b u t on l y i f t h ey a re a l r e a dy on ( i n s i d e t h e e l l i p s e ) . * /
x v a r = r a n d ( ) % · v c . n umx p i x e l s ;
y v a r = r a nd ( ) % v c . n umy p i x e l s ;
i f ( _g e t p i x e l ( x v a r , y v a r ) ! = 0
(
_s e t c o l o r C r a n d ( ) % 1 6 > :
_s e t p i x e l ( x v a r , y v a r > :
#include <Stdio.h>
The line consists of all characters up to and including the first newline character (\n). The
R1matkB The gets function reads a line from the standard input stream stdio and stores it in buffer.
gets function then replaces the newline character with a null character ('\0') before return
ing the line. In contrast, the fgets function retains the newline character.
Relum Value If successful, the gets function returns its argument. A NULL pointer indicates an error or
end-of-file condition. Use ferror or feof to determine which one has occurred.
I * GETS . C *
I
#i n c l ude < s d i o . h >
v o i d ma i n ( )
�
(
c h a r l i n [ 81 ] ;
p r i n t f ( " I n put a s t r i n g : • ) ;
gets ( 1 i ne > ;
p r i n t f ( " T h e l i n e e n t e red w a s : % s \ n " , l i n e ) ;
�l
Output
I n put a s t i n g : T h i s i s a s t r i n g .
T h e l i o e e t e red wa s ' T h i s i s a s t r i og
I
377 _gettextcolor
#include <graph.h>
R11matlcs The _gettextcolor function returns the color index o f the current text color. The text color
is set by the _settextcolor function and affects text output with the _outtext and _outmem
functions only. The _setcolor function sets the color for font text output using the
_outgtext function.
The default is 7 in test modes; it is the highest legal color index of the current palette in
graphics modes.
R11turn Valu11 The _gettextcolor function returns the color index of the current text color.
#include <graph.h>
Remarks The _gettextcursor function returns the current cursor attribute (i.e., the shape). This func
tion works only in text video modes.
Rstum Value The function returns the current cursor attribute, or -1 if an error occurs (such as a call to
the function in a graphics mode).
#include <graph.h>
Remarks The _gettextposition function returns the current text position as an rccoord structure,
defined in GRAPH.H.
Element Description
short row Row coordinate
short col Column coordinate
Remarks The text position given by the coordinates ( 1 , 1 ) is defined as the upper-left comer of the
text window.
Text output from the _outtext and _outmem functions begins at the current text position.
Font text is not affected by the current text position. Font text output begins at the current
graphics output position, which is a separate position.
#i n c l u d e < c o n i o . h >
#i n c l u d e < s td i o . h >
#i n c l u d e < g ra p h . h >
_gettextp sition 380
c h a r b u f f e r [ 80 ] ;
v o i d ma i n ( ) j
,
I
I * Sa v e o i g i n a l f o r e g r o u n d , b a c k g round , a n d text po s i t i on . * /
s h o r t b l i k , fgd , o l d f g d ;
l ong bgd , o l dbgd ;
r
s t ruct re oord ol dpos :
I
o l dbgd = g e t b k c o l o r C > :
o l dpos = g e t t e x t p o s i t i o n C > :
_c l ea rs c r e e n ( _GC L EARSC R E E N > :
I * Fi r s t t i me n o bl i n k , s e c o n d t i me bl i n k i n g . * /
I
f o r ( bl i k = 0 : bl i n k <= 1 6 : b l i n k += 1 6 >
I
I * L o p t h ro u g h 8 ba c kg round c o l o r s . * /
fo r ( gd = 0 ; b g d < B : bgd++ >
{
_s t b k c o l o r ( bgd > :
_s t t extpos i t i on ( ( s h o r t ) bgd + ( ( bl i n k I 1 6 ) * 9 ) + 3 , 1 > :
_s t t ex t c o l o r C 7 > :
sp i n t f ( b u f fe r , " B a c k : %d F o r e : " , bgd > :
_o ttext ( buffer > :
ro l
I * Loop t h r o u g h 1 6 f o r e g r o u n d c o l o r s . * /
( f g d = 0 ; f g d < 1 6 ; fg d++ )
[I
}
�
g} e t c h C > :
I
I
381 _gettextwindow
#include <graph.h>
void _far _gettextwindow( short _far *rl, short _far *cl , short _far *r2,
short _far *c2 );
Remarks The _gettextwindow function finds the boundaries of the current text window. The text
window is the region of the screen to which output from the _outtext and _outmem func
tions is limited. By default, this is the entire screen, unless it has been redefined by the
_settextwindow function.
The window defined by _settextwindow has no effect on output from the _outgtext func
tion. Text displayed with _outgtext is limited to the current viewport.
#include <graph.h>
Remarks The __getvideoconfig function returns the current graphics environment configuration in a
videoconfig structure, defined in GRAPH.H.
The values returned reflect the currently active video adapter and monitor, as well as the
current video mode.
The videoconfig structure contains the following members, each of which is of type short:
Member Contents
adapter Active display adapter
bitsperpixel Number of bits per pixel
memory Adapter video memory in kilobytes
mode Current video mode
monitor Active display monitor
numcolors Number of color indices
numtextcols Number of text columns available
The values for the adapter member of the videoconfig structure are given by the manifest
constants shown in the list below. For any applicable adapter ( _CGA, _EGA, or _VGA),
the corresponding Olivetti® adapter ( _OCGA, _OEGA, or _OVGA) represents a superset
of graphics capabilities.
The values for the monitor member of the videoconfig structure are given by the manifest
constants listed below:
In every text mode, including monochrome, the _getvideoconfig function returns the value
32 for the number of available colors. The value 32 indicates the range of values (0-3 1)
accepted by the _settextcolor function. This includes 1 6 normal colors (0-15) and 1 6
blinking colors ( 16-3 1 ). Blinking is selected by adding 1 6 to the normal color index. Be
cause monochrome text mode has fewer unique display attributes, some color indices are
redundant. However, because blinking is selected in the same manner, monochrome text
mode has the same range (0-3 1 ) as other text modes.
_getvideo nfig $ 384
Return Value The _getvideoconfig function returns the video configuration information in a structure, as
noted above. There is no error return.
Example ��--���
j
I * GV I D C FG . C : T h i s p r o g r a m d i s p l a y s i n forma t i on a bout t h e c u r rent
* v i deo c o n f g u r a t i o n .
*/
�oi d ma i n ( ) I
s t ruct v i d � o c o n f i g v c ;
s h o rt c · •
char b [ 5�0 ] ; I * B u f f e r f o r s t r i ng * /
b
_get v i d e oc n f i g ( & v c ) ;
�
I * W r i t e a l i nf o rma t i o n to a s t r i ng , t h e n output s t r i n g . */
v c . numx p i x e l s l ;
l
c = s p r i nit f ( b , • X pi xe1 s : %d \ n " ,
c += s p r i � t f ( b + c , • y p i x e l s : %d\ n " , v c . n umy p i x e l s ) ;
c += s p r i ntf ( b + c , " Text c o l umn s : % d \ n " , v c . n umtext c o l s ) ;
c += s p r i t f ( b + c , " Text rows : %d\ n " , v c . n umt ex t r ow s ) ;
c += s p r i t f ( b + c , " Co l o r s : %d\ n " , v c . n umc o l o r s ) ;
c += s p r i t f ( b + c , " B i t s / p i x e l : %d\ n " , vc . bi tsperpi xel ) ;
c += s p r i t f ( b + c , " V i d e o p a g e s : %d \ n " , vc . numv i d e o p a g e s ) ;
c += s p r i ry t f ( b + c , " Mode : %d\n " , v c . mode ) ;
c += s p r i rl t f ( b + c , " Mon i t o r :
c += s p r i rt t f ( b + c , " Ad a pt e r : %d\ n " , vc . adapter ) ;
c += s p r i � t f ( b + c , " Memo ry :
%d\n " , vc . mon i t o r ) ;
Output
X pi xel s : 0
Y pi xel s : 0
Text c o l umn s : 80
Text rows : 25
Col ors : 32
B i t s / p i xel : 0
V i deo pages : 1
M od e : 3
Ada p t e r : 8
M on i t o r : 24
Memo ry : 256
_getvieWi oord Functions 386
#include <graph.h>
Remarks The _getviewcoord routines translate the specified coordinates (x, y) from one coordinate
system to view coordinates and then return them in an xycoord structure, defined in
GRAPH.ff. The xycoord structure contains the following elements:
Element Description
·
short xcoord x coordinate
short ycoord y coordinate
Routine Translation
Retum Value The _getviewcoord function returns the coordinates as noted above. There is no error
return.
387 _getviewcoord Functions
#include <graph.h>
Remarks The _getvisualpage function returns the current visual page number.
Return Value The function returns the number of the current visual page. All hardware combinations sup
port at least one page (page number 0). In OS/2, only page 0 is available.
#include <Stdio.h>
Remarks The getw function reads the next binary value of type int from the file associated with
stream and increments the associated file pointer (if there is one) to point to the next un
read character. The getw function does not assume any special alignment of items in the
stream.
Return Value The getw function returns the integer value read. A return value of EOF may indicate an
error or end-of-file. However, since the EOF value is also a legitimate integer value, feof
or ferror should be used to verify an end-of-file or error condition.
The getw function is provided primarily for compatibility with previous libraries. Note
that portability problems may occur with getw, since the size of the int type and the order
ing of bytes within the int type differ across systems.
#i n c l u d e < s t d i o . h >
#i n c l u d e < s t d l i b . h >
v o i d ma i n ( )
(
FI LE *stream ;
i nt i ;
getw 390
� l
( /*
i f ( C s t r e m = fopen ( " g etw . c • , " rb " > > == N U L L >
*/
r i n t f " C o u l d n ' t open f i l e \ n " > :
el s
�
f
. 1* */
Rea a word f rom t h e s t rea m :
l
i = ge w < s t r e a m ) ;
I f �here i s a n e r ro r . . •
i f ( f�r r o r ( s t r e a m ) )
1
(
p r ' n t f ( " g etw f a i l ed \ n " > :
c l a re r r ( s t r e a m ) ;
el se
p r ·· n t f { " Fi r s t d a t a w o r d i n f i l e : 0x% . 4x \ n " , );
f c l o s ( s t re a m > :
Output I
Fi rst data �ord i n fi l e : 0x2a 2f
391 _getwindowcoord
#include <graph.h>
Remal'ks The _getwindowcoord function translates the view coordinates (x, y) to window coordi
nates and returns them in the _wxycoord structure, defined in GRAPH.ff.
The _wxycoord structure contains the following elements:
Element Description
double wx x coordinate
double wy y coordinate
Retum Value The function returns the coordinates in the _wxycoord structure. There is no error return.
#include <graph.h>
Remarks The _getwritemode function returns the current logical write mode, which is used when
drawing lines with the _lineto, _polygon, and _rectangle functions.
The default value is _GPSET, which causes lines to be drawn in the current graphics color.
The other possible return values are _GXOR, _GAND, _GOR, and _GPRESET. See
_putimage for more details on these manifest constants.
Retum Value The _getwritemode function returns the current logical write mode, or -1 if not in
graphics mode.
&m __ ______________________________________________________________ _
#i n c l u d e < �o n i o . h >
#i n c l ude < s t d l i b . h>
#i n c l ude < r a p h . h >
l:
( " P S ET •
_G P R ESET , _GX O R , _GO R , _GA N O
c h a r *wm s t [ S J = " P RE S ET " , " XO R •, "OR " " AN D " l:
v o i d ma i n ( �
( i
s ho r t i x, y;
393 _getwritemode
I * F i nd a v a l i d g r a p h i c s mod e . * I
i f ( ! _s et v i d eomod e ( _MAX C O LO RM O D E ) )
exi t C 1 ) ;
x = y = 70 ;
box ( x , y , 50 , _G P S ET , _G F I L L I NT E R I O R ) ;
_s e t c o l o r C 2 ) ;
box ( x , y , 40 , _G P S ET , _G F I L L I NT E R I O R ) ;
fo r ( i = Iii ; i < 5 ; i ++ >
{
_s ettextpos i t i on ( l , 1 ) ;
_outtext ( wms t r [ i ] ) ;
box ( x += 1 2 , y += 1 2 , 50 , wmo d e s [ i ] , _GBO R D E R ) ;
getc h ( ) ;
#include <time.h>
Rematks The gmtime function converts the timer value to a structure. The timer argument repre
sents the seconds elapsed since 00:00:00, January l , 1 970, Greenwich mean time. This
value is usually obtained from a call to the timer function.
,
The gmtime function breaks down the timer value and stores it in a structure of type tm,
defined in TIME.H. (See asctime for a description of the structure members.) The struc
ture result reflects Greenwich mean time, not local time.
The fields of the structure type tm store the following values, each of which is an int:
Field Value Stored
tm_sec Seconds
tm_min Minutes
tm_hour Hours (0-24)
tm_mday Day of month ( 1-3 1 )
tm_mon Month (0-1 1 ; January = 0)
tmJear Year (current year minus 1 900)
The gmtime, mktime, and localtime functions use a single statically allocated structure to
hold the result. Each call to one of these routines destroys the result of any previous call.
DOS and OS/2 do not accommodate dates prior to 1 980. If timer represents a date prior to
-���
1 980, gmtime returns NULL.
The gmtime function returns a pointer to the structure result. There is no error return.
I * GMT I M E . C : T h i s p ro g r a m u s es gmt i me to c o n v e rt a l on g - i n t e g e r
* r e p r e s e n t a t i on of G reenwi c h mea n t i me to a s t r u c t u r e n a med n ewt i me ,
* t h e n u s e s a s c t i me to c o n v e r t t h i s s t r u c t u r e to a n o u t p u t s t r i n g .
*I
v o i d ma i n ( )
(
s t ruct tm * n ewt i me ;
l on g l t i me ;
t i me ( & l t i me ) ;
Output
Description Returns the status of the most recent graphics function call.
#include <graph.h>
Remarks The _grstatus function returns the status of the most recently used graphics function. The
_grstatus function can be used immediately following a call to a graphics routine to deter
mine if errors or warnings were generated. Return values less than 0 are errors, and values
greater than 0 are warnings.
The following manifest constants are defined in the GRAPH.ff header file for use with the
_grstatus function:
0 _GROK Success
-1 _GRERROR Graphics error
-2 _GRMODENOTSUPPORTED Requested video mode not supported
-3 _GRNOTINPROPERMODE Requested routine only works in cer-
tain video modes
-4 _GRINVALIDPARAMETER One or more parameters invalid
-5 _GRFONTFILENOTFOUND No matching font file found
-6 _GRINVALIDFONTFILE One or more font files invalid
-7 _GRCORRUPTEDFONTFILE One or more font files inconsistent
-8 _GRINSUFFICIENTMEMORY Not enough memory to allocate buff-
er or to complete a _floodflll
operation
-9 _GRINVALIDIMAGEBUFFER Image buffer data inconsistent
1 _GRMOOUTPUT No action taken
2 _GRCLIPPED Output was clipped to viewport
3 _GRPARAMETERALTERED One or more input parameters was al-
tered to be within range, or pairs of
parameters were interchanged to be
in the proper order
397 _grstatus
After a graphics call, use an if statement to compare the return value of _grstatus to
_GROK. For example:
i f { _g r s t a t u s < _G RO K )
/ * h a n d l e g r a p h i c s e r ro r * /
The functions listed below cannot cause errors, and they all set _grstatus to GROK:
See the list below for the graphics functions that affect _grstatus. The list shows error or
warning messages that can be set by the graphics function. In addition to the error codes
listed, all of these functions can produce the _GRERROR error code.
_getwindowc rd _GRNOTINPROPERMODE
_getwritemo _GRNOTINPROPERMODE
_imagesize fu ctions _GRNOTINPROPERMODE
_lineto functi ns _GRNOTINPROPERMODE GRNOOUTPUT,
:GRCLIPPED
_moveto func ons · _GRNOTINPROPERMODE
_outgtext _GRNOTINPROPERMODE GRCLIPPED,
:GRNOOUTPUT
_pie function GRNOTINPROPERMODE, GRNOOUTPUT,
-GRINVALIDPARAMETER, :GRCLIPPED
:GRINSUFFI CIENTMEMORY
_polygon fun 1 tions GRNOTINPROPERMODE, GRNOOUTPUT,
-GRINVALIDPARAMETER, :GRCLIPPED
:GRINSUFFICIENTMEMORY
_putimage GRERROR, GRPARAMETERALTERED,
-GRNOTINPROPERMODE, :GRNOOUTPUT
-GRINVALIDPARAMETER,
:GRINVALIDIMAGEBUFFER
_rectangle GRNOTINPROPERMODE, GRNOOUTPUT,
-GRINVALIDPARAMETER, :GRCLIPPED
:GRINSUFFICIENTMEMORY
_registerfon GRCORRUPI'EDFONTFILE,
-GRFONTFILENOTFOUND,
-GRINSUFFICIENTMEMORY,
_scrolltex
I ndow
:GRINVALIDFONTFILE
_GRNOOUTPUT
_selectpalet GRNOTINPROPERMODE,
:GRINVALIDPARAMETER
_GRINVALIDPARAMETER
_setbkcolor _GRINVALIDPARAMETER _GRPARAMETERALTERED
_setcliprgn _GRNOTINPROPERMODE _GRPARAMETERALTERED
_setcolor _GRNOTINPROPERMODE _GRPARAMETERALTERED
GRERROR,
I·r-
_setfont
-GRFONTFILENOTFOUND,
-GRINSUFFICIENTMEMORY,
:GRPARAMETERALTERED
Continued page
399 _grstatus
_setgtextvector _GRPARAMETERALTERED
_settextcolor _GRPARAMETERALTERED
_settextcursor _GRNOTINPROPERMODE
_settextposition _GRPARAMETERALTERED
_settextrows _GRINVALIDPARAMETER _GRPARAMETERALTERED
_settextwindow _GRPARAMETERALTERED
_setvideomode _GRERROR,
_GRMODENOTSUPPORTED,
_GRINVALIDPARAMETER
_setvideomoderows _GRERROR,
_GRMODENOTSUPPORTED,
_GRINVALIDPARAMETER
_setvieworg _GRNOTINPROPERMODE
_setviewport _GRNOTINPROPERMODE _GRPARAMETERALTERED
_setvisualpage _GRINVALIDPARAMETER
_setwindow _GRNOTINPROPERMODE, _GRPARAMETERALTERED
_GRINVALIDPARAMETER
setwritemode _GRNOTINPROPERMODE,
_GRINVALIDPARAMETER
Return Value The _grstatus function returns the status of the most recently used graphics function.
See Also _arc functions, _ellipse functions, _tloodfill, _lineto functions, _pie functions,
_remapallpalette, _setactivepage, _setbkcolor, _setcolor, _setpixel functions,
_settextcolor, _settextcursor, _setvisualpage, _setwindow, _setwritemode
Remarks The halloc function allocates a huge array from the operating system consisting of num ele
ments, each of which is size bytes long. Each element is initialized to 0. If the size of the
array is greater than 1 28K ( 1 3 1 ,072 bytes), the size of an array element must then be a
power of 2.
Return Va/u i The halloc function returns a void huge pointer to the allocated space, which is guaranteed
to be suitably aligned for storage of any type of object. To get a pointer to a type other than
void huge, use a type cast on the return value. If the request cannot be satisfied, the return
I value is NULL.
!
Compatibility D ANSI • DOS • OS/2 D UNIX D XENIX
I
�
I * HALLOC!. C : T h i s p r o g r a m u s e s h a l l oc t o a l l o c a t e s p a c e f o r 30 , 000 l on g
* i n t e g e s , t h e n u s e s h f r e e t o d ea l l o c a t e t h e memo ry .
*I :
#i n c l u d e k s t d i o . h>
#i n c l u d e ( s t d l i b . h >
1/i n c l u d e r <ma l 1 o c . h >
rl
I
v o i d ma i < l
l
l on g l h u g e * h b u f ;
i
I
I
401 ha/lac
I * Al l o c a t e h u g e b u f f e r * /
h b u f = ( l on g _h uge * l h a l l oc ( 30000 L , s i zeof ( l ong l l ;
i f ( hbuf = NULL )
=
I * Free h u g e b u ffe r * /
hfree ( hbuf ) ;
Output
Memo ry s u c c e s s fu l l y a l l o c a t ed
402
I
Description Handle critical error conditions.
#include <dos.h>
Remarks These three functions are used to handle critical error conditions that use DOS interrupt
Ox24. The _harderr function installs a new critical-error handler for interrupt Ox24.
the new critical-error handler installed by _harderr. The _hardresume function returns to
The hardresume and hardreturn functions control how the program will return from
The _harderr function does not directly install the handler pointed to by handler; instead,
The deverror argument is the device error code. It contains the AX register value passed
by DOS to the INT Ox24 handler. The errcode argument is the DI register value that DOS
passes to the handler. The low-order byte of errcode can be one of the following values:
Code Meaning
6 Seek error
7 Unknown media type
8 Sector not found
9 Printer out of paper
10 Write fault
11 Read fault
12 General failure
The devhdr argument is a far pointer to a device header that contains descriptive informa
tion about the device on which the error occurred. The user-defined handler must not
change the information in the device-header control block.
If the error occurred on a disk device, the high-order bit (bit 15) of the deverror argument
will be set to 0, and the deverror argument will indicate the following:
Bit Meaning
14 Not used.
00 DOS
01 File allocation table
10 Directory
11 Data area
The low-order byte of deverror indicates the drive in which the error occurred (0 = drive
A, 1 = drive B, etc.).
ff the error occurs on a device other than a disk drive, the high-order bit (bit 1 5) of the
deverror argument is 1 . The attribute word located at offset 4 in the device-header block in
dicates the type of device that had the error. If bit 1 5 of the attribute word is 0, the error is
a bad memory image of the file allocation table. If the bit is l, the error occurred on a char
acter device and bits 0-3 of the attribute word indicate the type of device, as shown in the
following list:
Bit Meaning
The user-defined handler function can issue only system calls OxOl through OxOC, or
Ox59. Thus, many of the standard C run-time functions (such as stream 1/0 and low-level
1/0) cannot be used in a hardware error handler. Function Ox59 can be used to obtain
further information about the error that occurred.
If the handler returns from -hardresume or from a return statement, the handler returns
to DOS.
405 _hard Functions
The _hardresume function should be called only from within the user-defined hardware
error-handler function. The result supplied to _hardresume must be one of the following
constants:
Constant Action
The _hardretn function allows the user-defined hardware error handler to return directly
to the application program rather than returning to DOS. The application resumes at the
point just after the failing 1/0 function request. The _hardretn function should be called
only from within a user-defined hardware error-handler function.
The error parameter of _hardretn should be a DOS error code, as opposed to the XENIX
style error code that is available in errno. Refer to MS-DOS Encyclopedia (Duncan, ed.;
Redmond, Wa.: Microsoft Press, 1 988) or Programmer's PC Sourcebook (Hogan; Red
mond, Wa. : Microsoft Press, 1988) for infonnation about the DOS error codes that may be
returned by a given DOS function call.
If the failing 1/0 function request is an INT Ox2 l function greater than or equal to function
Ox38, _hardretn will then return to the application with the carry flag set and the AX reg
ister set to the _hardretn error parameter. If the failing INT Ox2 l function request is less
than function Ox38 and the function can return an error, the AL register will be set to OxFF
on return to the application. If the failing INT Ox2 l does not have a way of returning an
error condition (which is true of certain INT Ox2 1 functions below Ox38), the error param
eter of _hardretn is not used, and no error code is returned to the application.
Oesarlpllan Add memory to the heap lheapadd) or to the based heap lbheapadd).
Rematits The _heapadd and _bheapadd functions add an unused piece of memory to the heap. The
_bheapadd function adds the memory to the based heap specified by seg. The _heapadd
function looks at the segment value and, if it is DGROUP, adds the memory to the near
heap. Otherwise, _heapadd adds the memory to the far heap.
See Also free functions, halloc, hfree, malloc functions, realloc functions
Exampm __ -1--------------------------------------------------------------
I * H EA PM I N . C : T h i s p ro g r a m i l l u s t r a t e s h e a p m a n a gement u s i ng
* _h e a p a d a nd _h e a pmi n .
�
*/
#i n c l u d e < t d i o . h>
#i n c l u d e < oni o . h>
#i n c l u d e < rocess . h>
#i n c l u d e < a l l oc . h >
I
407 _heapadd Functions
v o i d ma i n ( )
(
i nt * p [ 3 ] , i :
I * Gi v e s p a c e of u s ed s t r i n g s t o h ea p . * /
_hea p a d d ( s l , s i z e o f ( s l ) > :
_h e a p a d d ( s 2 , s i z e o f ( s 2 ) > :
h e a pd ump C " After a dd i n g u s ed s t r i n g s • > :
/ * Free s ome of t h e b l o c k s . * /
f ree < p [ l ] > :
f ree ( p [ 2 ] ) ;
h e a pd ump C " After f r e e i n g memo ry • ) ;
I * M i n i mi z e h ea p . * /
_h e a pmi n C > ;
h e a pdump C " After c ompa c t i ng h ea p • > :
I * Wa l k t h ro u g h h e a p e n t r i e s , d i s p l a y i n g i n f o rma t i on a bo u t e a c h b l oc k . * /
v o i d h e a pd ump C c h a r *ms g )
( .
s t ruct _hea p i n fo h i ;
�
Output
l
U S E D b l o c k a t 2 D 3 9 : 1030 of s i z e 5 1 2
F R E E b l o k a t 2 D 3 9 : 1 232 of s i z e 460
After a d d i n u s ed s t r i n g s
F R E E b l o k a t 2 D 3 9 : 0044 of s i z e 5 2
F R E E b l o ¢ k a t 2D39 : 007A of s i z e 50
U S E D b l o ¢ k a t 2 D 3 9 : 00A E of s i ze 3 5 64
U S E D b l o � k a t 2 D 3 9 : 0 E9C of s i ze 364
l
U S E D b l o ¢ k at 2 D3 9 : 1 00A of s i z e 36
USED b l o f k at 2 D 3 9 : 1030 of s i z e 5 1 2
F R E E b l o k a t 2D39 : 1 2 3 2 of s i z e 460
Afte r a l l oc t i n g memo ry
U S E D b l o k a t 2 D 3 9 : 0044 of s i z e 20
i
U S E D b l o � k a t 2 D 3 9 : 005A of s i z e 4 0
F R E E b l o f k a t 2 D 3 9 : 0084 of s i ze 40
U S E D bl o p k a t 2 D 3 9 : 00AE of s i z e 3 5 64
U S E D b l o k a t 2 D 3 9 : 0 E 9 C of s i z e 364
USED b l o k a t 2 D 3 9 : 100A of s i z e 3 6
�
U S E D b l o k a t 2 D 3 9 : 1030 of s i z e 5 1 2
F R E E b l o F k a t 2 D 3 9 : 1 2 3 2 of s i z e 460
Aft e r f r e e i r g memo ry
U S E D b l o k a t 2 D 3 9 : 0044 of s i z e 20
F R E E b l o k a t 2 D 3 9 : 005A of s i z e 40
FREE b l o k at 2 D 3 9 : 0084 of s i z e 40
U S E D b l Qc k a t 2 D 3 9 : 100A o f s i z e 3 6
U S E D b l � c k a t 2 D 3 9 : 1030 o f s i ze 5 1 2
F R E E b l 9 c k a t 2 D 3 9 : 1 232 o f s i z e 460
�
After c omp c t i n g h e a p
U S E D b l c k a t 2D39 : 0044 of s i z e 2 0
F R E E b l c k a t 2 D 3 9 : 005A of s i z e 8 2
�q
U S E D b l oc k a t 2 D 3 9 : 00AE o f s i z e 3564
USED b l c k a t 2 D 3 9 : 0 E 9 C o f s i z e 364
U S E D b l c k a t 2 D 3 9 : 1 00A o f s i z e 3 6
U S E D b l c k a t 2D39 : 1030 of s i ze 5 1 2
F R E E b l c k a t 2 D 3 9 : 1 232 o f s i z e 1 2
409 _heapchk Functions
#include <malloc.h>
R1mam The _heapchk routines help to debug heap-related problems by checking for minimal con
sistency of the heap.
In large data models (that is, compact-, large-, and huge-model programs), _heapchk maps
to _tbeapchk. In small data models (tiny-, small-, arid medium-model programs),
_heapchk maps to _nheapchk.
Return Value All four routines return an integer value that is one of the following manifest constants (de
fined in MALLO C.H):
Constant Meaning
r
=r
Examp• �� �����������������������---���
' * H EA P CH K . C T h i s p r � g r a m c he c k s t h e h e a p for c o n s i s t ency
* a nd p r i n t s an a p p r op r i a t e mes s a ge .
*I
I
�l
1
#i n c l u d e <ma l oc . h>
#i n c l ude < s t i o . h >
v o i d ma i n < >
(
i nt h e a p t a t u s :
c h a r *buf er :
I * Al l o c a e a nd d ea l l o c a t e s ome memory * /
i f { C b uff r - ( c h a r * ) ma l l oc C 100 ) ) ! = N U L L
free ( u f f e r > :
(
case _ EAPOK :
pri tfC " OK - heap i s fi ne\n " ) ;
bre k:
case - EAP EMPTY :
pri tfC " OK - h e a p i s empty \ n " > :
bre k:
case - E A P BADB E G I N :
pri t f C " E RROR - b a d s t a rt of h e a p \ n " > :
'T '
bre k:
case - EAPBADNO D E :
i
pri t f C " E R RO R - b a d n o d e i n hea p \ r " > :
Output I
OK - heap i � f i ne
411 _heapmin Functions
Rematlrs The _heapmin functions minimize the heap by releasing unused heap memory to the oper
ating system.
In large data models (that is, compact-, large-, and huge-model programs), _heapmin
maps to _theapmin. In small data models (tiny-, small-, and medium-model programs),
_heapmin maps to _nheapmin.
Based-heap segments are never freed (i.e., unlinked from the based heap list and released
back to the operating system) by the _bheapmin function. The _bfreeseg function is used
for that purpose.
Return Value The _heapmin functions return 0 if the function completed successfully, or -1 in the case
of an error.
DBScrlptlon Check heaps for minimal consistency and set the free entries to a specified value.
#include <malloc.h>
Remarks The _heapset family of routines helps debug heap-related problems in programs by show
ing free memory locations or nodes unintentionally overwritten.
The _heapset routines first check for minimal consistency on the heap in a manner identi
cal to that of the _heapchk functions. After the consistency check, the _heapset functions
set each byte of the heap's free entries to the fill value. This known value shows which
memory locations of the heap contain free nodes and which locations contain data that
were unintentionally written to freed memory.
In large data models (that is, compact-, large-, and huge-model programs), _heapset maps
to _fheapset In small data models (tiny-, small-, and medium-model programs), _heapset
maps to _nheapset
413 _heapset Functions
Return Value All four routines return an int whose value is one of the following manifest constants
(defined in MALLOC.H):
Constant Meaning
/ * H EA P S ET . C : T h i s p r o g r a m c h e c k s t h e h e a p a n d f i l l s i n f r e e en t r i e s
* wi th the cha racter Z ' ' .
*/
#i n c l u d e <ma l l oc . h >
#i n c l u d e < s t d i o . h >
#i n c l u d e < s td l i b . h >
v o i d ma i n ( )
(
i nt heapstatus :
c h a r *buffe r :
�
I
_heapse FuncUons 414
I
i f ( C b u f �e r ma l l oc C 1 ) )
= == NULL I * M a k e s u re h e a p i s i n i t i a l i z ed * /
h e a p s t a tJs
exi t ( 1 0 ) ;
= _h e a p s et C ' Z ' l : I * F i l l i n f re e e nt r i es * /
swi t c h ( � e a p s t a t u s )
(
�
c a s e i H EAPOK :
br�a k ;
p r n t f ( " O K - h e a p i s fi n e \ n " ) :
c a s e JH EAP EM PTY :
p r � n t f ( " O K - h e a p i s empty \ n " ) ;
b r�a k ;
c a s e JH E A P BADB E G I N :
p r � n t f ( " E RROR - b a d s t a rt o f h e a p \ n " ) ;
b r ea k ;
c a s e JH EA P BADNOD E :
p r � n t f ( " E RROR - b a d n o d e i n h e a p \ n " l ;
b r ea k ;
�
f ree ( bu f e r ) ;
I
Output
OK - hea p fi ne
415 _heapwalk Functions
Descrlpl/on Traverse the heap and return information about the next entry.
include <malloc.h>
Remarks The _heapwalk family of routines helps debug heap-related problems in programs.
The _heapwalk routines walk through the heap, traversing one entry per call, and return a
pointer to a _heapinfo structure that contains information about the next heap entry. The
_heapinfo structure, defined in MALLOC.H, contains the following elements:
Element Description
A call to _heapwalk that returns _HEAPOK stores the size of the entry in the _size field
and sets the _useflag field to either _FREEENTRY or _USEDENTRY (both are constants
defined in MALLOC.H). To obtain this information about the first entry in the heap, pass
the _heapwalk routine a pointer to a _heapinfo structure whose _pentry field is NULL.
The various _heapwalk functions walk through and gather information on these heaps:
In large data models (that is, compact-, large-, and huge-model programs), _heapwalk
maps to _theapwalk. In small data models (tiny-, small-, and medium-model programs),
_heapwalk maps to _nheapwalk.
Return Value All three routines return one of the following manifest constants (defined in MALLO C.H):
Constant Meaning
_HEAPBADNODE A bad node has been found, or the heap "is damaged.
_HEAPBADPTR The _pentry field of the _heapinfo structure does not contain
a valid pointer into the heap. ·
v o i d h e a pd ump ( v o i d ) ;
v o i d ma i n ( )
{
c h a r *buffe r ;
h e a pdump ( ) ;
i f ( ( bu f f e r = ma l l oc ( 5 9 > > ! = N U L L >
{
h e a pdump ( ) ;
free ( buffer ) ;
J
h e a pdump ( ) ;
v o i d h e a p d ump ( v o i d
{
s t r u c t _hea p i n fo h i n fo ;
i nt hea p s t a t u s ;
h i n fo . _p e n t ry = N U L L ;
w h i l e < < h e a p s t a t u s = _h e a pwa l k ( & h i nfo > > == _H EAPOK
{
p r i n t f ( " %6 s b l o c k a t % Fp of s i ze %4 . 4 X \ n " ,
( h i n f o . _u s e f l a g == _U S E D E NT RY ? " U S E D " : " F R E E " ) ,
h i n f o . _pent ry , h i n f o . _s i z e ) ;
s w i tc h ( h e a p s t a t u s )
{
c a s e _H E A P E M PTY :
p r i n t f ( " O K - empty h ea p \ n " > :
b r ea k ;
c a s e _H EAP E N D :
p r i n t f ( " O K - end o f h ea p \ n " ) ;
b r ea k ;
c a s e _H EAPBAD PT R :
p r i n t f ( " E RRO R - b a d p o i n t e r to h ea p \ n " > :
b r ea k ;
c a s e _H EAPBADB E G I N :
p r i n t f ( " E RRO R - b a d s t a rt of h ea p \ n " ) ;
brea k ;
c a s e _H EAPBADN OD E :
p r i n t f ( " E RROR - b a d node i n h ea p \ n " ) ;
brea k ;
_heapwalk Functions 418
l
Output
U S E D b l o c k a t 0067 : 10 3 E of s i ze 000 E
U S E D b l o c k a t 0067 : 104E of s i ze 0 1 F4
l
U S E D b l o c k ! a t 0067 : 1 244 of s i ze 0026
USED b l o c k a t 0067 : 1 2 6 C of s i ze 0200
FREE b l o c k at 006 7 : 1 4 6 E of s i ze 0890
OK - end o f h e a p
U S E D b l o c k a t 0067 : 1 0 3 E of s i ze 000 E
U S E D b l o c k a t 0067 : 10 4 E of s i ze 0 1 F4
l
U S E D b l o c k a t 0067 : 1 244
USED b l o c k a t 0067 : 1 2 6 C
USED b l o c k at 0067 : 14 6 E
of
of
of
s i ze
s i ze
s i ze
0026
0200
003C
FREE b l o c k , a t 006 7 : 14AC of s i ze 0852
OK - end of h e a p
U S E D b l o c k a t 006 7 : 1 0 3 E of s i ze 000 E
U S E D b l o c k a t 0067 : 1 04E of s i ze 0 1 F4
U S E D b l o c k a t 0067 : 1 244 of s i ze 0026
USED b l o c k at 0067 : 1 2 6 C of s i ze 0200
end o f � e a p
of s i ze 0852
OK -
419 hfree
Rematits The hfree function deallocates a memory block; the freed memory is returned to the oper
ating system. The memblock argument points to a memory block previously allocated
through a call to halloc. The number of bytes freed is the number of bytes specified when
the block was allocated.
Note that attempting to free an invalid memblock argument (one not allocated with halloc)
may affect subsequent allocation and cause errors.
I * H A L LOC . C : T h i s p ro g r a m u s e s h a l l oc to a l l o c a t e s p a c e f o r 30 , 000 l on g
* i n t e g e r s , t h e n u s e s h f r e e t o d ea l l o c a t e t h e memory .
*I
v o i d ma i n ( )
(
l ong _h u g e * h buf :
/ * Al l o c a t e h u g e buffer * /
h b u f - < l on g _h u g e * ) h a l l oc < 30000 L , s i zeof C l on g > > :
i f ( hbuf � NULL )
p r i n t f ( " I n s u f f i c i ent memo ry a v a i l a b l e \ n " > :
el se
p r i n t f ( " Memory s u c c e s s fu l l y a l l o c a t ed \ n " > :
hfree 420
/ * Free h ge buffer * /
h f ree < h b f ) ;
Output
Memo ry s u c c e s f u l l y a l l oca t ed
421 hypot, hypotl
#include <math.h>
x, y Floating-point values
Remarks The hypot and hypotl functions calculate the length of the hypotenuse of a right triangle,
given the length of the two sides x and y (or xi and yl). A call to hypot is equivalent to the
following:
The hypotl function uses the 80-bit, 1 0-byte coprocessor fonn of arguments and return
values. See the reference page on the long double functions for more details on this data
type.
Return Value The functions return the length of the hypotenuse. If an overflow results, the functions re
turn HUGE_VAL and set errno to ERANGE.
Compatlblllty hypot
hypotl
I * H Y P OT . C : T h i s p r o g r a m p r i n t s t h e hypot e n u s e of a r i g h t t r i a n g l e . * /
v o i d ma i n ( )
(
l
doubl e x 3.0, y = 4.0;
p r i n t f ( " l f a r i g h t t r i a ng l e h a s s i des %2 . l f a n d %2 . l f , •
" i t s hypot e n u s e i s % 2 . l f \ n " , x , y , hypot ( x , y > > ;
Output
II
I f a r i g h t t r i a n gl e h a s s i des 3 . 0 a n d 4 . 0 , i t s hypot e n u s e i s 5 . 0
423 _imagesize Functions
#include <graph.h>
Remarks The functions in the _imagesize family return the number of bytes needed to store the
image defined by the bounding rectangle and specified by the coordinates given in the
·
function call.
The _imagesize function defines the bounding rectangle in terms of view-coordinate
points (xl , yl ) and (x2, y2).
The _imagesize_w function defines the bounding rectangle in terms of window-coordinate
points (xl , yl ) and (x2, y2).
The _imagesize_wxy function defines the bounding rectangle in terms of the window
coordinate pairs pwxyl and pwxy2.
The number of bytes needed to store the image is determined by the following formula:
xwi d = a b s ( x l - x 2 ) + 1 ;
ywi d = a b s C y l - y 2 ) + 1 ;
s i z e = 4+ C C l on g ) C C xw i d * b i t s_p e r_p i x e l +7 ) / 8 ) * ( 1 o n g ) yw i d ) ;
Return Value The function returns the storage size of the image in bytes. There is no error return.
I
I
See Also _getimage functions, _getvideocontig, _putimage functions
Remarks The inp and inpw functions read a byte and a word, respectively, from the specified input
port. The input value can be any unsigned integer in the range 0 65,535 .
-
To use inp and inpw in OS/2 protected mode, you must use a .DEF file to declare the
IOSEG segment that the run-time library uses to perform input/output on the port. In addi
tion, the intrinsic (/Oi) versions of these functions do not work unless you put the code in a
. segment that is marked with the IOPL keyword in the .DEF file.
Because you cannot do IOPL from a regular code segment, the run-time library
declares a separate code segment called _IOSEG. In order to use inp, inpw, outp,
or outpw in any of the protected-mode run-time libraries (?LIBCP, LLIBCDLL,
LLIBCMT, or CDLLOBJS-based DLL), you must have a .DEF file containing this line:
S E GMENTS _ I O S E G C LASS ' I OS E G_COD E ' I O P L
Return Value The functions return the byte or word read from port. There is no error return.
#include <dos.h>
int int86( int intnum, union REGS *inregs, union REGS *outregs );
Rematts The int86 function executes the 8086-processor-family interrupt specified by the interrupt
number intnum. Before executing the interrupt, int86 copies the contents of inregs to the
corresponding registers. After the interrupt returns, the function copies the current register
values to outregs. It also copies the status of the system carry flag to the cflag field in the
outregs argument. The inregs and outregs arguments are unions of type REGS. The union
type is defined in the include file DOS.H.
Do not use the int86 function to call interrupts that modify the DS register. Instead, use the
int86x function. The int86x function loads the DS and ES registers from the segregs para
meter and also stores the DS and ES registers into segregs after the function call.
Return Value The return value is the value in the AX register after the interrupt returns. If the cftag field
in outregs is nonzero, an error has occurred; in such cases, the -dosermo variable is also
set to the corresponding error code.
v o i d ma i n { )
(
u n i on REGS i n regs , o u t r e g s ;
/ * Di s p l a y r e s u l t s . * /
p r i n t f { " C u r s o r po s i t i on \ n \ t Row : % d \ n \ t C o l umn : %d \ n " ,
o u t r e g s . h . d h , o u t regs . h . d l l ;
•
Output
C u r s o r po s i t i on
Row : 2
C o l umn : 0
Cursor shape
Sta rt : 6
End : 7
int86x
Description
I Executes the 8086 interrupt; accepts segment-register values.
428
#include <dos.h>
int int86x( int intnum, union REGS *inregs, union REGS *outregs,
struct SREGS *segregs );
Remarks The int86x function executes the 8086-processor-family interrupt specified by the inter
rupt number intnum. Unlike the int86 function, int86x accepts segment-register values in
segregs, enabling programs that use large-model data segments or far pointers to specify
which segment or pointer should be used during the system call.
Before executing the specified interrupt, int86x copies the contents of inregs and segregs
After the interrupt returns, the function copies the current register values to outregs, cop
· to the corresponding registers. Only the DS and ES register values in segregs are used.
ies the current ES and OS values to segregs, and restores DS. It also copies the status of
the system carry flag to the ctlag field in outregs.
The REGS and SREGS types are defined i n the include file DOS.ff.
.
Segment values for the segregs argument can be obtained by using either the segread func
tion or the FP_SEG macro.
Return Value The return value is the value in the AX register after the interrupt returns. If the cflag field
in outregs is nonzero, an error has occurred; in sucli cases, the _dosermo variable is also
set to the corresponding error code.
I * I NT86 X . C : I n t h i s p r o g r a m , i n t86x e x e c u t e s a n I NT 2 1 H i n s t r u c t i on
* t o i n v o k e DOS s y s t em c a l l 43H ( c h a nge f i l e a t t r i b u t e s ) . T h e p r o g r a m
* u s e s i n t86x b e c a u s e t h e f i l e , wh i c h i s refe r e n c ed wi t h a fa r p o i nt e r ,
* may be i n a s e gment o t h e r t h a n t h e d e fa u l t d a t a segme n t . T h u s , t h e
* p r o g r a m mu s t e x p l i c i t l y set t h e D S reg i s t e r w i t h t h e S R E GS s t r u c t u r e .
*/
v o i d ma i n ( )
{
u n i on RE GS · i n regs , o u t r e g s ;
s t r u c t S R E GS s e g r e g s ;
i nt res u l t ;
Output
At t r i b s = 0x0020
intdos 430
#include <dos.h>
Remarks The intdos function invokes the DOS system call specified by register values defined in
inregs and returns the effect of the system call in outregs. The inregs and outregs argu
ments are unions of type REGS. The REGS type is defined in the include file DOS.H.
To invoke a system call, intdos executes an INT 2 1 H instruction. Before executing the in
struction, the function copies the contents of inregs to the corresponding registers. After
the INT instruction returns, intdos copies the current register values to outregs. It also cop
ies the status of the system carry flag to the cflag field in outregs. A nonzero cflag field in
dieates the flag was set by the system call and also indicates an error condition.
The intdos function is used to invoke DOS system calls that take arguments for input or
output in registers other than DX (DH/DL) and AL. The intdos function is also used to in
voke system calls that indicate errors by setting the carry flag. Under any other conditions,
the bdos function can be used.
Do not use the intdos function to call interrupts that modify the DS register. Instead, use
the intdosx or int86x function.
Return Value The intdos function returns the value of the AX register after the system call is completed.
If the cflag field in outregs is nonzero, an error has occurred and _doserrno is also set to
the corresponding error code.
t
See Also bdos, intdosx
v o i d ma i n ( )
(
u n i on REGS i n regs , o u t regs ;
Output
D a t e : 6 / 1 6 / 1 989
intdosxlI 432
I #include <dos.h>
int intdosx( union REGS *inregs, union REGS *outregs, struct SREGS *segregs );
Remarks The intdosx function invokes the DOS system call specified by register values defined in
inregs and returns the results of the system call in outregs. Unlike the intdos function,
intdosx accepts segment-register values in segregs, enabling programs that use large
model data segments or far pointers to specify which segment or pointer should be used
during the system call. The REGS and SREGS types are defined in the include file DOS.H.
To invoke a system call, intdosx executes an INT 21 H instruction. Before executing the in
struction, the function copies the contents of inregs and segregs to the corresponding regis
ters. Only the OS and ES register values in segregs are used. After the INT instruction
returns, intdosx copies the current register values to outregs and restores OS. It also copies
the status of the system carry flag to the cflag field in outregs. A nonzero cflag field indi
cates the flag was set by the system call and also indicates an error condition.
The intdosx function is used to invoke DOS system calls that take an argument in the ES
register or that take a OS register value different from the default data segment.
Segment values for the segregs argument can be obtained by using either the segread func
tion or the FP_SEG macro.
Return Valu The intdosx function returns the value of the AX register after the system call is com
pleted. If the cflag field in outregs is nonzero, an error has occurred; in such cases,
_doserrno is also set to the corresponding error code.
Campatibili � I
D ANSI • DOS D OS/2 D UNIX D XENIX
Exampre ___,,__����-
1 * I NTDOS . C * /
Ii i n c l u d e d o s . h >
#i n c l u d e s t d i o . h >
433 intdosx
v o i d ma i n ( )
[
u n i on REGS i n regs , o u t r e g s ;
s t ruct SREGS s eg r e g s ;
Output
#include <ctype.h>
c Integer to be tested
Rematics Each function in the is family tests a given integer value, returning a nonzero value if the
integer satisfies the test condition and 0 if it does not. The ASCII character set is assumed.
The is functions and their test conditions are listed below:
The isascii routine produces meaningful results for all integer values. However, the remain
ing routines produce a defined result only for integer values corresponding to the ASCII
character set (that is, only where isascii holds true) or for the non-ASCII value EOF (de
fined in STDIO.H).
These routines are implemented both as functions and as macros. For details on choosing a
function or a macro implementation, see Section 1 .4, "Choosing Between Functions and
Macros."
Return Value These routines return a nonzero value if the integer satisfies the test condition and 0 if it
does not.
Compat/bl//ty isalnum, isalpha, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper,
isxdigit
isascii
Example �������-
�
(
p h a
i
)
<
( ch
ch
ch
?
;
;
;;;
) ;
;
) ? "AS" )
print� ( % 3s i s l o w er< ch
) ? "C" )
11 o n
print ;
) ? " G" )
• L•
;;
•, ) ? ) ;
000201
Output
AS
AS
AS
C
C
C
38393a 89
3c3d3b3e
AN AS D G PR x
AN AS D G PR x
AS G PU PR
AS G PU PR
4041423f
< AS G PU PR
= AS G PU PR
> AS G PU PR
? AS G PU PR
@ AS G PU PR
A AN A AS G PR u x
B AN A AS G PR u x
437 isatty
Remarks The isatty function detennines whether handle is associated with a character device (a ter
minal, console, printer, or serial port).
Return Value The isatty function returns a nonzero v alue if the device is a character device. Otherwise,
the return value is 0.
v o i d ma i n ( )
(
i f ( i s a tty ( f i l eno C s t d o u t ) ) )
p r i n t f ( " s tdout h a s not been red i rected t o a f i l e \ n " ) ;
el se
p r i n t f ( " s t dout h a s been red i rected t o a f i l e \ n " l ;
Output
Remarks The itoa function converts the digits of the given value argument to a null-terminated char
-�-· II
acter string and stores the result (up to 17 bytes) in string. The radix argument specifies the
base of value; it must be in the range 2-36. If radix equals 10 and value is negative, the
first character of the stored string is the minus sign (-).
'
Campallblllty D ANSI • DOS • OS/2 0 UNIX 0 XEN IX
I
See Also ltoa, ultoa
Exampm ����������������������������
I * I TOA . C : 1 h i s p r o g r a m c o n v e r t s i n t e g e r s of v a r i ous s i z e s to s t r i n g s
J,
* in vari o s radi xes .
*/
l
1
#i n c l ude < s d l i b . h >
#i n c l ude < s d i o . h >
: :: :::
oi i
� h e r [ 20 ] ;
i nt i = 344 5 ;
l ong 1 = - 344 1 1 5 L ;
unsi gned 1 on g u l = 1 2 34 5 6 7 8 90 U L ;
1
I
'
!
01 Uoa
i t oa < i , b u f fe r , 1 0 ) ;
pri ntf ( " St r i n g o f i n t e g e r %d < ra d i x 10 ) : % s \ n " , i , b u f f e r ) ;
i t oa ( i , b u f fe r , 1 6 ) ;
pri ntf( " St r i n g o f i nt e g e r %d < ra d i x 1 6 ) : 0x% s \ n " , i , buffer ) ;
i t oa ( i , buffe r , 2 ) ;
pri ntf ( " St r i n g of i nt e g e r %d < ra d i x 2 ) : % s \ n " , i , b u f f e r ) ;
l t o a ( 1 , b u f fe r , 1 6 ) ;
p r i n t f ( " St r i n g o f l on g i n t %l d ( ra d i x 1 6 ) : 0x%s \ n " , 1 , buffer ) ;
u l t o a ( u l , b u f fe r , 1 6 > ;
p r i n t f ( " St r i n g o f u n s i g n ed l on g % l u < ra d i x 1 6 ) : 0x%s \ n " , u l , b u f f e r ) ;
Output
Remades The kbhit function checks the console for a recent keystroke. If the function returns a non
zero value,_ a keystroke is waiting in the buffer. The program can then call getch or getche
to get the keystroke.
R1tum Valu1 The kbhit function returns a nonzero value if a key has been pressed. Otherwise, it re
turns O.
I
* T h e p r o g a m c a n c a l l g e t c h o r getc h e t o get t h e key s t ro k e .
*I
v o i d ma i n ( )
{
I * D i s p l y mes s a g e u nt i l k ey i s p r e s s e d . * /
whi l e( ! bhi t ( ) )
c p u t s " H i t me ! ! • ) ;
I * U s e g t c h to t h row k ey away . * /
p r i n t f ( \ n Key s t r u c k wa s ' %c ' \ n " , get c h ( ) > :
getch ( ) ;
Output I
l
H i t me ! ! H i me ! ! H i t me ! ! H i t me ! ! H i t me ! ! H i t me ! ! H i t me ! !
Key s t r u c k a s ' k '
441 labs
#include <math.h>
n Long-integer value
Remarks The labs function produces the absolute value of its long-integer argument n.
Return value The labs function returns the absolute value of its argument. There is no error return.
v o i d ma i n ( )
(
i nt i x = -4 , i y ;
l ong l x = -41567 L , l y ;
doubl e dx = - 3 . 1 4 1 5 9 3 , dy ;
iy = abs ( i x ) ;
p r i n t f ( " T h e a b s o l u t e va l u e of %d i s %d \ n " , i x , i y ) ;
l y = l abs ( l x ) ;
p r i n t f ( " T h e a b s o l u t e va l ue of %l d i s % l d \ n " , l x , l y ) ;
dy = f a b s ( dx ) ;
p r i ntf ( " T h e a b s o l u t e v a l ue of %f i s % f \ n " , dx , dy ) ;
labs 442
Output
T h e a b s o l u t e v a l u e of - 4 i s 4
T h e a bs o l u t e v a l u e of - 4 1 5 6 7 i s 4 1 5 6 7
T h e a bs o l u t e v a l u e of - 3 . 1 4 1 5 9 3 i s 3 . 1 4 1 5 9 3
443 ldexp, ldexpl
#include <math.h>
x Floating-point value
exp Integer exponent
Remarks The ldexp and ldexpl functions calculate the value of x * 2exp.
Return Value The ldexp and ldexpl functions return x * 2exp. If an overflow results, the functions return
± HUGE_VAL (depending on the sign of x) and set errno to ERANGE.
The ldexpl function uses the 80-bit, 1 0-byte coprocessor form of arguments and return
values. See the reference page on the long double functions for more details on this data
type.
Compat/bHity Idexp
ldexpl
Exampm ��������-
1* LDEX P . C */
#i n c l ude <ma t h . h >
#i n c l ude < s t d i o . h >
ldexp, l exp/ 444
v o i d ma i n ( )
{
doubl e x = 4.0, y;
i nt p = :
y = l d ex ( x , p > :
p r i n t f { %2 . l f t i mes two t o t h e powe r of %d i s %2 . l f \ n " , x , p , y >:
Output
#include <Stdlib.h>
numer Numerator
denom Denominator
Remarks The ldiv function divides numer by denom, computing the quotient and the remainder. The
sign of the quotient is the same as that of the mathematical quotient. Its absolute value is
the largest integer that is less than the absolute value of the mathematical quotient. If the
denominator is 0, the program will terminate with an error message.
The ldiv function is similar to the div function, with the difference being that the argu
ments and the members of the returned structure are all of type long int.
Element Description
Return Value The ldiv function returns a structure of type ldiv_t, comprising both the quotient and the
remainder.
#i n c l u d e < s t d l i b . h >
#i n c l u d e <ma t h . h >
#i n c l u d e < s t d i o . h >
/div 446
v o i d ma i n ( )
(
l ong x = 5 149627 , y = 2 3487 9 ;
l d i v_t d i v_r e s u l t ;
d i v_res u l t = l di v C x , y ) ;
p r i n t f C F o r %l d I % l d , t h e q u o t i ent i s % l d , a nd t h e rema i n d e r i s % l d \ n " ,
, y , d i v_r e s u l t . q uot , d i v_re s u l t . rem ) ;
Output
char *lf'md( const void *key, const void *base, unsigned int *num, unsigned int width,
int ( *compare )( const void *eleml, const void *elem2 ) );
Remarks The lfind function perfonns a linear search for the value key in an array of num elements;
each element is width bytes in size. (Unlike bsearch, lfind does not require the array to be
sorted.) The base argument is a pointer to the base of the array to be searched.
The compare argument is a pointer to a user-supplied routine that compares two array ele
ments and then returns a value specifying their relationship. The lfind function c alls the
compare routine one or more times during the search, passing pointers to two array ele
ments on each call. This routine must compare the elements, then return one of the follow
ing values:
Value Meaning
Return Value If the key is found, lfind returns a pointer to the element of the array at base that matches
key. If the key is not found, lfind returns NULL.
Exampm ��+-�������-
j ..
1
#i n c l ude < s e r c h . h>
#i n c l ude < s t i n g . h>
#i n c l ude < s t i o . h >
�oi d �
i n t c ompa re ( c h a r **a rg l , c h a r * * a r g 2 > :
ma i n ( i t a rgc , c h a r * * a r g v >
j
c h a r **resul t ;
c h a r * k.ey " h el l o " ;
r
i nt c ompa re ( a r ** a rg l , c h a r **a rg2
(
1
r e t u r n ( s r cmp1 C *a r g l , *a rg2 ) > :
Output
[ C : \ L I B R E F ] l f i nd W h a t i f I s a i d H e l l o worl d
H e l l o found
449 _lineto Functions
#include <graph.h>
x, y End point
wx, wy End point
R1matlcs The functions in the _lineto family draw a line from the current graphics position up to
and including the destination point. The destination point for the _lineto function is given
by the view-coordinate point (x, y). The destination point for the _lineto_w function is
given by the window-coordinate point (wx, wy).
The line is drawn using the current color, logical write mode, and line style. If no error
occurs, _lineto sets the current graphics position to the view-coordinate point (x, y);
_lineto_w sets the current position to the window-coordinate point (wx, wy).
If you use _floodfill to fill in a closed figure drawn with _lineto calls, the figure must be
drawn with a solid line-style pattern.
R1tum Value The _lineto and _lineto_w routines return a nonzero value if anything is drawn; otherwise,
they return 0.
v o i d ma. i n ( )
(
s h o rt x , , x i nc , y i n c , c o l o r .. 1 ;
s t ruct v i e o c o n f i g v ;
I * Fi nd a v a l i d g ra p h i c s mode . * I
i f ( ! _s e t i d eomod e ( _MAXCO LORMODE ) )
exi t C >;
_getv i d eo onfi g ( &v > :
x i nc = v . umx p i x e l s I 50 ;
yi nc - v . umyp i x e l s I 50 ;
t
)
getch C > :
#include <locale.h>
Remarks The localeconv function gets detailed infonnation on the locale-specific settings for
numeric fonnatting of the program's current locale. This infonnation is stored in a struc
ture of type lconv.
The lconv structure, defined in LOCALE.H, contains the following elements:
Element Description
The elements of grouping and mon_grouping are interpreted according to the following
rules:
Value Interpretation
CHAR_MAX No further grouping is to be performed.
0 The previous element is to be repeatedly used for the re
mainder of the digits.
n The integer value n is the number of digits that make up the
current group. The next element is examined to determine the
size of the next group of digits before the current group.
The values for p_sign_posn and n_sign_posn are interpreted according to the following
rules:
Value Interpretation
Return Value The localeconv function returns a pointer to a structure of lconv type. Calls to the
setlocale function with category values of LC_ALL, LC_MONETARY, or
LC_NUMERIC will overwrite the contents of the structure.
Description Converts a time value and corrects for the local time zone.
#include <time.h>
structure of type tm. The long value timer represents the seconds elapsed since 00:00:00,
Remarks The localtime function converts a time stored as a time t value and stores the result in a
January l , 1 970, Greenwich mean time; this value is usually obtained from the time
function.
The fields of the structure type tm store the following values:
Note that the gmtime, mktime, and localtime functions use a single statically allocated
tm structure for the conversion. Each call to one of these routines destroys the result of the
previous call.
The localtime function makes corrections for the local time zone if the user first sets the
environment variable TZ. When TZ is set, three other environment variables (timezone,
daylight, and tzname) are automatically set as well. See tzset for a description of these
variables.
The TZ variable is not part of the ANSI standard definition of localtime but is a Microsoft
extension.
455 locallime
Rlllum Value The localtime function returns a pointer to the structure result. DOS and OS/2 do not ac
commodate dates prior to 1 980. If the value in timer represents a date prior to January 1 ,
1 980, the function returns NULL.
#i n c l u d e < s t d i o . h >
#i n c l u d e < s t r i n g . h >
#i n c l ud e < t i me . h >
v o i d ma i n ( )
(
s t r u c t tm * n ewt i me ;
c h a r a m_pm [ ] = " AM " :
t i me_t l on g_t i me ;
Output
F r i J u n 1 6 06 : 2 7 : 02 AM
locking 456
#include <Sys\locking.h>
#include <io.h> Required only for function declarations
Remarks The locking function locks or unlocks nbytes bytes of the file specified by handle. Lock
ing bytes in a file prevents access to those bytes by other processes. All locking or unlock
ing begins at the current position of the file pointer and proceeds for the next nbytes bytes.
It is possible to lock bytes past the end of the file.
The mode argument specifies the locking action to be performed. It must be one of the fol
lowing manifest constants:
Constant Action
LK_LOCK Locks the specified bytes. If the bytes cannot be locked, imme
diately tries again after 1 second. If, after IO attempts, the
bytes cannot be locked, returns an error.
LK NBLCK Locks the specified bytes. If bytes cannot be locked, returns
an error.
LK_NBRLCK Same as LK_NBLCK.
LK_RLCK Same as LK_LOCK.
LK_UNLCK Unlocks the specified bytes. (The bytes must have been pre
viously locked.)
More than one region of a file can be locked, but no overlapping regions are allowed.
When a region of a file is being unlocked, it must correspond to a region that was pre
viously locked. The locking function does not merge adjacent regions; if two locked re
gions are adjacent, each region must be unlocked separately.
Regions should be locked only briefly and should be unlocked before closing a file or exit
ing the program.
467 locking
The locking function should be used only under OS/2 or under DOS versions 3.0 and later;
it has no effect under earlier versions of DOS. Also, file sharing must be loaded to use the
locking function. Note that under DOS versions 3.0 and 3. 1 , the files locked by parent
processes may become unlocked when child processes exit.
Retum Value The locking function returns 0 if successful. A return value of -1 indicates failure, and
ermo is set to one of the following values:
Value Meaning
v o i d ma i n ( )
(
i n t f h , n umrea d ;
l ong pos r e s u l t ;
c h a r buf e r [ 4 0 ] ;
i f ( ( fh - l l 1 1 ( _o s ma j o r < 3 ) )
exi t C 1 > ;
l
I * Loc k ome byt e s a n d read t h em . Then u n l o c k . * /
i f ( l oc k n g ( f h , L K_N B LC K , 3 0 L ) ! = - 1 )
(
pri nt C " N o o n e c a n c h a n g e t h e s e by t e s w h i l e I ' m rea d i n g t h em\ n " ) ;
n umre d - rea d ( f h , buffe r , 30 ) ;
pri nt C " %d byt e s read : % . 30s \ n " , numrea d , buffer ) ;
l oc k i g ( fh , L K_U N LC K , 3 0 L ) ;
l
pri nt C " N ow I ' m d o n e . Do w h a t you w i l l wi t h t h em\ n " l ;
}
: e r ro
el s
C " Loc k i n g fa i l ed \ n " ) ;
cl ose( f );
�e lr
c a n h a n g e t h e s e bytes w h i l e I ' m •ea d i n g t h em
30 byt e s rea d : / * LOC K I N G . C : T h i s p ro g r a m ope
N ow I ' • d o n . Do what y o u wi l l wi t h t h em
I
I
459 log Functions
#include <math.h>
Remarks The log and loglO functions calculate the natural logarithm and the base- 10 logarithm, re
spectively, of x. The logl and loglOl functions are the 80-bit counterparts and use the 80-
bit, 1 0-byte coprocessor form of arguments and return values. See the reference page on
the long double functions for more details on this data type.
Return Value The log functions return the logarithm of the argument x. If x is negative, the functions
print a DOMAIN error message to stderr, return the value -HUGE_VAL, and set errno to
EDOM. If x is 0, the functions print a SING error message to stderr, return the value
-HUGE_VAL, and set errno to ERANGE.
Error handling can be modified by using the matherr or _matherrl routine.
logl, loglOl
I * LOG . C : T h i s p r o g r a m u s e s l og a n d l o g 1 0 to c a l c u l a t e t h e n a t u r a l
* l o g a r i t hm a n d t h e ba s e - 1 0 l og a r i thm of 9 , 000 .
*I
�1
v o i d ma i n ( )
{ !
doubl e x 9000 . 0 ;
doubl e y ;
y = l og ( � > :
p r i ntf ( " l o g ( % . 2 f ) = %f\ n " , x , y > :
y = l og10 ( x ) ;
pri ntf( " l og10( % . 2f J = %f\n " , x, y J ;
I
Output
i! =
l o g ( 9000 . 00 1 = 9 . 1 04980
l og 1 0 ( 9000 . 0 J 3 . 954243
I
461 long double Functions
The 8087 family of numeric coprocessor chips supports the 80-bit precision floating-point
data type. In Microsoft C, version 6.0, the long double functions, whose names end with 1,
map the C long double type into this 80-bit, 10-byte form. Unlike the regular floating
point functions (such as acos), which return values of type double, these long double func
tions (such as acosl) return values of type long double. The long double functions also
return their values on the coprocessor stack for all calling conventions.
The long double type is also supported by the addition of the "L" prefix for a floating
point format specification in the printf and scanf family of functions.
The long double versions are described on the reference pages for their regular counter
parts. These are the regular C run-time math functions with corresponding long double
equivalents:
Regular Function Long Double Form
acos acosl
asin asinl
atan atanl
atan2 atan21
atof atold
cabs cabsl
ceil ceill
cos cosl
cosh coshi
exp expI
fabs fabsl
floor floorI
fmod fmodl
frexp frexpl
hypot hypotl
Idexp ldexpl
log logl
loglO loglOI
matherr matherrl
modf modfl
long do le Functions 462
pow powI
sin sinl
sinh sinhl
sqrt sqrtl
tan tanl
tanh tan hi
463 longjmp
#include <Setjmp.h>
Remarks The longjmp function restores a stack environment and execution locale previously saved
in env by setjmp. The setjmp and longjmp functions provide a way to execute a nonlocal
goto; they are typically used to pass execution control to error handling or recovery code
in a previously called routine without using the normal call and return conventions.
A call to setjmp causes the current stack environment to be saved in env. A subsequent
call to longjmp restores the saved environment and returns control to the point immedi
ately following the corresponding setjmp call. Execution resumes as if value had just been
returned by the setjmp call. The values of all variables (except register variables) that are
accessible to the routine receiving control contain the values they had when longjmp was
called. The values of register variables are unpredictable.
The longjmp function must be called before the function that called setjmp returns. If
longjmp is called after the function calling setjmp returns, unpredictable program be
havior results.
The value returned by setjmp must be nonzero. If value is passed as 0, the value l is substi
tuted in the actual return.
Observe the following three restrictions when using longjmp:
1 . Do not assume that the values of the register variables will remain the same. The values
of register variables in the routine calling setjmp may not be restored to the proper
values after longjmp is executed
2. Do not use longjmp to transfer control from within one overlay to within another. The
overlay manager keeps the overlay in memory after a call to longjmp.
3. Do not use longjmp to transfer control out of an interrupt-handling routine unless the
interrupt is caused by a floating-point exception. In this case, a program may return
from an interrupt handler via longjmp if it first reinitializes the floating-point math
package by calling _fpreset.
tf
I
#include <Stdlib.h>
Remarks The _lrotl and _lrotr functions rotate value by shift bits. The _lrotl function rotates the
value left. The _lrotr function rotates the value right. Both functions "wrap" bits rotated
off one end of value to the other end.
Return Value Both functions return the rotated value. There is no error return.
I * L ROT . C * /
#i n c l ude < s t d l i b . h >
#i n c l ude < s t d i o . h >
v o i d ma i n ( )
(
u n s i gned l on g v a l = 0x0fa c3 5 7 9 1 ;
Output
Oest:rlpllan Performs a linear search for a value; adds to end of list if not found.
char *Isearch( const void *key, const void *base, unsigned int *num,
unsigned int width, int ( *compare )( const void *elem], const void *elem2 ) ) ;
Rematlrs The lsearch function performs a linear search for the value key in an array of num ele
ments, each of width bytes in size. (Unlike bsearch, lsearch does not require the array to
be sorted.) The base argument is a pointer to the base of the array to be searched.
If key is not found, lsearch adds it to the end of the array.
The compare argument is a pointer to a user-supplied routine that compares two array ele
ments and returns a value specifying their relationship. The lsearch function calls the
compare routine one or more times during the search, passing pointers to two array ele
ments on each call. This routine must compare the elements, then return one of the follow
ing values:
Value Meaning
Retum Value If the key is found, lsearch returns a pointer to the element of the array at base that
matches key. If the key is not found, lsearch returns a pointer to the newly added item at
the end of the array.
467 /search
Remarks The lseek function moves the file pointer associated with handle to a new location that is
offset bytes from origin. The next operation on the file occurs at the new location. The
origin argument must be one of the following constants, which are defined in STDIO.H:
Definition
The lseek function can be used to reposition the pointer anywhere in a file. The pointer can
also be positioned beyond the end of the file. However, an attempt to position the pointer
before the beginning of the file causes an error.
Return Value ! The lseek function returns the offset, in bytes, of the new position from the beginning of
the file. The function returns -1 L to indicate an error and sets errno to one of the follow
ing values:
Value Meaning
EBADF Invalid file handle
EINVAL Invalid value for origin, or position specified by offset is
before the beginning of the file
On devices incapable of seeking (such as terminals and printers), the return value is
undefined.
469 /seek
I * L S E EK . C : T h i s p r o g r a m f i r s t opens a f i l e n a med L S E E K . C .
* I t t h e n u s e s l s e e k t o f i n d t h e be g i n n i n g of t h e f i l e ,
* t o f i nd t h e c u r rent pos i t i on i n t h e f i l e , a n d t o f i nd
* the end o f the f i l e .
*I
v o i d ma i n ( )
(
i nt f h ;
l on g pos ; I * Pos i t i on of f i l e p o i n t e r * /
c h a r buffer [ 1 0 ] ;
/ * Seek t h e beg i n n i n g o f t h e f i l e : * /
pos = l s ee k C f h , 0 L , S E E K_S ET ) ;
i f ( pos = ll >
-
/ * Move f i l e po i n t e r a l i tt l e * /
rea d ( f h , buffe r , 1 0 ) ;
I * Fi nd c u r re n t pos i t i on : * /
pos = l s e e k C f h , 0 L , S E E K_CU R ) ;
i f ( pos == - l l >
p e r ro r C � l s e e k t o c u r rent pos i t i on fa i l ed " ) ;
el se
p r i n t f C " Po s i t i on f o r c u r rent po s i t i on s e e k = % l d \ n " , p o s > :
/seek 470
I * S e t h e e n d of t h e f i l e : * /
p o s = l e e k ( f h , 0 L , S E E K_E N D ) ;
i f ( p o s == - l l >
p e r r J r ( " l s e e k to e n d fa i l e d " > ;
el se
p r i n � f ( " P o s i t i o n f o r e n d of f i l e s e e k = % l d \ n " , p o s ) ;
cl ose ( );
r
I
I
Output
I
Pos i t i on f b e g i n n i n g of f i l e s e e k = 0
P os i t i on fr r c u r r e n t p o s i t i on s e e k = 1 0
P o s i t i o n fq r e n d of f i l e s e e k = 1 1 83
411 ltoa
Rematks The lt0a function converts the digits of value to a null-tenninated character string and
stores the result (up to 33 bytes) in string. The radix argument specifies the base of value,
which must be in the range 2-36. If radix equals 10 and value is negative, the first charac
ter of the stored string is the minus sign (-).
Return Value The Itoa function returns a pointer to string. There is no error return.
v o i d ma i n ( )
(
c h a r buffe r [ 20 ] ;
i nt i = 344 5 ;
l on g 1 = - 344 1 1 5 L ;
u n s i g n ed l on g u l = 1 2 3 4 5 6 7890U L ;
lloa 472
!
l t oa C l , buffer , 1 6 > :
p r i n t f ( S t r i ng of l on g i n t % l d < ra d i x 1 6 ) : l/Jx% s \ n " , l , buffer ) ;
u l toa C u ll ,buffe r , 1 6 ) ;
p r i ntf ( " St r i ng o f u n s i gned l on g % l u ( ra d i x 1 6 ) : l/Jx% s \ n " , u l , buffer ) ;
Output
#include <Stdlib.h>
void _makepath( char *path, char *drive, char *dir, char *fname, char *ext );
Remarks The _makepath routine creates a single path name, composed of a drive letter, directory
path, file name, and file-name extension. The path argument should point to an empty buff
er large enough to hold the complete path name. The constant _MAX_PATH, defined in
STDLIB.H, specifies the maximum size path that the _makepath function can handle.
The other arguments point to buffers containing the path-name elements:
Buffer Description
jname The jname argument contains the base file name without any
extensions. Ifjname is NULL or points to an empty string, no
file name is inserted in the composite path string.
ext The ext argument contains the actual file-name extension,
with or without a leading period (.). The _makepath routine
will insert the period automatically if it does not appear in ext.
If ext is a null character or an empty string, no period is in
serted in the composite path string.
There are no size limits on any of the above four fields. However, the composite path must
be no larger than the _MAX_PATH constant. The _MAX_PATH limit permits a path name
much larger than any of the current versions of DOS or OS/2 will handle.
Examp• ---+---
1 * MAKE PATH . C * /
#i nc l ude < s d l i b . h>
#i n c l u d e < s d i o . h >
v o i d ma i n ( )
(
cha r pat _b u f f e r [_MAX_PATH l ;
char dri e [_MAX_D R I V E ] ;
cha r
char
di r
fna
� _MAX_D I R ] ;
e [_MAX_FNAM E ] ;
cha r ext _MA X_E X T ] ;
I[
.
_ma k e p a t C p a t h_b u f f e r , " c " , " \ \ c 60\ \ c l i b r e f \ \ " , " m a k e p a t h " , " c " >:
pri ntfC
I
I
475 _makepath
Output
P a t h ex t r a c ted w i t h _s pl i t p a t h :
Dri ve : c :
D i r : \ c 60\ c l i b re f \
F i l e n a me : ma kepa t h
Ext : . c
ma/lac unctions 476
Remadrs Functions in the malloc family allocate a memory block of at least size bytes. The block
may be larger than size bytes because of space required for alignment and maintenance in
formation. If size is 0, each of these functions allocates a zero-length item in the heap and
returns a valid pointer to that item.
The storage space pointed to by the return value is guaranteed to be suitably aligned for
storage of any type of object. To get a pointer to a type other than void, use a type cast on
the return value.
In large data models (compact-, large-, and huge-model programs), malloc maps to
_fmalloc. In small data models (tiny-, small-, and medium-model programs), malloc maps
to · nmalloc.
The _fmalloc function allocates a memory block of at least size bytes in the far heap,
which is outside the default data segment. The return value is a far pointer to void.
The _bmalloc function allocates a memory block of at least size bytes in the based heap
segment specified by the segment selector seg.
The malloc functions allocate memory in the heap segment specified below.
If you are creating programs to run in both real mode and protected mode, you should prob
ably bind with APILMR.OBJ as well as API.LIB and OS2.LIB. This is necessary if a pro
gram will use the nmalloc function.
The functions listed below call the malloc family of routines. In addition, the C start-up
code uses malloc to allocate storage for the environ/envp and argv strings and arrays.
The following routines call malloc:
The following routines call malloc only in the multithread run-time libraries (LLIBCMT,
LLIBCDLL, CDLLOBJS), not in the regular run-time libraries:
C5. 1 DiNerences In Microsoft C version 5. 1, the _fmallac function would retry allocating within the
default data segment (i.e., in the near heap) if sufficient memory was not available outside the default
data segment. Version 6. O returns NULL under these conditions.
In version 5. 1, the start-up code used ma/lac only if wild-card expansion was used.
The _freec( _memavl, and _memmax functions called ma/lac in version 5. 1 but do not do so in ver
sion 6.0.
returns a ( void near * ) and fmalloc returns a ( void far * ) The bmalloc function
Return Value The malloc function returns a void pointer to the allocated space. The _nmalloc function
The malloc, fmalloc and nmalloc functions return NULL if there is insufficient mem
-
ory av ailable. The bmalloc function returns _NULLOFF if there is insufficient memory
_
available.
Always check the return from the malloc function, even if the amount of memory re
quested is small.
Campatlblllty malloc
_
bmalloc, _fmalloc, nmalloc
_
v o i d ma i n ( )
'{
char *stri ng :
I * A l l o c a t e s p a c e f o r a p a t h n a me * /
s t r i ng = ma l l oc C _MAX_PATH ) ;
i f ( s t r i n g == N U L L )
p r i n t f C " I n s uf f i c i ent memo ry a v a i l a b l e \ n " ) ;
el se
p r i n t f C " M emory s p a c e a l l o c a ted f o r p a t h n a me \ n " ) ;
free ( s t r i ng ) ;
p r i ntf ( " Memory f r e ed \ n " l :
Output
#include <math.h>
Remarks The matherr functions process errors generated by the functions of the math library. The
math functions call the appropriate matherr routine whenever an error is detected. The
_matherrl function uses the 80-bit, 10-byte coprocessor form of arguments and return
values. See the reference page on the long double functions for more details on this data
type.
The user can provide a different definition of the matherr or _matherrl function to carry
out special error handling.
When an error occurs in a math routine, matherr is called with a pointer to an exception
type structure (defined in MATH.H) as an argument.
The exception structure contains the following elements:
Element Description
The type specifies the type of math error. It is one of the following values, defined in
MATH.H:
Value Meaning
The structure member name is a pointer to a null-terminated string containing the name of
the function that caused the error. The structure members argl and arg2 specify the values
that caused the error. (If only one argument is given, it is stored in argl.)
The default return value for the given error is retval. If you change the return value, re
member that the return value must specify whether an error actually occurred. If the
matherr function returns 0, an error message is displayed and errno is set to an appro
priate error value. If matherr returns a nonzero value, no error message is displayed, and
errno remains unchanged.
Return Value The matherr functions should return 0 to indicate an error, and a nonzero value to indicate
successful corrective action.
Compatibility matherr
_matherrl
See Also acos functions, asin functions, atan functions, bessel functions, cabs, cos functions, exp,
hypot, log functions, pow, sin functions, sqrt, tan functions
#i n c l u d e <ma t h . h >
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
matherr, _matherrl 482
v o i d ma i n ( )
[
/ * Do s e e r a l ma t h o p e ra t i o n s t h a t c a u s e e r ro r s . T h e ma t h e r r
* routi e h a nd l e s DOMA I N e r r o r s , b u t l et s t h e s y s t em h a n d l e
* other e r r o r s n o rma l l y .
*I
pri ntf( l og ( - 2 . 0 ) = %e\ n " , l og ( - 2 . 0 ) > :
·
pri ntf C l og 1 0 c - s . 0 > % e \ n " , l og 1 0 C - 5 . 0
= ):
pri ntf C l og ( 0 . 0 ) = %e\ n • , l og ( 0 . 0 ) > :
I * H a n d l e s v e r a l ma t h e r r o r s c a u s ed by pa s s i n g a n e g a t i v e a rg ument
* t o l og o l og 1 0 C DOMA I N e r r o r s ) . When t h i s h a ppen s , ma t h e r r ret u r n s
* t h e n a t u a l o r b a s e - 1 0 l og a r i t hm of t h e a bs o l ute v a l u e of t h e
* a rgument a n d s u p p re s s e s t h e u s u a l e r r o r mes s a ge .
*I
i n t ma t h e r r s t ruct except i on *exc ept )
(
/ * H a nd e DOMA I N e r r o r s f o r l og o r l og 1 0 . * /
i f ( e x c p t - >type == DOMA I N )
[
i f ( s t rcmp C except - > n ame , " l og • ) == 0 )
(
except - > retv a l = l og ( - C except - > a rg l ) > :
p r i n t f C " Sp e c i a l : u s i n g a b s o l ute v a l ue : %s : DOMA I N e r r o r \ n " ,
except - > n ame > :
return 1 :
�1 st
}
i f ( s t rcmp C except - > n a me , " l og 1 0 " > == 0 >
el se
[
p r i t f C " N o rma l : • ) ;
ret r n 0 ; / * E l s e u s e t h e defa u l t a c t i o n s * /
483 matherr, _matherrl
Output
S p e c i a l : u s i n g a b s o l u t e v a l u e : l og : DOMA I N e r r o r
l og ( - 2 . 0 > = 6 . 9 3 1 47 2 e - 00 1
Spec i a l : u s i n g a bs o l u t e v a l u e : l og 1 0 : DOMA I N e r r o r
l og 1 0 ( - 5 . 0 > = 6 . 989700e-001
N o rma l : l og : S I N G e r r o r
l og ( 0 . 0 > = - 1 . 7 9 7 6 93e+308
max 484
#include <Stdlib.h>
Rsmarks
I The max macro compares two values and returns the value of the larger one. The argu
ments can be of any numeric data type, signed or unsigned. Both arguments and the return
I value must be of the same data type.
Rslam Vahle I The macro returns the larger of the two arguments.
Exampm �--1-����-
/ * M I NMAX . C * / j I
#i n c l ude < s d l i b . h >
#i n c l ude < s d i o . h >
�oi d ma i n ( )
�0I ;
11 :
i nt a =
i nt b =
p r i n t f C j T h e l a rg e r of %d a n d %d i s % d \ n " , a , b , ma x ( a , b :
p r i n t f ( 1 T h e sma l l e r of %d a n d %d i s % d \ n " , a , b , mi n ( a , b
)
) ;
Output
I 10 21 i s 21
10 21 i s 1 0
T h e l a rg e r j f and
T h e s ma l l e r l of a nd
I
I
I
485 _memavl
Remarks The _memavl function returns the approximate size, in bytes, of the memory available for
dynamic memory allocation in the near heap (default data segment). The _memavl func
tion can be used with calloc, malloc, or realloc in tiny, small, and medium memory mod
els and with _ncalloc, _nmalloc or _nrealloc in any memory model.
The number returned by the _memavl function may not be the number of contiguous
bytes. Consequently, a call to malloc requesting allocation of the size returned by
_memavl may not succeed. Use the _memmax function to find the size of the largest
available contiguous block of memory.
Return Value The _memavl function returns the size in bytes as an unsigned integer.
See Also calloc functions, _freect, malloc functions, _memmax, realloc functions
#i n c l u d e <ma l l o c . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
(
l ong *l ongpt r ;
Output I
Memo ry a v a i � a bl e before _nma l l oc - 60906
Memo ry a v a i ll a b l e a ft e r _nma l l oc = 40390
487 memccpy, _fmemccpy
void *memccpy( void *dest, void *src, int c, unsigned int count );
void _far * _far _fmemccpy( void _far *dest, void _far *src, int c, unsigned int count );
Remalks The memccpy and _fmemccpy functions copy 0 or more bytes of src to dest, halting when
the character c has been copied or when count bytes have been copied, whichever comes
first.
The _fmemccpy function is a model-independent (large-model) form of the memccpy
function. It can be called from any point in any program.
Return Value If the character c is copied, memccpy or _fmemccpy returns a pointer (or far pointer) to
the byte in dest that immediately follows the character. If c is not copied, memccpy re
turns NULL.
Campatlblllty memccpy
_fmemccpy
Exampm ��
����--
t * MEMCCPY . C * /
#i n c l u d e <memo ry . h >
#i n c l u d e < s td i o . h >
#i n c l u d e < s t r i n g . h >
memccp , _fmemccpy 488
v o i d ma i n ( >
I
Output
Remarks The memchr and -fmemchr functions look for the first occurrence of c in the first count
bytes of buf. They stop when they find c or when they have checked the first count bytes.
The _fmemchr function is a model-independent (large-model) form of the memchr func
tion. It can be called from any point in any program.
Return Value If successful, me�chr or _fmemchr returns a pointer (or a far pointer) to the first location
of c in buf. Otherwise, they return NULL.
Compallblllly memchr
fmemchr
Exampm ����
I * M EM CH R . C * /
#i n c l u d e <memo ry . h >
#i n c l u d e < s t d i o . h >
msmchr _tmsmchr j I
490
i nt ch = ' r ' :
char str [ J " l a zy " ;
char stri ng [ ] = " T h e q u i c k b r own d o g j umps o v e r t h e l a zy fox " ;
cha r fmt l [ ] = • 1 2 3 4 5" ;
char fmt2 [ ] = " 1 2345678901 2 3 4 5 67890 1 2 3 4 5 6 7 890123456 78901 234567 890 " ;
v o i d ma i n ( )
I
c h a r *pd s t ;
!
i nt resu t ;
t
p r i n t f ( " St r i ng t o be s e a r c h ed : \ n \ t \ t % s \ n " , s t r i n g l ;
p r i n t f ( " \ t \t%s \ n \ t \ t % s \ n \ n " , fmt l , fmt2 l ;
�
pri ntf( Sea r c h c ha r : \ t %c \ n " , c h ) ;
pdest = emc h r C s t r i n g , c h , s i zeof ( s t r i n g l l ;
resul t = pdest - stri n g + 1 ;
i f ( pdes != NULL )
pri nt C " Re s u l t : \ t \ t%c found a t pos i t i on %d \ n \ n " , c h , r e s u l t l :
el se
pri nt C " Re s u l t : \ t \ t%c n o t found \ n " l ;
Output
Stri ng to b s e a r c h ed :
T h e q u i c k b r own d o g j umps o v e r t h e l a zy fox
1 2 3 4 5
1 2 34567890 1 2 3 4 5 6 7 89 0 1 2 34 5 6 7 8 9 0 1 2345678901 234567890
Sea r c h c h a r : r
Re s u l t : r found a t p os i t i on 1 2
491 memcmp, _fmemcmp
int memcmp( const void *buf1 , const void *buj2, size_t count ) ;
int _far _fmemcmp( const void _far *bufl , const void _far *buj2, size_t count );
Remarks The memcmp and _fmemcmp functions compare the first count bytes of bufl and buj2
and return a value indicating their relationship, as follows:
Value Meaning
Return Value The memcmp function returns an integer value, as described above.
Compatibility memcmp
_fmemcmp
492
r
* f i r s t a n d s e c ond . I f the f i r s t 1 9 byt e s of the s t r i n g s a r e
r
* e q u a l , t h p ro g r a m c on s i d e r s t h e s t r i n g s to be e q u a l .
*/
I
#i n c l ude < s t i n g . h >
#i n c l ude < s t i o . h >
v o i d ma i n ( > ,
I
�
I
�
c h a r s e c o d [ J = " 1 23456 7890 1 2 3456789 1 " ;
i nt resul ;
f
e l s e i f ( r e s u l t =� 0 )
p r i n t f � " F i r s t i s eq u a l t o s ec o n d . \ n " ) ;
el se i f ( resul t > 0 )
p r i n t f ( " Fi r s t i s g r e a t e r t h a n s ec o n d . \ n " ) ;
pri ntf ( n ompa r e ' % . 20 s ' t o ' % . 20 s ' : \ n " , f i r s t , s e c o n d ) ;
·
r e s u l t = emcmp ( f i r s t , s e c o n d , 20 ) ;
i f ( resul < 0 )
p r i n t f " F i r s t i s l e s s t h a n s e cond . \ n " ) ;
e l s e i f ( r e s u l t == 0 )
p r i n t f � " F i r s t i s e q u a l to s ec o n d . \ n " ) ;
el se i f ( resul t > 0 )
f
p r i n t f " F i r s t i s g r e a t e r t h a n s ec o n d . \ n " ) ;
I
I
I
493 memcmp, _fmemcmp
Output
Remarks The memcpy and _fmemcpy functions copy count bytes of src to dest. If the source and
destination overlap, these functions do not ensure that the original source bytes in the over
lapping region are copied before being overwritten. Use memmove to handle overlapping
regions.
The _fmemcpy function is a model-independent (large-model) form of the memcpy func
tion. It can be called from any point in any program.
There is a semantic difference between the function version of memcpy and its intrinsic
version. The function version supports huge pointers in compact-, large-, and huge-model
programs, but the intrinsic version does not.
Return Value I The memcpy and _fmemcpy functions return a pointer to dest.
I
Compatibilitfr memcpy
_fmemcpy
/ * M E M C P Y . C . I l l u s t r a t e o v e r l a pp i n g c o py : memmo v e h a n d l es i t
* c o r re c t l y ; memc py d o e s not .
*I
#i n c l u d e <memo ry . h >
#i n c l u d e < s t r i n g . h >
#i n c l ude < s t d i o . h >
I * Re s t o r e s t r i n g l t o o r i g i n a l c o n t e n t s * /
memc py ( s t r i n g l + 1 6 , s t r i ng2 + 40 , 3 ) ;
1
Output
F u n c t i on : I memc py w i t h o u t o v e r l a p
�
S o u rc e : fox
I
Des t i n a t i o : dog j umps over the l a zy fox
�
Re s u l t : The q u i c k b rown fox j umps over the l a zy fox
Length : 43 c h a r a c t e r s
Functi on : memmo v e wi t h o v e r l a p
Sou rce : q u i c k b rown fox j umps o v e r t h e l a zy dog
Desti nati o : b r own fox j umps o v e r t h e l a zy dog
Re s u l t : I T h e q u i c k q u i c k b r own fox j umps o v e r t h e l a zy dog
Length : ! 49 cha racters
Functi on : I memcpy w i t h o v e r l a p
Source : I q u i c k b r own dog j umps o v e r t h e l a zy fox
D e s t i n a t i op : b rown dog j umps over the l a zy fox
Re s u l t : Th e q u i c k q u i c k q u i c k q u i c k q u i c k q u i c k q u i c k q u i c
Leng t h : I 50 c h a ra c t e r s
491 memicmp, _fmemicmp
Remades The memicmp and _fmemicmp functions compare the first count characters of the two
buffers bufl and bufl byte-by-byte. The comparison is made without regard to the case of
letters in the two buffers; that is, uppercase and lowercase letters are considered equiv
alent. The memicmp and _fmemicmp functions return a value indicating the relationship
of the two buffers, as follows:
Value Meaning
Rstum Value The memicmp and _fmemicmp functions return an integer value, as described above.
Compal/blllly memicmp
_fmemicmp
l
* re g a rd t o the c a s e of the l et t e r s .
*I
#i n c l u d e m emo ry . h >
#i n c l u d e s t d i o . h>
#i n c l u d e s t r i ng . h >
v o i d ma i n (' )
(
i nt re u l t ;
c h a r f i r s t [ ] = " T h o s e W h o W i l l Not Lea rn f r om H i s t o ry " ;
c h a r s c o n d [ ] = " T H O S E WHO W I L L NOT LEARN F ROM t h e i r mi s t a k e s " ;
I* Not that the 29th cha racter i s ri ght here A */
1
p r i t f ( " Fi r s t i s e q u a l t o s e c o n d . \ n " ) ;
el s e i ( r e s u l t > 0 )
p r i t f ( " Fi r s t i s g r e a t e r t h a n s e c ond . \ n " ) ;
I
I
Output
C ompa re ' h o s e W h o W i l l Not Lea rn f rom ' t o ' TH O S E WHO W I L L NOT L EARN F ROM '
F i r s t i s q u a l t o s ec o n d .
499 _memmax
#inchide <malloc.h>
The _memmax function returns the size (in bytes) of the largest contiguous block of
memory that can be allocated from the near heap (i.e., the default data segment). Calling
_nmalloc with the value returned by the _memmax function will succeed as long as
_memmax returns a nonzero value.
R1tum Value The function returns the block size, if successful. Otherwise, it returns 0, indicating that
nothing more can be allocated from the near heap.
v o i d ma i n ( )
(
s i ze_t c o n t i g ;
c h a r *p ;
_mem ax 500
/ * D e t e mi n e c o n t i g u o u s memo ry s i ze * /
con t i g _memma x ( ) ;
p r i n t f ( " La r g e s t b l o c k of a v a i l a b l e memo ry i s %u by t e s l on g \ n " , con t i g ) ;
i f( con i g )
{
p = nma l l oc ( con t i g * s i z e o f ( i n t l l ;
if( == NULL )
p i n t f ( " E r r o r wi t h ma l l o c ( s h o u l d n e v e r o c c u r l \ n " l ;
el se
{
p i n t f ( " M a x i mum a l l oc a t i on s u c c e e d ed \ n " ) ;
f ee ( p ) ;
)
el se
pri n f( " N ea r h e a p i s a l r e a dy f u l l \ n " ) ;
Output
#include <String.h>
Remarks The memmove and _fmemmove functions copy count characters from the source (src) to
the destination (dest). If some regions of the source area and the destination overlap, the
memmove and _fmemmove functions ensure that the original source bytes in the overlap
ping region are copied before being overwritten.
The _fmemmove function is a model-independent (large-model) form of the memmove
function. It can be called from any point in any program.
Return Value The memmove and fmemmove functions return the value of dest.
Compatibllity memmove
_fmemmove
/ * M E M C P Y . C . I l l u s t ra t e o v e r l a p p i n g copy : memmove h a nd l e s i t
* c o r rectl y ; memc py d o e s not .
*I
#i n c l u d e <memo ry . h >
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
,
memm ve, _lmemmove 502
c h a r s t r i n � 2 [ 60 J
c h a r s t r i n � 1 [ 60 J " T h e q u i c k b rown d o g j umps o v e r t h e l a zy fox " ;
" T h e q u i c k b r own fox j umps o v e r t h e l a zy d og " ;
/* 1 2 3 4 5
* 1 2 345678901 23456 7890 1 2 34567890 1 2 34 5 6 7890 1 2 34 5 6 7 890
*I
v o i d ma i n (
{
l ;
I • s o u r c e : \ t \ t% s \ n " , s t r i n g l + 40
pri ntf C . " Func t i on : \ tmemcpy w i t h out o v e r l a p \ n "
pri ntf( l :
" De s t i n a t i on : \ t % s \ n " , s t r i n g l + 1 6 l ;
I
pri ntf(
memc py ( s t r i n g l + 1 6 , s t r i n g l + 40 , 3 l ;
I
pri ntf( " Re s u l t : \ t \ t % s \ n " , s t r i n g l l ;
pri ntf ( . " Leng t h : \ t\t%d c h a r a c t e r s \ n \ n " , s t rl en ( s t r i n g l l l ;
/* Re s t � r e
s t r i ngl to ori gi n a l contents */
memcpy ( s t r i n g l + 1 6 , s t r i n g 2 + 40 , 3 l :
1
p r i n t f ( , " D e s t i n a t i on : \ t % s \ n " , s t r i n g 2 + 1 0 l ;
memmo v e s t r i n g 2 + 1 0 , s t r i n g 2 + 4 , 40 l ;
p r i n t f ( 1 " Re s u l t : \ t \ t % s \ n " , s t r i n g 2 l ;
p r i n t f ( l " Le n g t h : \ t \ t%d c h a r a c t e r s \ n \ n " , s t r l en ( s t r i n g 2 l l ;
! " D e s t i n a t i on : \ U s \ n " , s t r i n g l + 1 0 l ;
pri ntf ( " So u r c e : \ t \ t% s \ n " , s t r i n g l + 4 ) ;
pri ntf(
memcpy ( s t r i n g l + 1 0 , s t r i n g l + 4 , 40 l ;
pri ntf( " Re s u l t : \ t \ t% s \ n " , s t r i n g l l ;
pri ntf ( " Leng t h : \ t \ t %d c h a r a c t e r s \ n \ n " , s t r l en ( s t r i n g l l l ;
Output
F u n c t i on : memcpy w i t h o u t o v e r l a p
Source : fox
D e s t i n a t i on' : dog j umps over t h e l a zy fox
Res u l t : T h e q u i c k b rown fox j umps over the l a zy fox
L e n gt h : 43 c h a r a c t e r s
F u n ct i on : memmo ve w i t h o v e r l a p
Source : q u i c k b rown fox j umps o v e r t h e l a zy dog
D e s t i n a t i on : ·
b rown fox j umps o v e r t h e l a zy dog
Res u l t : T h e q u i c k q u i c k b r own fox j umps o v e r t h e l a zy dog
Length : 49 c h a r a c t e r s
503 memmove, _lmemmove
F u n c t i on : memcpy w i t h o v e r l a p
S o u rc e : q u i c k b rown dog j umps o v e r t h e l a zy fox
Dest i nati on : b r own d o g j umps over the l a zy fox
Res u l t : The qui c k q u i c k q u i c k q u i ck qui c k qui c k qui c k qui c
Lengt h : 50 c h a r a c t e r s
msmsst _fmsmsst 504
c Character to set
Remal'lcs The memset and _fmemset functions set the first count bytes of dest to the character c.
There is a semantic difference between the function version of memset and its intrinsic
version. The function version supports huge pointers in compact-, large-, and huge-model
programs, but the intrinsic version does not.
Return Value The memset and _fmemset functions return a pointer to dest.
CampaUblllly memset
_fmemset
Exampm ___,____.;.__
. _________________________________________________________
�
I * M EM S ET . : T h i s p r o g r a m u s e s mems et t o s et t h e f i r s t f o u r by tes
* of buff r t o " * " .
*I
505 memset, _fmemset
v o i d ma i n ( )
(
c h a r buff e r [ ] = " T h i s i s a t e s t of t h e memset f u n c t i o n " ;
Output
B e f o r e : T h i s i s a test o f t h e mems et f u n ct i o n
Afte r : **** i s a t e s t of t h e mems et f u n ct i on
min 506
#include <Stdlib.h>
Remarks The min macro compares two values and returns the value of the smaller one. The argu
ments can be of any numeric data type, signed or unsigned. Both arguments and the return
value must be of the same data type.
Retum Value The macro returns the smaller of the two arguments.
Exampm __ -+------------------------------------------------------------
1 * M I NMAX . C * /
#i n c l ude < s d l i b . h >
#i n c l ude < s d i o . h>
�oi d >
'
J
ma i n (
i nt a = 0;
i nt b "' 1;
Output
I
T h e l a rg e r f 10 a n d 2 1 i s 2 1
T h e sma l l e r o f 1 0 a nd 2 1 i s 1 0
I
I
507 mkdir
Remarks The mkdir function creates a new directory with the specified dirname. Only one
directory can be created at a time, so only the last component of dirname can name a new
directory.
The mkdir function does not do any translation of path-name delimiters. Both DOS and
OS/2 accept either "\" or "/" internally as valid delimiters within path names.
Return Value The mkdir function returns the value 0 if the new directory was created. A return value of
-1 indicates an error, and errno is set to one qf the following values:
Value Meaning
Exampre ��
��
I * MAKED I R . C */
#i n c l u d e < d i rect . h >
#i n c l u d e < s t d l i b . h >
#i n c l u d e < s t d i o . h >
508
(
f
�
i n t res l t :
�
p r i n f ( " D i rect o ry ' \ \ t e s t tmp ' wa s s u c c e s s f u l l y c re a t e d \ n " > :
s y s t m C " d i r \ \ t e s t tmp " > :
i f ( md i r C " \ \ t e s t tmp • } 0 }
p i n t f ( " D i r e c t o ry ' \ \ t e s t tmp ' wa s s uc c e s s fu l l y remo ved \ n " > :
el se
p i n t f C " P robl em remo v i n g d i rect o ry ' \ \ t e s ttmp ' \ n " > :
el se
p r i n f C " P ro b l em c rea t i n g d i r e c t o ry ' \ \ t esttmp ' \ n " > :
Output
T h e v o l um l a bel i n d r i v e C i s O S 2 .
D i rect o ry of C : \ T E STTM P
Remalks The mktemp function creates a unique file name by modifying the given template argu
ment. The template argument has the form:
baseXX.XX.XX.
where base is the part of the new file name that you supply, and the X's are placeholders
for the part supplied by mktemp; mktemp preserves base and replaces the six trailing X's
with an alphanumeric character followed by a five-digit value. The five-digit value is a
unique number identifying the calling process. The alphanumeric character is 0 ('0') the
first time mktemp is called with a given template.
In subsequent calls from the same process with copies of the same template, mktemp
checks to see if previously returned names have been used to create files. If no file exists
for a given name, mktemp returns that name. If files exist for all previously returned
names, mktemp creates a new name by replacing the alphanumeric character in the name
with the next available lowercase letter. For example, if the first name returned is
t0 1 2 34 5 and this name is used to create a file, the next name returned will be
ta 1 2 3 4 5 . When creating new names, mktemp uses, in order, 'O' and then the lowercase
letters 'a' through ' z ' .
Note that the original template is modified by the first call to mktemp. If you then call the
mktemp function again with the same template (i.e., the original one), you will get an
error.
The mktemp function generates unique file names but does not create or open files.
Return Value The mktemp function returns a pointer to the modified template. The return value is
NULL if the template argument is badly formed or no more unique names can be created
from the given template.
/ * M KT EM P . T h e p ro g r a m u s e s mktemp to c re a t e fi ve un i q u e f i l e n a m e s .
* I t open e a c h f i l e n a m e to e n s u r e t h a t t h e n ext n a me i s u n i q u e .
*/
�
//i n c l u d e < o . h >
#i n c l u d e < t r i n g . h >
J
#i n c l u d e < td i o . h >
�
c h a r * t emp l a t e = " fn X X X X X X " ;
cha r *resu t ;
J\
c h a r names 5 J [ 9 J ;
�oi d ma i n O
i nt i :
F I LE *f : 9
for< i lil ; i < 5 ; i ++ )
[
s t rc y ( n ame s [ i J , t empl a t e >:
I * A t empt t o fi nd a u n i q u e fi l e n a me : * /
r e s u l t = mkt emp ( n a m es [ i J > :
l
i f ( e s u l t == N U L L )
�
p r i n t f ( " P r obl em c r e a t i n g t h e t empl a t e " ) ;
el se
( I
i f c l C fp = fopen ( r e s u l t , " w " ) ) ! = N U L L
p r i n t f ( " U n i q u e f i l e n a me i s % s \ n " , r e s u l t ) ;
el e
p r i n t f ( " C a n n ot open % s \ n " , r e s u l t > :
fc o s e ( fp > :
II
Output
#include <time.h>
R1matltB The mktime function converts the supplied time structure (possibly incomplete) pointed to
by timeptr into a fully defined structure with "normalized" values and then converts it to a
time_t calendar time value. The structure for the tm is described in the reference page for
asctime.
The converted time has the same encoding as the values returned by the time function.
The original values of the tm_wday and tm_yday components of the timeptr structure are
ignored. and the original values of the other components are not restricted to their normal
ranges.
If successful, mktime sets the values of tm_wday and tm_yday appropriately, and sets
the other components to represent the specified calendar time, but with their values forced
to the normal ranges; the final value of tm_mday is not set until tm_mon and tm_year are
determined.
DOS and OS/2 do not accommodate dates prior to 1 980. If timeptr references a date before
January l , 1980, mktime returns -1 .
Note that the gmtime and localtime functions use a single statically allocated buffer for
the conversion. If you supply this buffer to mktime, the previous contents will be
destroyed.
Retum Value The mktime function returns the specified calendar time encoded as a value of type
time_t If the calendar time cannot be represented, the function returns the value -1 cast as
type time_t.
v o i d ma i n ( )
(
s t ruct t w h e n :
t i me_t n w , res u l t ;
i nt d ys ;
t i me ( &n w > :
w h e n = * l oc a l t i me ( & n ow > :
p r i n t f ( C u r rent t i me i s % s \ n " , a s c t i me ( &w hen > >:
j
p r i n t f ( How ma ny d a y s to l oo k a h e a d : • > :
s c a n f ( • d " , &days > :
w h e n . tm_ d a y = w h e n . tm_md ay + d a y s ;
i f ( ( re s l t = m k t i me ( &when ) ) ! = C t i me_t ) - 1 )
p r i n t ( " I n %d d a y s t h e t i me w i l l be % s \ n " ,
d a y s , a s c t i me ( &w h e n > > ;
el se
p e r r o ( " mkt i me fa i l ed " > :
Output
How ma ny d a � s t o l oo k a h e a d : 23
I n 2 3 d a y s l h e t i me w i l l be W e d J u l 1 2 1 1 : 4 5 : 20 1 989
_
I
513 modi, modi/
#include <math.h>
x Floating-point value
intptr Pointer to stored integer portion
Remades The modf functions break down the floating-point value x into fractional and integer parts,
each of which has the same sign as x. The signed fractional portion of x is returned. The in
teger portion is stored as a floating-point value at intptr.
The modtl function uses the 80-bit, 1 0-byte coprocessor form of arguments and return
values. See the reference page on the long double functions for more details on this data
type.
Retum Value The modf and modtl functions return the signed fractional portion of x. There is no error
return.
Campatlblllty modf
modtl
• OS/2
'
0 ANSI • DOS 0 UNIX 0 XENIX
Exampm ����
I * MOD F . C * /
#i n c l ude <ma t h . h >
#i n c l ude < s t d i o . h >
modi, m di/ 514
v o i d ma i n ( )
(
doubl e x i y , n ;
x = J1
- 14 . 7 65432 1 ; / * D i v i d e x i n to i t s f r a c t i o n a l * /
l
y = modf x , &n ) ; / * a nd i n teger pa rts */
Output
F o r - 14 . 87 6 4 3 , t h e f r a c t i on i s - 0 . 87 6 54 3 a nd t h e i n t e g e r i s - 14
515 movedata
void movedata( unsigned int srcseg, unsigned int srcoff, unsigned int destseg,
unsigned int destoff, unsigned int count );
Remarks The movedata function copies count bytes from the source address specified by
srcseg:srcoff to the destination address specified by destseg:destoff.
The movedata function was intended to move far data in small-data-model programs. The
newer model-independent _fmemcpy and _fmemmove functions should be used instead
of the movedata function. In large-data-model programs, the memcpy and memmove
functions can also be used.
Segment values for the srcseg and destseg arguments can be obtained by using either the
segread function or the FP_SEG macro.
The movedata function does not handle all cases of overlapping moves correctly. These
occur when part of the destination is the same memory area as part of the source. The
memmove function correctly handles overlapping moves.
' ������������������������������-
Exampm �--
I * M O V E DATA C *I
#i n c l ude <m mo ry . h >
#i n c l u d e < s di o . h>
#i n c l ude < s ri ng . h>
#i n c l u d e < d s . h>
#i n c l ude <m l l oc . h >
'
c h a r _fa r * r e = " T h i s i s a t e s t . " ;
�oi d ma i n ( )
c h a r _fa � *dest ;
I
i f ( ( d e s i = _fma l l oc ( 80 ) ) ! = N U L L )
{
moved t a ( F P_S E G ( s rc ) , F P_O F F ( s rc ) ,
FP_S E G ( d e s t ) , FP_O F F ( d e s t ) , _f s t r l en ( s rc ) + 1 ) ;
pri nt " T h e s o u rc e d a t a a t % Fp i s ' % Fs ' \ n " , s rc , s rc > :
pri nt " T h e d e s t i n a t i on d a t a a t % Fp i s ' % Fs ' \ n " , d e s t , d e s t ) ;
_ff r e dest ) ;
I
�I[
Output
I
-I
I
I
517 _maveta Functions
#include <graph.h>
x, y View-coordinate point
wx, wy Window-coordinate point
Remarks The _moveto functions move the current position to the specified point. The _moveto
function uses the view-coordinate point (x, y) as the current position. The _moveto_w func
tion uses the window-coordinate point (wx, wy) as the current position. No d�wing takes
place.
Return Value The function returns the coordinates of the previous position. The _moveto function re
turns the coordinates in an xycoord structure. The xycoord structure, defined in
GRAPH.ff, contains the following elements:
Element Description
Element Description
518
l
�
/ti n c l u d e < g a p h . h >
�oi d
I
ma i n { )
s h o rt x , � . x i nc , y i nc , col o r = 1 ;
�
s t r u c t v i eocon f i g v ;
l
\
I * Fi n d a v a l i d g r a p h i c s mode . * /
i f { ! _s e t v i d eomod e { _MA X C O L O RM O D E
_g et v i d e o f o n f i g ( & v ) ;
exi t ( 1 ) ;
xi nc = v . r umx pi x e l s I 50 ;
yi nc = v . r umypi x e l s I 50 ;
�
f o r ( x = � . y = v . n umyp i xel s
I
- 1 ; x < v . n umxp i xel s ; x += xi n c , y -= y i n c
I
_s e t c o o r ( col o r++ % 1 6 >:
_mo v e t ( x , 0 ) ;
_l i n e t ( 0 , y ) ;
I
getc h ( ) ;
r
_s et v i d e o od e ( _D E FAU LTMODE ) ;
519 _msize Functions
Remarks The _msize family of functions returns the size, in bytes, of the memory block allocated
by a call to the appropriate version of the calloc, malloc, or realloc functions.
In large data models (compact-, large-, and huge-model programs), _msize maps to
_fmsize. In small data models (tiny-, small-, and medium-model programs), _msize maps
to nmsize.
The _nmsize function returns the size (in bytes) of the memory block allocated by a call to
_nmalloc, and the _fmsize function returns the size (in bytes) of the memory block allo
cated by a call to fmalloc or frealloc. The bmsize function returns the size of a block
allocated in segment seg by a call to _bmall0c, _bcalloc, or _brealloc.
The location of the memory block is indicated below:
0
Retum Value All four functions return the size (in bytes) as an unsigned integer.
ExamP• ---1----
I * R EA L LO C . T h i s p r o g r a m a l l o c a t e s a bl o c k o f memo ry f o r buffer
* a nd t h en uses _ms i z e t o d i s p l ay the s i z e of that bl o c k . Next , i t
* u s e s rea l oc to e x p a n d t h e amount of memo ry u s e d by buffer
* a nd t h en c a l l s _ms i z e a g a i n t o d i s p l a y the new amount of
* memo ry a l oc a t e d to b u ffe r .
*I .
#i n c l u d e < s d i o . h >
#i n c l ude <m l l oc . h>
#i n c l ude < s d l i b . h >
v o i d ma i n ( )
[
(
l ong * b u fe r ;
s i z e_t s z e ;
i f ( C b u f e r = ( l o n g * ) ma l l oc C 1000 * s i zeof ( l on g ) ) ) == N U L L )
�
exi t ( 1 ) ;
s i z e = _ s i z e ( buffer ) ;
p r i n t f ( S i z e of b l o c k a ft e r ma l l oc of 1000 l on g s : % u \ n " , s i z e ) ;
/ * Rea l l c a t e a n d s h ow new s i z e : * /
t
i f ( C buf e r = r e a l l oc C buffe r , s i z e + ( 1 000 * s i zeof C l ong ) ) ) ) == N U L L
exi t C 1 l > :
s i z e = -�s i z e ( buffer l ;
p r i n t f ( r s i z e o f b l o c k a ft e r rea l l oc of 1 000 mo re l on g s : % u \ n " , s i ze ) ; •
free ( b u f e r > :
Output
S i z e of b l o k a ft e r ma l l oc of 1 000 l on g s : 4000
S i z e of bl o k a ft e r rea l l oc o f 1000 more l on g s : 8000
521 onexit
#include <Stdlib.h>
Rematb The one:xit function is passed the address of a function lfune) to be called when the pro
gram terminates normally. Successive calls to one:xit create a register of functions that is
executed in LIFO (last-in-first-out) order. No more than 32 functions can be registered
with one:xit; one:xit returns the value NULL if the number of functions exceeds 32. The
functions passed to one:xit cannot take p arameters.
The one:xit function is not part of the ANSI definition, but is instead a Microsoft exten
sion. The ANSI-standard ate:xit function does the same thing as one:xit, and should be used
instead of one:xit when ANSI portability is desired.
All routines passed to onexit should have the _loadds attribute if used in multithread
dynamic-link libraries.
Return Value The one:xit function returns a pointer to the function if successful and returns NULL if
there is no space left to store the function pointer.
Exampm ______________________________________________________________�
I* ONEX IT . C *I
#i n c l u d e < s t d l i b . h >
#i n c l ude < s t d i o . h >
I * P rototypes * /
v o i d fn l ( v o i d ) , fn2 C v o i d ) , fn3 C v o i d ) , fn4 ( v o i d l ;
anexit 522
v o i d ma i n ( )
(
onex i t ( n l > :
o n ex i t C n 2 > :
o n ex i t C f n 3 > :
r
o n ex i t ( n4 > :
p r i n t f ( T h i s i s e x e c u t ed f i r s t . \ n " ) ;
voi d fnl C )
(
pri ntf ( next . \ n " ) ;
v o i d fn 2 C )
(
pri ntfC executed • ) ;
v o i d fn 3 C )
(
pri ntf ( is • );
v o i d fn4 ( )
(
pri ntf( Thi s • );
Output
T h i s i s exe uted f i r s t .
T h i s i s e x e uted n e x t .
523 open
#include <fcntl.h>
#include <Sys\types.h>
#include <Sys\stat.h>
#include <io.h> Required only for function declarations
Remarks The open function opens the file specified by filename and prepares the file for subsequent
reading or writing, as defined by oflag. The oflag argument is an integer expression
formed from one or more of the manifest constants defined in FCNTL.H (listed below).
When two or more manifest constants are used to form the oflag argument, the constants
are combined with the bitwise-OR operator ( I ). See Section 2.5, "File Handling," for a dis
cussion of binary and text modes.
The FCNTL.H file defines the following manifest constants:
Constant Meaning
O_APPEND Repositions the file pointer to the end of the file before every
write operation.
O_BINARY Opens file in binary (untranslated) mode.
O_CREAT Creates and opens a new file for writing; this has no effect if
the file specified by filename exists.
O_EXCL Returns an error value if the file specified by filename exists.
Only applies when used with o_CREAT.
O_RDONLY Opens file for reading only; if this flag is given, neither
O_RDWR nor O_WRONLY can be given.
O_RDWR Opens file for both reading and writing; if this flag is given,
neither 0_RDONLY nor 0_WRONLY can be given.
O_TEXT Opens file in text (translated) mode.
open 524
O_TRUNC Opens and truncates an existing file to zero length; the file
must have write permission. The contents of the file are de
stroyed. If this flag is given, you cannot specify O_RDONLY.
O_WRONLY Opens file for writing only; if this flag is given, neither
0_RDONLY nor O_RDWR can be given.
WARNING Use the O_ TRUNC flag with care, as it destroys the complete contents of an existing file.
Either O_RDONLY, O_RDWR, or O_WRONLY must be given to specify the access mode.
There is no default value for the access mode.
The pmode argument is required only when 0_CREAT is specified. If the file exists,
pmode is ignored. Otherwise, pmode specifies the file's permission settings, which are set
when the new file is closed for the first time. The pmode is an integer expression contain
ing one or both of the manifest constants S_IWRITE and S_IREAD, defined in
SYS\STAT.H. When both constants are given, they are joined with the bitwise-OR opera
tor ( I ) . The meaning of the pmode argument is as follows:
Value Meaning
If write permission is not given, the file is read-only. Under DOS and OS/2, all files are
readable; it is not possible to give write-only permission. Thus the modes S_IWRITE and
S_IREAD I S_IWRITE are equivalent.
The open function applies the current file-permission mask to pmode before setting the per
missions (see umask).
The filename argument used in the open function is affected by the DOS APPEND com
mand.
Note that under DOS versions 3.0 and later, a problem occurs when SHARE is installed
and a new file is opened with oflag set to O_CREAT I O_RDONLY or o_CREAT I
0 _WRONLY and pmode set to S_IREAD. Under these conditions, the operating system
prematurely closes the file during system calls made within open. This problem does not
occur under OS/2.
To work around the problem, open the file with the pmode argument set to S_IWRITE.
Then close the file and use chmod to change the access mode back to S_IREAD. Another
work-around is to open the file with pmode set to S_IREAD and oflag set to O_CREAT I
O_RDWR.
525 open
Return Value The open function returns a file handle for the opened file. A return value of -1 indicates
an error, and errno is set to one of the following values:
Value Meaning
EEXIST The 0_CREAT and 0_EXCL flags are specified, but the
named file already exists.
See Also access, chmod, close, creat, dup, dup2, fopen, sopen, umask
#i n c l u d e <fcntl . h>
#i n c l u d e < sy s \ ty p e s . h >
#i n c l u d e <sys \ s ta t . h>
#i n c l u d e < i o . h>
#i n c l u d e < s td i o . h >
v o i d ma i n ( )
{
i n t fh l , f h 2 ;
open 526
I
f h l = open ( " O P E N . C " , O_RDO N LY ) ;
i f ( f h l �= - 1 )
�
p e r r o l'1' ( " open f a i l ed o n i n p u t f i l e " ) ;
I
l se ·
�
p r i n t f ( " open s u c c eeded on i n put f i l e \ n " l ;
l cl ose fhl l ;
1
p r i n t 1i ( " open s u c c eeded on output f i l e \ n "
cl ose fh2 l ;
l ;
Output
I
open s u c c e e � ed on i n p u t f i l e
open s u c c e e � ed on o u t p u t f i l e
527 _outgtext
#include <graph.h>
Remarks The _outgtext function outputs on the screen the null-tenninated string that text points to.
The text is output using the current font at the current graphics position and in the current
color.
No fonnatting is provided, in contrast to the standard console 1/0 library routines such as
printf.
After it outputs the text, _outgtext updates the current graphics position.
The _outgtext function operates only in graphics video modes (e.g., _MRES4COLOR).
Because it is a graphics function, the color of text is set by the _setcolor function, not by
the _settextcolor function.
#i n c l u d e <coni o . h>
#i n c l ude <stdi o . h>
#i n c l u d e <stdl i b . h>
#i n c l u d e < s t r i n g . h>
#i n c l ude <graph . h>
_outgte 1'I 528
t
1fd ef i n e N F NTS 6
i
{
=
" C o u r i r " , " He l v e t i c a " , " T i mes Roma n " , " Mo d e rn " , " Sc r i pt " , " Roma n "
� n s i gned
);
l
c a r *opt i o n s [ N FONTS ] =
" c o u r i . r " , " h e l v " , " tms rmn " , " mod e r n " , " s c ri pt " , " roma n "
l: I
!
v o i d ma i n C j
u n s i g n � d c ha r l i s t [ 20 J ;
(
c h a r f � n d i r [_MAX_PAT H ] ;
i'
struct vi deoconfi g vc ;
s t r u c t _font i n fo f i ;
s ho r t o n t n um , x , y ;
I
/ * Rea � h e a d e r i n fo f rom a l l . FO N f i l e s i n c u r r e n t o r g i v e n d i r e c t o ry . * /
i f ( _r , g i s t e rfon t s ( " * . FO N " l <= 0 l
{ .
_o � ttext ( " En t e r f u l l p a t h w h e r e . FO N f i l e s a r e l o c a t ed : • l ;
g et s < fon d i r l ;
s t � c a t ( f o n d i r , " \ \ * . FO N " l ;
1 j
f _reg i s t e rf o n t s ( fondi r ) <= 0 l
l
I * Set h i g h e s t a v a i l a b l e g r a p h i c s mode a n d get c o n f i g u ra t i on . * /
i f ( ! _s e t v i deomod e ( _MAX R E S MO D E l l
ex i t ( 1 l ;
_g et v i � e o c o n f i g ( & v c l ;
i
_c i e a r s c reen ( _GC LEARSC R E E N l;
i f { _s etfont ( l i s t l >= 0 l
{ i
I
529 _outgtext
_mo v e t o ( x , y > :
i f ( v c . numc o l o r s > 2 )
_s etc o l o r < fontnum + 2 > :
I * Rot a te a n d d i s p l ay text . * /
_s e t g t ext v e c t o r ( 1 , 0 l :
_ou t g t ext ( f a c e [ fontnum] > :
_s etgtext v e c t o r ( 0 , 1 > :
_outgtext ( fa c e [ fontnum] > :
_s etgtext v e c t o r ( - 1 , 0 > :
_o utgtext C fa c e [ fontnum] > :
_s e t g t ext v e c t o r ( 0 , - 1 > :
_outgtext C f a c e [ fontnum] > :
el se
(
_o u t t ex t ( " E r ro r : C a n ' t s e t font : • l:
_o u t t ex t ( l i s t > :
}
getc h C > :
}
_u n reg i s te r fonts ( ) ;
_s e t v i d e omod e ( �D E FAU LTMODE > :
_autmet I
530
DBBt:riptlan
I Prints text of a specified length in graphics mode.
#include <graph.h>
R1matks The _outmem function outputs the string that text points to. The length argument specifies
the number of characters to output.
Unlike _outtext, the _outmem function prints all characters literally, including ASCII 10,
13, and 0 as the equivalent graphics characters. No formatting is provided. Text is printed
using the current text color, starting at the current text position.
To output text using special fonts, you must use the _outgtext function.
Exampm
�
----����-
1 * OUTM E M . i l l u s t r a tes :
* _o u t em
I
*I .
'
i
#i n c l u d e < t d i o . h >
f
#i n c l ud e < r a p h . h >
�oi d ma i n C
t
i n t i l en ;
char t p [ 10J ;
I
531 _outmem
_c l ea r s c reen ( GC L EARSC R E E N l ;
_
for ( i = 0 ; i < 2 5 6 ; i ++ )
{
_s ettextpos i t i on ( ( i % 24 ) + 1 , ( i I 24 ) * 7 ) ;
l en =s p r i ntf ( tmp , " %3d %c " , i , i l ;
_o utmem ( tmp , l en l ;
_s ettextpos i t i on ( 24 , 1 ) ;
532
I
Description Outputs a byte (outp) or a word (outpw) at a port.
Remarks The outp and outpw functions write a byte and a word, respectively, to the specified out
put port. The port argument can be any unsigned integer in the range 0 - 65,535; 17yte
can be any integer in the range 0 255; and dataword can be any value in the range
-
0 - 65,535.
Both outp and outpw are supported in OS/2. You must use a .DEF file to declare the
IOSEG segment the run-time library uses to perform input/output on the port. In addition,
the intrinsic (/Oi) versions of these functions do not work unless you put the code in a seg
ment that is marked with the IOPL keyword in the .DEF file.
You cannot do IOPL from a regular code segment, so the run-time library has declared a
separate code segment called _IOSEG. In order to use inp, inpw, outp, or outp in any of
the protected mode run-time libraries (?LIBCP, LLIBCDLL, LLIBCMT, or CDLLOBJS
based DLL), you must have a .DEF file with this line in it:
SEGMENTS _I O S E G C LA S S ' I O S E G_C O O E ' IOPL
Return Value The functions return the data output. There is no error return.
I* OUTP . C : T h i s p r o g r a m u s e s i n p a n d o u t p to ma k e s o u n d of v a r i a b l e t o n e
* and dur t i on .
*I
533 outp, outpw
#i nc l u d e < c o n i o . h>
#i n c l u d e < s t d i o . h >
#i n c l u d e < t i me . h >
voi d ma i n ( )
{
Beep (
Beep (
698 , 700 > :
5 2 3 , 500 > :
*I
v o i d Beep < un s i gned f r e q u ency , uns i gned d u ra t i on
i nt control :
(
i f ( d u r a t i on < 7 5 )
I * 7 5 i s a bout t h e s h o r t e s t rel i a bl e d u ra t i on o f a s ound . * /
d u ra t i on = 7 5 ;
* w r i t e ( by t e b y byt e ) t o t i me r .
I * D i v i d e i n put f r e q u ency by t i mer t i c k s p e r s econd a n d
*I
freq uency = C u n s i gned ) ( 1 1 9 3 1 8 0 L I f r e q u en cy ) ;
outp C 0x6 1 , c o n t r o l I 0 x 3 ) ;
I * T u r n o n t h e spea k e r ( w i t h b i t s 0 a nd 1 ) . * /
I * T u r n s pea k e r ba c k on i f n e c es s a ry . * /
i f ( frequency )
outp C 0x 6 1 , c o n t r o l > :
534
r, I
/ * P a u s e s o r a s p ec i f i ed n umbe r of mi c r o s e c o n d s . * /
v o i d S l eep,.( c l o c k_t wa i t )
(
c l o c k_ f goal ;
goa l =11wa i t + c l o c k ( ) ;
w h i l e ( g o a l > c l oc k ( ) )
535 _outtext
#include <graph.h>
Remarks The _outtext function outputs the null-tenninated string that text points to. No fonnatting
is provided, in contrast to the standard console 1/0 library routines such as printf. This
function will work in any screen mode.
#i n c l u d e < c o n i o . h >
#i n c l u d e < s t d i o . h >
# i n c l ude < g r a p h . h >
c h a r b u f f e r [ 80 ] ;
v o i d ma i n ( )
{
j
/ * S a v e o r i g i n a l foreg round , b a c k g round , a n d text po s i t i on . * /
�1
o l dfgd , _gettextcol o r ( ) ;
o l dbgd =: _g etb k c o l o r ( ) ;
o l dpos _g ettextpos i t i on ( ) ;
_c l ea rs reen ( _GClEARSC R E E N ) ;
/ * F i r s � t i me n o b l i n k , s e c o n d t i me bl i n k i n g . * /
f o r { b l i [ n k = 0 ; bl i n k < = 1 6 ; bl i n k += 1 6 )
{ .
l
I * L op t h ro u g h 8 b a c k g ro u n d c o l o r s . * /
(
fo r < b g d = 0 ; b g d < 8 ; bg d++ )
1
_s � t b k c o l o r < bgd ) ;
_s ettextpos i t i on ( ( s h o rt l bgd + ( ( b l i n k I 1 6 ) * 9 ) + 3 , 1 ) ;
�
-�ettext c o l o r ( 7 ) ;
1
s r i n t f ( buffe r , " Ba c k : %d Fore : " , bgd ) ;
- uttext ( buffer ) ;
/ � Loop t h r o u g h 1 6 foreground c o l o r s . * /
for ( fgd = 0 ; fgd < 1 6 ; fgd++ )
(
_s ettextc o l o r ( fgd + b l i n k ) ;
s p r i ntf ( buffe r , • %2d • , fgd + b l i n k ) ;
_o uttext ( buffer ) ;
getc h ( ) ;
I,
/ * Re s t o r e o r i g i n a l foreground , b a c k g r o u n d , and text p o s i t i on . */
_s e t b k c o� o r < ol dbgd ) ;
_s ettex t c o l o r ( o l dfgd ) ;
(
_c l ea r s c ! r een { _GC L EARSC R E E N ) ;
_s ettext p o s i t i on ( o l dpos . row , o l dpos . c o l ) ;
I
537 _pclose
Dsscr/plian Waits for a child command and closes the stream on the associated pipe.
Remarks The _pclose function waits for a child command and closes the stream on the associated
pipe. The argument stream is the return value from a previous call to _popen. The _pclose
function looks up the process ID of the child command started by the associated _popen
call, closes the stream, executes a cwait call on the child command, and returns the exit sta
tus of the child command. See _pipe for a general discussion of pipes in OS/2.
Rstum Value The _pclose function returns the exit status of the child command. The format of the return
value is the same as that for cwait, with the exception that the low-order and high-order
bytes are swapped. If an error occurs, -1 is returned.
A similar function (pclose) is available in the XENIX and UNIX operating environments.
Remades The perror function prints an error message to stderr. The string argument is printed first,
followed by a colon, then by the system error message for the last library call that pro
duced the error, and finally by a newline character. If string is a null pointer or a pointer to
a null string, perror prints only the system error message.
The actual error number is stored in the variable errno (defined in ERRNO.H). The sys
tem error messages are accessed through the variable sys_errlist, which is an array of mes
sages ordered by error number. The perror function prints the appropriate error message
by using the ermo value as an index to sys_errlist. The value of the variable sys_nerr is
defined as the maximum number of elements in the sys_errlist array.
To produce accurate results, perror should be called immediately after a library routine re
turns with an error. Otherwise, the errno value may be overwritten by subsequent c alls.
Under DOS and OS{l, some of the ermo values listed in ERRNO.H are not used. These
additional errno values are reserved for UNIX and XENIX use. See Section 3.3,
"_dosermo, ermo, sys_errlist, sys_nerr," for a list of ermo values used on DOS and
OS{l and the corresponding error messages. The perror function prints an empty string
for any ermo value not used under the operating system.
I
See Also clearerr, ferror, strerror
Examp� --�---------------------------------------------------
1 * P E RROR . c J T h i s p r o g r a m a t t empts t o open a f i l e n a med NOSUCH F . I LE .
l
* S i n c e t h 1 s f i l e p r o ba b l y d o e s n ' t exi s t , a n e r r o r mes s a g e i s d i s p l ayed .
* T h e s a me m e s s a g e i s c re a t ed u s i n g p e r ro r , s t re r ro r , a n d _s t re r ro r .
*I
I
539 perror
#i n c l u d e <fcntl . h>
#i n c l u d e < s y s \ types . h >
#i n c l u d e < s y s \ s t a t . h>
#i n c l u d e < i o . h>
#i ncl ude <stdl i b . h>
#i n c l u d e < s td i o . h >
#i n c l u d e <stri ng . h>
v o i d ma i n < >
[
i n t fh :
el se
[
p r i ntf C " open s u c c e e d ed on i n put f i l e \ n " > :
cl ose( fh > :
p e r r o r s a y s open fa i l ed : N o s u c h f i l e o r d i r e c t o ry
s t re r r o r s a y s open fa i l ed : N o s u c h f i l e o r d i r e c t o ry
_s t r e r ro r s a y s open fa i l ed : N o s u c h f i l e o r d i r e c t o ry
I
l
1
I
#include <pgchart.h>
short _far _pg_analyzechart( chartenv _far *env, char _far * _far *categories,
tloat _far *values, short n ) ;
short _far _pg_analyzechartms( chartenv _far *env, char _far * _far *categories,
tloat _far *values, short nseries, short n, short arraydim,
char _far * _far *serieslabels ) ;
Rematks The _pg_analyzechart routines an alyze a single or multiple series of data without actually
displaying the presentation-graphic image.
The _pg_analyzechart function fills the chart environment with default values for a
single-series bar, column, or line chart, depending on the type specified by the call to the
_pg_defaultchart function. The variables calculated by _pg_analyzechart reflect the data
given in the arguments categories and values. All arguments are the same as those used
with the _pg_chart function.
The _pg_analyzechartms function fills the chart environment with default values for a
multiseries bar, column, or line chart, depending on which type is specified in the
_pg_defaultchart function. The variables calculated by _pg_analyzechartms reflect the
data given in the arguments categories and values. All arguments are the same as those
used with the _pg_chartms function.
Boolean flags in the chart environment, such as AUTOSCALE and LEGEND, should be set
to TRUE before calling either _pg_analyzechart function. This will ensure that the func
tion will calculate all defaults.
For a discussion of the chart environment and related topics, see Section 2.6.2,
"Presentation-Graphics Functions."
541 _ pg ana/yzechart Functions
_
Return Value The _pg_analyzechart and _pg_analyzechartms functions return 0 if there were no er
rors. A nonzero value indicates a failure.
Exampm ������-
1* P GACHART . C : T h i s e x a mpl e i l l u s t ra t e s p r e s e n t a t i o n - g r a p h i c s
* a n a l yze f u n c t i o n s .
* T h e exampl e u s e s
* _p g_a n a l y z e c h a rtms
* The s ame p r i n c i pl e s a ppl y f o r
* _pg_a n a l yzepi e _pg_a n a l yze c h a rt
*
_pg_a n a l y z e s c a t t e r _pg_a n a l y z e s c a t t e rms
*I
#i n c l u d e <coni o . h>
#i n c l u d e <stri ng . h>
#i n c l u d e <stdl i b . h>
#i n c l u d e < g ra p h . h >
#i n c l u d e < p g c h a rt . h >
#d e f i n e FA L S E 0
f/d e f i n e T RU E 1
v o i d ma i n ( }
{
c h a rtenv e n v :
I * Fi nd a v a l i d g r a p h i c s mode . * /
i f ( ! _s e t v i deomod e ( _MAX RESMOOE )
ex i t ( 1 ) :
I * Defa u t mul t i s e r i e s ba r c h a rt * /
_pg_d efa l t c h a rt ( &en v , _PG�BA RCHART , _P G_P LA I N BARS ) ;
s t rc py ( n v . ma i n t i t l e . t i t l e , " L i tt l e Lea g u e Rec o r d s - Defa u l t " > :
_pg_c h a r ms < &en v , mont h s , v a l u e s , T EAMS , MONTH S , MONTHS , t e a ms > :
getch < > :
_c l ea rs reen C _GC L EA R S C R E E N ) ;
I * Ana l y e mul t i s e r i e s ba r c h a rt w i t h a ut o s c a l e . T h i s s e t s a l l
* d e f a u t s ca l e v a l u e s . We w a n t y a x i s v a l u e s t o be a utoma t i c .
I
_pg_d efa � l t c h a rt C & e n v , _PG_BA RCHART , _PG_P LA I N BARS ) ;
r
*I
#include <pgchart.h>
short _far _pg_analyzepie( chartenv _far *env, char _far * _far *categories,
float _far *values, short _far *explode, short n ) ;
Remades The _pg_analyzepie function analyzes a single series of data without actually displaying
the graphic image.
The _pg_analyzepie function fills the chart environment for a pie chart using the data con
tained in the array values. All arguments are the same as those used in the _pg_chartpie
function.
For a discussion of the chart environment and related topics, see Section 2.6.2,
"Presentation-Graphics Functions."
RBlum Value The _pg_analyzepie function returns 0 if there were no errors. A nonzero value indicates a
failure.
#include <pgchart.h>
Remalks The _pg_analyzescatter set of routines analyzes a single or multiple series of data without
actually displaying the graphic image.
The _pg_analyzescatter function fills the chart environment for a single-series scatter dia
gram. The variables calculated by this function reflect the data given in the arguments
xvalues and yvalues. All arguments are the same as those used in the _pg_chartscatter
function.
The _pg_analyzescatterms function fills the chart environment for a multiseries scatter di
agram. The variables calculated by _pg_analyzescatterms reflect the data given in the ar
guments xvalues and yvalues. All arguments are the same as those used in the function
·
_pg_chartscatterms.
Boolean flags in the chart environment, such as AUTOSCALE and LEGEND, should be
set to TRUE before calling _pg_analyzescatterms; this ensures that the function will cal
culate all defaults.
For a discussion of the chart environment and related topics, see Section 2.6.2,
"Presentation-Graphics Functions."
Return Value The _pg_analyzescatter and _pg_analyzescatterms functions return 0 if there were no er
rors. A nonzero v alue indicates a failure.
545 _pg_analyzescatter Functians
#include <pgchart.h>
short _far _pg_chart( chartenv _far *env, char _far * _far *categories,
float _far *values, short n );
short _far _pg_chartms( chartenv _far *env, char _far * _far *categories,
float _far *values, short nseries, short n, short arraydim,
char _far * _far *serieslabels );
Rematkl The _pg_chart function displays a single-series bar, column, or line chart, depending on
the type specified in the chart environment variable (env).
The _pg_chartms function displays a multiseries bar, column, or line chart, depending on
the type specified in· the chart environment. All the series must contain the same number of
data points, specified by the argument n.
The array values is a two-dimensional array containing all value data for every series to
be plotted on the chart. Each column of values represents a single series. The parameter
rowdim is the integer value used to dimension rows in the array declaration for values.
For example, the following code fragment declares the identifier v a 1 ues to be a two
dimensional floating-point array with 20 rows and 1 0 columns:
#d ef i n e A RRAY D I M 20
fl o a t v a l u e s [ A R RAY D I M ] [ 1 0 ] ;
s h o r t rowd i m = A R RAY D I M ;
Note that the number of columns in the values array cannot exceed 10, the maximum num
ber of data series on a single chart. Note also that row d i m must be greater than or equal
to the argument n, and the column dimension in the array declaration must be greater than
or equal to the argument nseries. If n and nseries are set to values less than the full dimen
sional size of the values array, only part of the data contained in values will be plotted.
547 _pg_chart Functions
The array series/abels holds the labels used in the chart legend to identify each series.
For a discussion of the chart environment and related topics, see Section 2.6.2,
"Presentation-Graphics Functions."
Retum Value The _pg_chart and _pg_chartms functions return 0 if there were no errors. A nonzero
value indicates a failure.
#i n c l u d e < c on i o . h >
#i n c l u d e <graph . h>
#i n c l u d e <stri ng . h>
#i n c l u d e <stdl i b . h>
#i n c l u d e < p g c h a rt . h >
#d ef i n e COUNT R I E S 5
fl o a t _fa r v a l u e [ COUNT R I E S ] = 42 . 5 , 14 . 3 , 35 . 2 , 21 . 3 , 32 . 6 };
c h a r _fa r * c a t e g o ry [ CO U NT R I E S J = "USSR" , " F r a n c e " , " U SA " , "UK" , " Ot h e r • J ;
s h o rt _fa r expl od e [ CO U N T R I E S ] = 0, 1, 0, l, 0 };
v o i d ma i n ( )
{
c h a rtenv e n v ; .
s ho r t mode _V R E S 1 6 C O LO R ;
=
I * Fi nd a v a l i d g r a p h i c s mode . * I
i f ( ! _s e t v i d e omod e C _MA X R E SMO D E )
exi t ( 1 ) ;
/ * S i n g l e - s e r i e s b a r c h a rt * /
_pg_d efa u l t c h a r t C &en v , _PG_BARCHART , _PG_P LA I N BARS ) ;
s t r c py C e n v . ma i n t i t l e . t i t l e , " W i dget P r o d u c t i on • ) ;
_pg_c h a rt C & e n v , c a t e g o ry , va l u e , COUNT R I E S > :
·
getch ( ) ;
_c l ea r s c reen C _GC LEARS C R E E N ) ;
548
l
I * S i n g e - s e r i e s c o l umn c h a rt * /
_pg_d ef u l t c h a rt ( &env , _PG_COLUMN CHART , _PG_P LA I N BARS ) ;
s t rc py ( e n v . ma i n t i t l e . t i t l e , " W i dget P roduct i on • > ;
_pg_c h a t C &env , c a t e g o ry , v a 1 u e , C O U NT R I E S > ;
getc h C > �
I* Pi e
_pg_d ef
s t rcpy (
l
_c l e a r s l reen ( _GC L EARSC R E E N ) ;
h a rt * /
u l t c h a rt ( &env , _PG_P I ECHART , _PG_P E R C E N T ) ;
e n v . ma i n t i t l e . t i t l e , " W i dget P roduct i on • ) ;
1
_pg_c h a t p i e C &en v , c a tegory , v a l u e , expl ode , C O U NT R I E S ) ;
getc h ( ) .
_s et v 1 d omode C _O E FAU LTMOD E > :
549 _ pg chartpie
_
#include <pgchart.h>
short _far _pg_chartpie( chartenv _far *env, char _far * _far *categories,
float _far *values, short _far *explode, short n );
Remarks The _pg_chartpie function displays a pie chart for the data contained in the array values.
Pie charts are formed from a single series of data-there is no multiseries version of pie
charts as there is for other chart types.
The array explode must be dimensioned so that its length is greater than or equal to the
argument n. All entries in explode are either 0 or 1 . If an entry is 1 . the corresponding pie
slice is displayed slightly removed from the rest of the pie.
For example if the explode array is initialized as
.
s h o r t expl ode [ 5 J = { 0 , 1 , 0 , 0 , 0 } ;
the pie slice corresponding to the second entry of the categories array will be displayed
"exploded.. from the other four slices.
For a discussion of the chart environment and related topics, see Section 2.6.2.
"Presentation-Graphics Functions.••
Return Value The _pg_chartpie function returns 0 if there were no errors. A nonzero value indicates a
failure.
#include <pgchart.h>
The _pg_chartscatter function displays a scatter diagram for a single series of data.
The _pg_chartscatterms function displays a scatter diagram for more than one series
of data.
The arguments xvalues and yvalues are two-dimensional arrays containing data for the
x axis and y axis, respectively. Columns for each array hold data for individual series; thus
the first columns of xvalues and yvalues contain plot data for the first series, the second
columns contain plot data for the second series, and so forth.
The n, rowdim, nseries, and serieslabels arguments fulfill the same purposes as those used
in the _pg_chartms function. See _pg_chartms for an explanation of these arguments.
For a discussion of the chart environment and related topics, see Section 2.6.2,
"Presentation-Graphics Functions."
R11tum Valu11 The _pg_chartscatter and _pg_chartscatterms functions return 0 if there were no errors.
A nonzero value indicates a failure.
551 _pg_chartscatter Functions
#include <pgchart.h>
short _far _pg_defaultchart( chartenv _far *env, short charttype, short chartstyle );
Remades The _pg_defaultchart function initializes all necessary variables in the chart environment
for the chart type by the variable charttype.
All title fields in the environment structure are blanked. Titles should be set in the proper
fields after calling _pg_defaultchart
The charttype variable can be set to one of the following manifest constants:
The chartstyle variable specifies the style of the chart with either the number " l " or the
number "2." Each of the five types of presentation-graphics charts can appear in two differ
ent chart styles, as described below:
In a pie chart, the pieces are "exploded" according to the explode array argument in the
_pg_chartpie function. In the "percent" format, percentages are printed next to each slice.
Bar and column charts have only one style when displaying a single series of data. The
on the same chart. The first style arranges the bars or coldmns for the different series side
styles "side by side" and "stacked" are applicable only when more than one series appear
by side, showing relative heights or lengths. The stacked style emphasizes relative sizes be
tween bars and columns.
Retum Value The _pg_defaultchart function returns 0 if there were no errors. A nonzero value indi
cates a failure.
01JSC1/pllan Gets the pixel bit map for the specified character.
#include <pgchart.h>
Rematks The _pg_getchardef function retrieves the current 8-by-8 pixel bit map for the character
having the ASCII number charnum. The bit map is stored in the chardefarray.
Retum Value The _pg_getchardef function returns 0 if there were no errors. A nonzero value indicates
an error.
#include <pgchart.h>
Remarks The _pg_getpalette function retrieves palette colors, line styles, fill patterns, and plot char
acters for all palettes. The pointer palette points to an array of palette structures that will
contain the desired palette values.
The palette used by the presentation-graphics routines is independent of the palette used by
the low-level graphics routines.
Return Value The function _pg_getpalette returns 0 if there were no errors, and it returns the value
_BADSCREENMODE if current palettes have not been initialized by a previous call to
_pg_setpalette.
I * PGGPAL . C : T h i s exampl e i l l u s t r a t e s p r e s e n t a t i o n - g ra p h i c s p a l e t t e s
* a n d t h e rout i n e s t h a t mod i fy t h em , i n c l u d i ng
* _pg_g e t p a l ette _pg_res etpa l ette _pg_s et s ty l e s e t
* _pg_g e t s ty l e s e t _pg_res e t s ty l e s et _pg_v l a b e l c h a rt
* _pg_h l a be l c h a rt _pg_s etpa l et t e
*I
#i n c l u d e < c on i o . h >
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d l i b . h >
#i n c l u d e < g r a p h . h >
#i n c l u d e < p g c h a rt . h>
556
{ { . 43 5 , . 522 , . 67 1 } .
{ . 533 , . 431 , . 40 1 } } ;
{ " Ma y " , " J u n e " , " J u l y " } ;
" Reds • } ;
/ * F i n d a v a l i d g r a p h i c s mod e . * I
i f ( ! _s e t i d eomode ( _MA X RE SMOO E )
ex i t ( 1 ) ;
_pg_i n i t c h a rt C ) ; / * I n i t i a l i z e c h a rt s y s t em . */
* c h a ra s e r s . N o t e t h a t t h e l i n e s ty l e s a re s e t i n t h e p a l e t t e , n o t
/ * Mod i fy p a l e t t e f o r d a ta l i n es , c o l o r s , f i l l p a t t e r n s , a n d
* i n t h e s ty l e s e t , s o t h a t on l y d a t a c o n n e c t o r s w i l l be a ff e c t ed .
*I
_pg_g e t p a l et t e ( p a l > :
!
I * Get d e fa u l t pa l et t e . */
pa l [ l J . p l ot c h a r = 1 6 ; I * S e t t o ASC I I 1 6 a nd 1 7 . */
pa l [ 2 J . p l ot c h a r = 1 7 ;
�
memcpy ( p l [ l ] . f i l l , f i l l l , 8 ) ; I * Copy f i l l ma s k s t o pa l ette . */
memcpy ( p 1 [ 2 ] . f i l l , f i l l 2 , 8 ) ;
pa l [ l ] . c � o r = 3 ; I * C h a n g e p a l ette c o l o r s . */
pa l [ 2 J . c o o r = 4 ;
p a l [ l ] . s t l e = 0xfcfc ; I * C h a n g e pa l ette l i n e s ty l es . */
pa l [ 2 ] . s t l e = 0x0303 ;
_p g_s e t p a l et t e ( pa l ) ; I * Put mod i f i ed pa l et t e . */
551 _pg_getpalette
I * M u l t i s e r i e s ba r c h a rt * /
s t rc py ( env . ma i n t i t l e . t i t l e , " L i t t l e Lea g u e Rec o r d s - C u s t omi zed " ) ;
_pg_c h a rtms ( &env , mon t h s , ( f l o a t _fa r * ) v a l ue s ,
T EAMS , MONTH S , MONTH S , teams ) ;
getch ( ) ;
_c l ea r s c reen ( _GC L EA RS C R E E N ) ;
I * M u l t i s e r i e s l i n e c h a rt * /
_p g_defa u l t c h a r t ( &env , _PG_L I N E CHART , _PG_P O I NTAN D L I N E ) ;
s t rc py ( e n v . ma i n t i t l e . t i t l e , " L i t t l e Lea g ue Records - C u s t omi zed " ) ;
_pg_c h a rtms ( &env , mon t h s , ( f l o a t _fa r * ) v a l ues ,
T EAMS , MONTH S , MONTH S , teams ) ;
I * P r i nt l a b e l s . * /
_pg_h l a b e l c h a rt ( &env , ( s h o rt ) ( en v . c h a rtw i ndow . x 2 * . 75 ) ,
( s h o rt ) ( en v . c h a rtwi ndow . y 2 * . 10 ) ,
12 , " U p a nd up ! " ) ;
_pg_v l a be l c h a rt ( & e n v , ( s h o rt ) ( en v . c h a rtwi ndow . x 2 * . 75 ) ,
( s h o rt ) ( en v . c h a rtwi ndow . y 2 * . 45 ) ,
1 3 , " S l i d i n g down ! " ) ;
getch ( ) ;
_c l ea rs c reen ( _GC LEARSC R E E N l ;
/ * M u l t i s e r i e s ba r c h a rt * /
_pg_defa u l t c h a rt ( &en v , _PG_BARCHART , _PG_P LA I N BARS l ;
s t rc py ( e n v . ma i n t i t l e . t i t l e , " L i ttl e Lea g u e Rec o r d s - Defa u l t " l ;
_pg_c h a rtms ( &env , mon t h s , ( fl o a t _fa r * ) v a l ues ,
T EAMS , MONTH S , MONTH S , teams ) ;
getch ( l ;
_c l ea r s c reen ( _GC LEARSC R E E N ) ;
I * M u l t i s e r i e s l i n e c h a rt * /
_pg_d efa u l t c h a r t ( &en v , _PG_L I N ECHART , _PG_PO I NTAN D L I N E ) ;
s t rcpy ( e n v . ma i n t i t l e . t i t l e , " L i t t l e L e a g u e Records - Defa u l t " ) ;
_pg_c h a rtms ( &env , mon t h s , ( f l o a t _fa r * ) v a l u e s ,
T EAMS , MONTH S , MONTH S , teams ) ;
getch < l ;
Description
I Gets the current styleset.
I llinclude qigcbart.b>
Remarks The __pg__getstyleset function retrieves the contents of the current styleset.
#include <pgchart.h>
short _far _pg_hlabelchart( chartenv _far *env, short x, short y, short color,
char _far *label );
Rematks The _pg_hlabelchart function writes text horizontally on the screen. The arguments x and
y are pixel coordinates for the beginning location of text relative to the upper-left comer of
the chart window.
Retum Value The _pg_hlabelchart functions return 0 if there were no errors. A nonzero value indicates
a failure.
#include <pgchart.h>
R1marlcs The _pg_initchart function initializes the presentation-graphics package. I t initializes the
color and style pools, resets the chartline styleset, builds default palette modes, and reads
the presentation-graphics font definition from the disk. This function is required in all pro
grams that use presentation graphics. The _pg_initchart function must be called before
any of the other functions in the presentation-graphics library.
The _pg_initchart function assumes a valid graphics mode has been established. There
fore, it must be called only after a successful call to the library function _setvideomode.
I
R1lurn Va/UB The _pg_initchart functions return 0 if there were no errors. A nonzero value indicates a
failure.
!
CompallblllfYi 0 ANSI • DOS 0 OS/2 D UNIX D XENIX
Description Resets palette colors, line styles, and patterns to default values.
#include <pgchart.h>
Remarks The _pg_resetpalette function sets the palette colors, line styles, fill patterns, and plot
· characters for the palette to the default for the current screen mode.
The palette used by the presentation-graphics routines is independent of the palette used by
the low-level graphics routines.
Return Value The _pg_resetpalette function returns 0 if there were no errors. If the screen mode is not
valid, the value _BADSCREENMODE is returned.
#include <pgchart.h>
Remarks The _pg_resetstyleset function reinitializes the styleset to the default values for the
current screen mode.
I
See Also i _pg_defaultchart, _pg__getstyleset, _pg_initchart, _pg_setstyleset
· Description Sets the pixel bit map for the specified character.
#include <pgchart.h>
Remarks The _pg_setchardef function sets the 8-by-8 pixel bit map for the character with the
ASCil number charnum. The bit map is stored in the chardef array.
Return Value The _pg_setchardef function returns 0 if there was no error. A nonzero value indicates an
error.
#include <pgchart.h>
Remarks The _pg_setpalette function sets palette colors, line styles, fill patterns, and plot charac
ters for all palettes. The pointer palette points to an array of palette structures that contain
the desired palette values.
The palette used by the presentation-graphics routines is independent of the palette used by
the low-level graphics routines.
Return Value The _pg_setpalette function returns 0 if there were no errors. If the new palettes are not
valid, the value _BADSCREENMODE is returned.
#include <pgchart.h>
#include <pgchart.h>
short _far _pg_vlabelchart( chartenv _far •env, short x, short y, short color,
char _far *label ) ;
Remades The _pg_vlabelchart function writes text vertically on the screen. The arguments x and y
are pixel coordinates for the beginning location of text relative to the upper-left corner of
Rslaml'allfJ
the chart window.
The _pg_vlabelchart function returns 0 if there were no errors. A nonzero value indicates
�
a failure.
#include <graph.h>
short _far _pie( short control, short xi, short yi, short x2, short y2, short .x3, short y3,
short x4, short "y4 );
short _far _pie_w( short control, double xi, double yi, double x2, double y2,
double .x3, double y3, double x4, double "y4 );
short _far _pie_wxy( short control, struct _wxycoord _far *pwxyi,
struct _wxycoord _far *pwxy2, struct _wxycoord _far *pwxy3,
struct _wxycoord _far*pwxy4 );
Remades The _pie functions draw a pie-shaped wedge by drawing an elliptical arc whose center and
two endpoints are joined by lines.
The _pie function uses the view coordinate system. The center of the arc is the center of
the bounding rectangle specified by the view coordinate points (xi, yi ) and (x2, y2). The
arc starts where it intersects the vector defined by (.x3, y3) and ends where it intersects the
vector (x4, "y4).
The _pie_wxy and _pie_w functions use the window coordinate system. The center of the
arc is the center of the bounding rectangle specified by the window coordinate pairs pwxyi
and pwxy2 for _pie_wxy, and by the points (xi , yi ) and (x2, y2) for _pie_w. The arc starts
where it intersects the vector defined by pwxy3 or (.x3, y3) and ends where it intersects the
vector defined by pwxy4 or (x4, "y4).
_pie Fu,ctions I
568
The _wxycoord structure is defined in GRAPH.H and contains the following elements:
Element Description
The wedge is drawn using the current color moving in a counterclockwise direction. The
control parameter can be one of the following manifest constants:
Constant Action
_GFILLINTERIOR Fills the figure using the current color and fill mask
_GB ORDER Does not fill the figure
Return Value
I These functions return a nonzero value if successful; otherwise, they return 0.
See Also I _arc functions, _ellipse functions, _floodfill, _getcolor, _lineto functions,
_rectangle functions, _setcolor, _setfdlmask
Exampm �-+--����-
v o i d ma i n ( )
(
I * F i nd a v a l i d g r a p h i c s mode . * /
i f ( ! _s et v i d eomod e C _MAX RESMODE )
exi t ( 1 ) ;
R1matb A pipe is an artificial file-like 1/0 channel that a program can create and use to pass infor
mation to other programs. A pipe is similar to a file in that it has a file pointer or a file de
scriptor, or both, and can be read from or written to using the input and output functions of
the standard library. Unlike a file, a pipe does not represent a specific file or device. In
stead, a pipe represents temporary storage in memory that is independent of the program's
own memory and is controlled entirely by the operating system.
Pipes may be used to pass information between programs. For example, the command pro
cessor in OS/2 creates a pipe when executing a command such as
P ROGRAM l I P ROGRAM2
The standard output handle of PROGRAM! is attached to the pipe's write handle. The
standard input handle of PROGRAM2 is attached to the pipe's read handle. This elimi
nates the need for creating temporary files to pass information to other programs.
The _pipe function creates a pipe. This function is similar to open but opens the pipe for
both reading and writing, returning two file handles instead of one. The program can either
use both sides of the pipe or close the one it does not need. This function typically opens a
pipe in preparation for linking it to a child process.
The _pipe function opens a pipe and returns two handles to the pipe in the phandles argu
· ment. The element phandles[O) contains the read handle, and the element phandles[l ] con
tains the write handle. Pipe file handles are used in the same way as other file handles.
(The low-level input and output functions read and write can read from and write to a
pipe.)
The psize argument specifies the amount of memory, in bytes, to reserve for the pipe.
571 _pipe
The textmode argument specifies the translation mode for the pipe. The manifest constant
O_TEXT specifies a text translation, and the constant O_BINARY specifies binary transla
tion. (See fopen for a description of text and binary modes.) If the textmode argument is 0,
the _pipe function uses the default translation mode specified by the default-mode variable
_fmode.
In multithread programs, no locking is performed. The handles returned are newly opened
and should not be referenced by any thread until after the _pipe call is complete.
Under OS/2, a pipe is destroyed when all its handles have been closed. (If all read handles
on the pipe have been closed, writing to the pipe will cause an error.) All read and write
operations on the pipe wait until there is enough data or enough buffer space to complete
the 1/0 request.
Return Value The _pipe function returns 0 if successful. A return value of -1 indicates an error, and
errno is set to one of the following values:
Value Meaning
A similar function (pipe} is available in the XENIX and UNIX operating environments.
I * P I P E . C : T h i s p r o g r a m u s e s _p i pe to pa s s s t reams of text to
* c h i l d p r o c es s e s .
*I
#i n c l u d e <stdl i b . h>
#i n c l u d e <stdi o . h>
/Ii n c l u d e <i o . h>
#i n c l u d e <fcntl . h>
#i n c l u d e <proces s . h> I * _p i pe */
#i n c l u d e <ma t h . h >
_pipe 572
v o i d ma i n ( i n t a rg c , c h a r *a rgv [ J
(
i nt h p i pe [ 2 J :
cha r h s t r [ 20 J :
i nt t e rms t a t , p i d , p robl em , c :
I * I f n o a rgumen t s , t h i s i s t h e pa rent . * /
i f ( a rg c 1 )
(
==
I * Open a s e t s o f p i pes . * /
i f ( _p i pe ( h p i pe , 2 5 6 , O_B I NARY ) == - 1 )
exi t ( 1 > :
I * C o n v e r t p i pe read h a n d l e to s t r i n g a n d pa s s a s a rg ument to
* s p a wned c h i l d . P ro g r a m spawns i t s e l f C a r g v [ 0 ] ) .
*I
i t oa C h p i p e [ READJ , h s t r , 1 0 > :
i f ( s p a w n l C P_NOWAI T , a rg v [ 0 ] , a r g v [ 0 ] , h s t r , N U L L == - 1 )
p r i ntf C " Spawn fa i l ed " > :
I * P u t p r o b l em i n w r i t e p i pe . S i n c e c h i l d i s r u n n i ng s i mu l t a neou s l y ,
* f i r s t s o l u t i o n s may b e done before l a s t p r o b l em i s g i ven .
*I
fo r e p robl em = 1 000 ; p r o b l em < = N U M P RO B L E M * 1000 ; p robl em += 1 000
(
p r i n t f C " Son , w h a t i s t h e s q u a re root of %d ? \ n " , p r o b l em > :
. w r i t e ( h p i p e [ W R I T E J , ( c h a r * ) &p r o b l em , s i zeo f C i n t ) l :
I * Wa i t u n t i l c h i l d i s d o n e proce s s i n g . * /
wa i t ( &te rms t a t > :
i f ( t e rms t a t & 0xff l
p r i n t f C " C h i l d fa i l ed \ n " > :
c l o s e ( h p i p e [ READ J > :
cl ose( hpi pe[WRITEJ > :
573 _pipe
I * I f t h e r e i s a n a rg ument , t h i s m u s t be t h e c h i l d . * /
el se
{
I * C o n v e rt pa s s ed s t r i ng h a n d l e t o i nt e g e r h a n d l e . * /
h p i p e [ READJ = a t o i C a rgv [ l ] ) ;
Output
#include <graph.h>
short _far _polygon( short control, struct xycoord _far *points, short numpoints );
short _far _polygon_w( short control, double _far *points, short numpoints );
short _far _polygon_wxy( short control, struct _wxycoord _far *points,
short numpoints ) ;
Remarks The _polygon functions draw polygons. The border of the polygon is drawn in the current
color and line style. The _polygon routine uses the view coordinate system (expressed in
xycoord structures), and the _polygon_wxy and _polygon_w routines use real-valued win
dow coordinates (expressed in _wxycoord structures and in pairs of double-precision float
ing-point values, respectively).
Constant Action
The _setwritemode, _setlinestyle, and _setfillmask functions all affect the output from
the_polygon functions.
Return Value The _polygon functions return a nonzero value if the arc is successfully drawn; otherwise,
they return 0.
S11 A/Ba _ellipse functions, _floodfill, _lineto functions, _pie functions, _rectangle functions,
_setcolor, _setfillmask, _setlinestyle, _setwritemode
#i n c l u d e < c o n i o . h>
#i n c l u d e < s t d l i b . h>
#i n c l u d e <graph . h>
#i n c l u d e <ma t h . h >
#i n c l u d e <stdl i b . h>
#d ef i n e P I 3 . 1 4 1 5
v o i d ma i n ( )
(
s h o rt s i d e , rad i u s = 90 , x = 0 , y = 0 ;
doubl e radi a n s ;
s t ruct xyc o o r d pol y s i d e [ 5 J ;
s t ruct v i d e o c on f i g v c ;
I * F i n d a v a l i d g r a p h i c s mode . * /
i f ( ! _s et v i d eomode ( _MA X R ESMODE
exi t ( 1 ) ;
_ge t v i de o c o n f i g ( & v c ) ;
_s e t v i ew o r g ( v c . n umx p i x e l s I 2 , v c . n umyp i x e l s I 2 ) ;
getc h ( ) ;
_s e t v i d e omod e ( _O E FAU LTMOD E ) ;
_papen 576
Remarks The _popen function creates a pipe and asynchronously executes a child copy of the com
mand processor with the specified command string command. See _pipe for a general dis
cussion of pipes in OS/2. The character string mode specifies the type of access requested,
as follows:
Description
" r" The calling process can read the child command's standard
output via the returned stream.
" w" The calling process can write to the child command's standard
input via the returned stream.
" b" Open in binary mode.
" t" Open in text mode.
See Section 2. 7, "Input and Output," for a discussion of text and binary modes.
Retum Value The _popen function returns a stream associated with one end of the created pipe. The
other end of the pipe is associated with the child command's standard input or standard out
put. If an error occurs, NULL is returned.
A similar function (popen) is available in the XENIX and UNIX operating environments.
#i n c l u d e < s t d i o . h >
#i n c l u d e < s t d l i b . h >
v o i d ma i n ( )
(
cha r buffer [ 128J ;
FI LE * c h kd s k ;
exi t ( 1 ) ;
I * C l o s e p i p e a nd p r i nt retu rn v a l u e of C H K DS K . * /
p r i n t f ( " \ n C h i l d r e t u r n e d %d \ n " , _pc l o s e C c h kd s k ) ) ;
Output
3 Fi l e ( s ) 1 2683264 bytes f r e e
D i r e c t o ry o f C : \ L I B R E F
T h e v o l ume l a b e l i n d r i v e C i s 052 .
P O L Y GO N C 921 6 - 14-89 6 : 51p
POPEN C 845 6 - 1 9 - 89 2 : 48p
POW C 190 6 - 1 3 - 89 6 : 07 p
C h i l d r e t u rned 0
paw Functions 578
#include <math.h>
x Number to be raised
y Power of x
Remalb The pow and powl functions compute x raised to the power of y.
The powl function is the 80-bit counterpart, and it uses an 80-bit, 1 0-byte coprocessor
fonn of arguments and return values. See the reference page on the long double functions
for more details on this data type.
Retum Value The pow and powl functions return the value of � . If x is not 0.0 and y is 0.0, pow and
powl return the value 1 . If x is 0.0 and y is negative, pow and powl set errno to EDOM
and return 0.0. If both x and y are 0.0, or if x is negative and y is not an integer, the func
tion prints a DOMAIN error message to stderr, sets ermo to EDOM, and returns 0.0. If an
overflow results, the function sets ermo to ERANGE and returns ±HUGE VAL. No mes-
-
The pow function does not recognize integral floating-point values greater than 264, such
as 1 . 0 E 1 00 .
Compatibility pow
powl
I * P OW . C * /
#i n c l u d e <ma t h . h >
#i n c l ude < s t d i o . h>
579 pow Functions
v o i d ma i n ( )
{
doubl e x = 2.0, y = 3.0, z;
z - pow ( x , y ) ;
p r i n t f ( " % . l f t o t h e p owe r of % . l f i s % . l f \ n " , x, y, z ) ;
Output
2 . 0 t o t h e powe r of 3 . 0 i s 8 . 0
printf 580
#include <Stdio.h>
Remarks The printf function formats and prints a series of characters and values to the standard out
put stream, stdout. The format argument consists of ordinary characters, escape sequen
ces, and (if arguments follow format) format specifications. The ordinary characters and
escape sequences are copied to stdout in order of their appearance. For example, the line
L i n e one
L i ne two
If arguments follow the format string, the format string must contain specifications that de
termine the output format for the arguments.
Format specifications always begin with a percent sign (%) and are read left to right.
When the first format specification (if any) is encountered, the value of the first argument
afterformat is converted and output accordingly. The second format specification causes
the second argument to be converted and output, and so on. If there are more arguments
than there are format specifications, the extra arguments are ignored. The results are unde
fined if there are not enough arguments for all the format specifications.
A format specification, which consists of optional and required fields, has the following
form:
% [f7ags]) [width]) [.precision]) [ { F I N I h I 1 1 L }])type
Format Specification Fields
Each field of the format specification is a single character or a number signifying a particu
lar format option. The simplest format specification contains only the percent sign and a
type character (for example, % s ) . The optional fields, which appear before the type charac
ter, control other aspects of the formatting. The fields in a printf format specification are
described in the following list:
581 print!
Field Description
Prefix Use
If a percent sign is followed by a character that has no meaning as a format field, the char
acter is copied to stdout. For example, to print a percent-sign character, use %%.
prinff 582
The type character is the only required fonnat field for the printf function; it appears after
any optional fonnat fields. The type character detennines whether the associated argument
is interpreted as a character, a string, or a number. (See Table R.2.)
Rag Directives
The first optional field of the format specification is flag. A flag directive is a character
that justifies output and prints signs, blanks, decimal points, and octal and hexadecimal pre
fixes. More than one flag directive may appear in a format specification. (See Table R.3.)
+ Prefix the output value with a sign Sign appears only for negative
(+ or -) if the output value is of a signed values (-).
signed type.
W hen used with the g or G format, the Decimal point appears only if
# flag forces the output value to contain digits follow it. Trailing zeros are
a decimal point in all cases and pre truncated.
vents the truncation of trailing zeros.
Width Specification
The second optional field of the format specification is the width specification. The width
argument is a non-negative decimal integer controlling the minimum number of characters
printed. If the number of characters in the output value is less than the specified width,
blanks are added to the left or the right of the values-depending on whether the
- flag (for left justification) is specified-until the minimum width is reached. If width is
prefixed with O,' zeros are added until the minimum width is reached (not useful for left
justified numbers).
The width specification never causes a value to be truncated. If the number of characters in
the output value is greater than the specified width, or width is not given, all characters of
the value are printed (subject to the precision specification).
The width specification may be an asterisk (*), in which case an int argument from the
argument list supplies the value. The width argument must precede the value being for
matted in the argument list. A nonexistent or small field width does not cause a truncation
of a field; if the result of a conversion is wider than the field width, the field expands to
contain the conversion result.
Precision Specification
The third optional field of the format specification is the precision specification. It speci
fies a non-negative decimal integer, preceded by a period (.), which specifies the number
of characters to be printed, the number of decimal places, or the number of significant
digits. (See Table R.4.) Unlike the width specification, the precision specification can
cause truncation of the output value, or rounding in the case of a floating-point value. If
precision is specified as zero and the value to be converted is zero, the result is no charac
ters output, as shown below:
The precision specification may be an asterisk (•), i n which case an int argument from the
argument list supplies the value. The precision argument must precede the value being for
matted in the argument list.
The interpretation of the precision value and the default when precision is omitted depend
on the type, as shown in Table R.4.
585 printf
Value Output
+ infinity 1.#1.NFrandom-digits
- infinity -l.#INFrandom-digits
Indefinite digit.#INDrandom-digits
NAN digit.#NANrandom-digits
printf 586
For printf, the format specification fields F and N refer to the "distance" to the object
being read (near or far), and h and I refer to the "size" of the object being read ( 1 6-bit
short or 32-bit long). The following list clarifies this use of F, N, h, I, and L:
The specifications " %hs" and " %Is" are meaningless to printf. The specifications
" %Np" and " %Fp" are aliases for " %hp" and " %Ip" for the sake of compatibility with
Microsoft C version 4.0.
Relum Value The printf function returns the number of characters printed, or a negative value in the
case of an error.
I * P R I NT F . C i l l u s t ra t e s output f o rma t t i ng w i t h p r i n t f . * /
#i n c l u d e < s t d i o . h>
v o i d ma i n ( )
(
char c h = ' h ' , * s t r i n g = " c omput e r " ;
i nt c o u n t = - 9 2 34 ;
d o u b l e fp = 2 5 1 . 7 366 ;
I * Di spl ay i ntegers . */
p r i n t f C " I nt e g e r fo rma t s : \ n "
" \ t D ec i ma l : % d J u st i f i ed : % . 6d U n s i gned : % u \ n " ,
c o u n t , c o u n t , count , c o u n t ) ;
I * D i s p l a y i n d i fferent r a d i x e s . * /
p r i n t f ( " D i g i t s 1 0 equa l : \ n \ tHex : % i Oct a l : % i Dec i ma l : % i \ n " ,
0 x l 0 , 0 1 0 , 10 ) ;
I * D i s p l ay s t r i n g s . * /
p r i n t f ( " St r i n g s i n f i e l d : \ n % 2 5 s \ n % 2 5 . 4 s \ n " , s t r i n g , s t r i n g ) ;
I * D i s p l a y rea l n umbe r s . * /
p r i n t f ( " Rea l n umbe r s : \ n \ t%f % . 2f %e % E \ n " , fp , fp , fp , fp ) ;
/* D i s p l a y p o i n t e r s . */
p r i n t f ( " Add r e s s a s : \ n \ tDefa u l t : %p Nea r : % N p Fa r : % F p \ n " ,
& c o u n t , ( i n t _n ea r * ) &count , ( i n t _fa r * ) &c o u n t ) ;
/ * Count c h a r a c t e r s p r i nted . * /
p r i n t f C " D i s p l a y t o h e re : \ n " ) ;
p r i n t f ( " 1 234567890 1 2 3456%n7890 1 234567890 \ n " , &count ) ;
p r i ntf ( " \ t N umber d i s p l ayed : %d \ n \ n " , c o u n t ) ;
printf 588
Output
I n t e g e r f o rma t s :
Dec i ma l : - 9 234 J u s t i f i ed : - 009234 U n s i gned : 56302
D ec i ma l - 9 234 a s :
Hex : D B E E h C h e x : 0xdbee Oct a l : 1 5 5 7 5 6
D i g i t s 1 0 e q ua l :
Hex : 1 6 Oct a l : 8 Dec i ma l : 1 0
Cha racters i n fi el d :
h h
Stri ngs i n fi el d :
comp u t e r
c omp
Rea l n umbe r s :
2 5 1 . 7 36600 251 . 74 2 . 5 1 7 3 66e+002 2 . 5 1 7 3 6 6 E+002
Add r e s s a s :
Defa u l t : 141C N e a r : 141C Fa r : 0087 : 14 1 C
D i s p l ay t o h e r e :
1 2 34567890 1 2 34567 890 1 234567890
N umbe r d i s p l ayed : 1 6
589 pule, putchar
#include <Stdio.h>
c Character to be written
stream Pointer to FILE structure
Remarks The putc routine writes the single character c to the output stream at the current position.
The putchar routine is identical to putc(c, stdout).
These routines are implemented as both macros and functions. See Section 1 .4, "Choosing
Between Functions and Macros," for a discussion of how to select between the macro and
function forms.
Return Value The putc and putchar routines return the character written, or EOF in the case of an error.
Any integer can be passed to putc, but only the lower 8 bits are written.
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
{
FI LE *stream ;
c h a r *p , buffe r [ ] " Th i s i s t h e l i n e o f output \ n " ;
i nt ch ;
putc, putchar 590
I * Ma k e s t a n d a rd out t h e s t ream a n d w r i t e t o i t . * /
s t re a m = s t d o u t ;
f o r ( p = b uffer ; ( c h ! = EO F ) && ( *p ! = ' \ 0 ' ) ; p++ )
c h = putc ( *p , s t re a m ) ;
Output
T h i s i s t h e l i n e of o u t p u t
591 putch
c Character to be output
Remarks The putch function writes the character c directly (without buffering) to the console.
#i n c l u d e < c o n i o . h>
#i n c l u d e <ctype . h >
v o i d ma i n ( )
(
i nt c h ;
p ut c h ( c h ) ;
put c h ( ' \ r ' ) ; I * Ca rri age return */
putc h ( ' \ n ' ) ; I * L i n e feed */
Output
Remarks The putenv function adds new environment variables or modifies the values of existing en
vironment variables. Environment variables define the environment in which a process ex
ecutes (for example, the default search path for libraries to be linked with a program).
varname=string
where varname is the name of the environment variable to be added or modified and string
is the variable's value. If varname is already part of the environment, its value is replaced
by string; otherwise, the new varname variable and its string value are added to the en
vironment. A variable can be set to an empty value by specifying an empty string.
This function affects only the environment that is local to the currently running process; it
cannot be used to modify the command-level environment. When the currently running
process terminates, the environment reverts to the level of the parent process (in most
cases, the operating system level). However, the environment affected by putenv can be
passed to any child processes created by spawn, exec, system, or (in OS/2 only) _popen,
and these child processes get any new items added by putenv.
Never free a pointer to an environment entry, because the environment variable will then
point to freed space. A similar problem can occur if you pass putenv a pointer to a local
variable, then exit the function in which the variable is declared.
The putenv function operates only on data structures accessible to the run-time library and
not on the environment "segment" created for a process by DOS or OS/2.
Note that environment-table entries must not be changed directly. If an entry must be
changed, use putenv. To modify the returned value without affecting the environment
table, use strdup or strcpy to make a copy of the string.
The getenv and putenv functions use the global variable environ to access the environ
ment table. The putenv function may change the value of environ, thus invalidating the
envp argument to the main function. Therefore, it is safer to use the environ variable to
access the environment information.
Return Value The putenv function returns 0 if it is successful. A return value of -1 indicates an error.
593 putenv
#i n c l u d e < s t d l i b . h >
#i n c l u d e < s td i o . h >
ma i n ( )
(
c h a r *l i b va r ;
I * Get t h e v a l ue of t h e L I B e n v i ronment v a r i a b l e . * /
l i bv a r = geten v < " L I B " > :
i f ( l i bva r I = N U L L )
p r i n t f ( " O r i g i n a l L I B v a r i a b l e i s : %s \ n " , l i bva r ) :
I * Get new v a l u e . * /
l i b va r = geten v ( " L I B " ) ;
i f ( l i bv a r ! = N U L L )
p r i n t f ( " N ew L I B v a r i a b l e i s : % s \ n " , l i bv a r > :
Output
#include <graph.h>
void _far _putimage( short x, short y, char _huge *image, short action );
void _far _putimage_w( double wx, double wy, char _huge *image, short action );
Remarks The _putimage function transfers to the screen the image stored in the buffer that image
points to.
In the _putimage function, the upper-left comer of the image is placed at the view coordi
nate point (x, y). In the _pu timage_w function the upper-left comer of the image is placed
,
The action argument defines the interaction between the stored image and the one that is
already on the screen. It may be any one of the following manifest constants (defined in
GRAPH.ff):
Constant Meaning
_GAND Transfers the image over an existing image on the screen. The
resulting image is the logical-AND product of the two images:
points that had the same color in both the existing image and
the new one will remain the same color, while points that have
different colors are joined by logical-AND.
_GPSET Transfers the data point-by-point onto the screen. Each point
has the exact color attribute it had when it was taken from the
screen by _getimage.
#include <stdio.h>
Remarks The puts function writes string to the standard output stream stdout, replacing the string' s
terminating null character ('\0') with a newline character (\n) i n the output stream.
Return Value The puts function returns a nonnegative value if it is successful. If the function fails, it
retums EOF.
I * PUTS . C : T h i s p r o g r a m u s e s p u t s to w r i t e a s t r i n g to s tdout . * /
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
{
p ut s ( " H e l l o w o r l d f r om p u t s ! " > :
Output
H e l l o w o r l d f r om p u t s !
691 putw
#include <Stdio.h>
Remarks The putw function writes � binary value of type int to the current position of stream. The
putw function does not affect the alignment of items in the stream, nor does it assume any
special alignment.
The putw function is provided primarily for compatibility with previous libraries. Note
that pqrtability problems may occur with putw, since the size of an int and ordering of
bytes within an int differ across systems.
Rstum Va/us The putw function returns the value written. A return value of EOF may indicate an error.
Since EOF is also a legitimate integer value, ferror should be used to verify an error.
#i n c l u d e < s td i o . h >
#i ncl ude <stdl i b . h>
v o i d ma i n ( )
{
F I L E * s t r ea m :
u n s i gned u :
putw C u + 0 x 2 1 3 2 , s t d o u t ) ;
putw ( u + 0 x 2 1 3 2 , s t ream > : / * W r i t e word to s t re a m . * /
putw 598
i f ( fe r r o r C s t ream ) ) I * Ma ke e r r o r c h ec k . * /
(
p r i n t f ( " p utw fa i l ed " > :
c l ea re r r < s t ream > :
exi t ( 1 > :
}
p r i n t f ( " \ nWrote ten word s \ n " > :
f c l o s e ( s t ream > :
Output
213!4!51617 !8!9! : ! ; !
Wrote ten w o r d s
599 qsort
Rematits The qsort function implements a quick-sort algorithm to sort an array of num elements,
each of width bytes. The argument base is a pointer to the base of the array to be sorted.
The qsort function overwrites this array with the sorted elements.
The argument compare is a pointer to a user-supplied routine that compares two array ele
ments and returns a value specifying their relationship. The qsort function calls the
compare routine one or more times during the sort, passing pointers to two array elements
on each call:
Value Meaning
The array is sorted in increasing order, as defined by the comparison function. To sort an
array in decreasing order, reverse the sense of "greater than" and "less than" in the com
parison function.
qsart 600
# i n c l u d e < s ea r c h . h >
#i n c l u d e < s t r i ng . h >
#i n c l u d e < s t d i o . h >
I * E l i mi n a t e a rg v [ 0 ] f rom s o rt : * /
a rg v++ ;
a rg c- :
I * S o rt rema i n i n g a rg s u s i n g Q u i c ks o rt a l g o r i t h m : * /
q s o rt { < v o i d * l a rg v , C s i z e_t ) a rgc , s i zeof { c h a r * ) , comp a re ) ;
I * O u t p u t s o rted l i s t : */
fo r { i = 0 : i < a rg c : ++i
p r i n t f { " %s • , a rg v [ i ] > :
pri ntf { " \ n " > :
Output
#include <Signal.h>
Remarks The raise function sends sig to the executing program. If a signal-handling routine for sig
has ben installed by a prior call to signal, raise causes that routine to be executed. If no
handler routine has been installed, the default action (as listed below) is taken.
The signal value sig can be one of the following manifest constants:
Return Value If successful, the raise function returns 0. Otherwise, it returns a nonzero value.
Remarks The rand function returns a pseudorandom integer in the range 0 to RAND_MAX. The
srand routine can be used to seed the pseudorandom-number generator before calling
rand.
Return Value The rand function returns a pseudorandom number, as described above. There is no error
return.
I * RAN D . C : T h i s p r o g r a m s ee d s t h e r a n d om - n umber g e n e r a t o r w i t h t h e
* t i me , t h en d i s p l ays 20 r a n d om i n t e g e r s .
*I
v o i d ma i n ( )
(
i nt i ;
I * D i s p l ay 10 n umbe rs . * /
fo r ( i = 0 ; i < 10 ; i ++ )
p r i n t f ( • %6d \ n " , r a n d ( ) ) ;
rand 604
Output
1 947 1
1 6395
8268
1 5 58 2
6489
28356
27042
5276
23070
10930
605 read
Remarks The read function attempts to read count bytes into buffer from the file associated with
handle. The read operation begins at the current position of the file pointer associated with
the given file. After the read operation, the file pointer points to the next unread character.
Return Value The read function returns the number of bytes actually read, which may be less than count
if there are fewer than count bytes left in the file, or if the file was opened in text mode
(see below). The return value 0 indicates an attempt to read at end-of-file. The return value
-1 indicates an error, and errno is set to the following value:
Value Meaning
EBADF The given handle is invalid; or the file is not open for reading;
or (DOS versions 3.0 and later and OS/2 only) the file is
locked.
If you are reading more than 32K (the maximum size for type int) from a file, the return
value should be of type unsigned int (see the example that follows). However, the maxi
mum number of bytes that can be read from a file in one operation is 65,534, since 65,535
(or OxFFFF) is indistinguishable from -1 , and therefore cannot be distinguished from an
error return.
If the file was opened in text mode, the return value may not correspond to the number of
bytes actually read. When text mode is in effect, each carriage-return-line-feed (CR-LF)
pair is replaced with a single line-feed character. Only the single line-feed character is
counted in the return value. The replacement does not affect the file pointer.
Note that under DOS and OS/2, when files are opened in text mode, a CTRL+Z character is
treated as an end-of-file indicator. When the CTRL+Z is encountered, the read terminates,
and the next read returns 0 bytes. The lseek function will clear the end-of-file indicator.
c h a r buffe r [ 60000 ] ;
v o i d ma i n ( >
(
i nt f h ;
u n s i g n e d i n t nbytes = 60000 , byt e s r ea d ;
I * Open f i l e f o r i n put : * /
i f ( C f h = open ( " r e a d . c " , O_RDON LY > > -1
==
(
p e r ro r C " open fa i l ed on i n put fi l e " ) ;
exi t C 1 > ;
/ * Rea d i n i nput : * /
i f ( C by t e s read = re a d ( f h , buffe r , nbytes > > <= 0 >
p e r ro r C " P robl em rea d i n g f i l e " ) ;
el se
p r i n t f ( " Re a d % u bytes f rom f i l e \ n " , by t e s r e a d ) ;
c l os e ( f h > :
Output
Re a d 7 4 7 by tes from f i l e
601 realloc Functions
Remades The realloc family of functions changes the size of a previously allocated memory block.
The memblock argument points to the beginning of the memory block. If memblock is
NULL, realloc functions in the same way as malloc and allocates a new block of size
bytes. If memblock is not NULL, it should be a pointer returned by calloc, malloc, or a
prior call to realloc.
The size argument gives the new size of the block, in bytes. The contents of the block are
unchanged up to the shorter of the new and old sizes, although the new block may be in a
different location.
The memblock argument can also point to a block that has been freed, as long as there has
been no intervening call to the corresponding calloc, malloc, _expand, or realloc func
tion. If successful, the reallocated block is marked in use.
In large data models (that is, compact-, large-, and huge-model programs), realloc maps to
_frealloc. In small data models (tiny-, small-, and medium-model programs), realloc maps
to _nrealloc.
realloc Functions 608
The various realloc functions reallocate memory in the heap specified in the following list:
Function Heap
Retum Value The realloc functions return a void pointer to the reallocated (and possibly moved)
memory block.
The return value is NULL if the size is zero and the buffer argument is not NULL, or if
there is not enough available memory to expand the block to the given size. In the first
case, the original block is freed. In the second, the original block is unchanged.
The storage space pointed to by the return value is guaranteed to be suitably aligned for
storage of any type of object. To get a pointer to a type other than void, use a type cast on
the return value.
Campallblllty realloc
#i n c l u d e < s t d i o . h >
#i n c l u d e <ma l l oc . h >
#i n c l u d e < s t d l i b . h >
v o i d ma i n ( )
(
l on g *buffe r ;
s i z e_t s i ze :
s i z e = _ms i z e ( b u f f e r ) ;
p r i n t f ( " S i z e of b l oc k a ft e r ma l l oc of 1000 l on g s : % u \ n " , s i z e > :
I * Rea l l o c a t e a n d s h ow n ew s i z e : * /
i f ( ( bu f f e r = r ea l l oc C buffe r , s i z e + ( 1 000 * s i zeof ( l on g > > > > == N U L L
exi t ( 1 > :
s i z e = _ms i z e ( b u f f e r > :
p r i n t f ( " S i z e o f b l 9 c k a ft e r rea l l oc of 1 000 more l on g s : % u \ n " , s i z e > :
Output
S i z e of bl o c k a ft e r ma l l oc of 1000 l on g s : 4000
S i z e of b l o c k a ft e r rea l l oc of 1000 more l on g s : 8000
_rectangle Functions 610
#Include <grapb.h>
short _far _rectangle( short control, short xl, short y1, short x2, short y2 );
short _far _rectangle_w( short control, double wxl, double wyl, double wx2,
double wy2 );
short _far _rectangle_wxy( short control, struct _wxycoord _far *pwxyl,
struct _wxycoord _far *pwxy2 );
xl , yl Upper-left corner
Remades The _rectangle functions draw a rectangle with the current line style.
The _rectangle function uses the view coordinate system. The view coordinate points
(xl , yl) and (x2, y2) are the diagonally opposed comers of the rectangle.
The _rectangle_w function uses the window coordinate system. The window coordinate
points (wxl, wyl) and (wx2, wy2) are the diagonally opposed corners of the rectangle.
The _rectangle_wxy function uses the window coordinate system. The window coordinate
points (pwxyl) and (pwxy2) are the diagonally opposed corners of the rectangle. The
coordinates for the _rectangle_wxy routine are given in terms of an _wxycoord structure
(defined in GRAPH.ff), which contains the following elements:
Element Description
Constant Action
_ GFILLINTERIOR Fills the figure with the current color using the current fill
mask
If the current fill mask is NULL, no mask is used. Instead, the rectangle is filled with the
current color.
If you try to fill the rectangle with the _floodfill function, the rectangle must be bordered
by a solid line-style pattern.
Retum Value The function returns a nonzero value if the rectangle is drawn successfully, or 0 if not.
S11 Also _arc functions, _ellipse functions, _floodfill, _getcolor, _lineto functions,
_pie functions, _setcolor, _setfillmask
&� --
--
I * R E CT . C : T h i s p ro g r a m d ra w s a rec t a n g l e . * /
v o i d ma i n ( )
(
I * F i nd a v a l i d g r a ph i c s mode . * I
i f ( l _s e t v i d eomod e C _MA X RESMO D E )
ex i t ( 1 ) ;
getch ( ) ;
#include <graph.h>
Remarks The _registerfonts function initializes the fonts graphics system. Font files must be
registered with the _registerfonts function before any other font-related library function
(_getgtextextent, _outgtext, _setfont, _unregisterfonts) can be used.
The _registerfonts function reads the specified files and loads font header information
into memory. Each font header takes up about 140 bytes of memory.
The pathname argument is the path specification and file name of valid .FON files. The
pathname can contain standard DOS wild-card characters.
The font functions affect only the output from the font output function _outgtext; no other
C run-time output functions are affected by font usage.
Return Value The _registerfonts function returns a positive value which indicates the number of fonts
successfully registered. A negative return value indicates failure. The following negative
values may be returned:
Value Meaning
#include <graph.h>
Remarks The _remapallpalette function remaps the entire color palette simultaneously to the colors
. given in the colors array. The colors array is an array of long integers where the size of the
array varies from 1 6 to 64 to 256, depending on the video mode. The number of colors
mapped depends on the number of colors supported by the current video mode. The
_remapallpalette function works in all video modes (except _ORESCOLOR mode), but
only with EGA, MCGA, or VGA hardware.
The default color v alues for a color text on 16-color graphics mode are shown below:
The first array element specifies the new color value to be associated with color index 0
(the background color in graphics modes). After the call to _remapallpalette, calls to
_setcolor will index into the new array of colors. The mapping done by _remapallpalette
affects the current display immediately.
_remapal/palette, _remappalette 614
The colors array can be larger than the number of colors supported by the current video
mode, but only the first n elements are used, where n is the number of colors supported by
the current video mode, as indicated by the numcolors element of the videoconfig
structure.
The long color value is defined by specifying three bytes of data representing the three
component colors: red, green, and blue.
Each of the three bytes represents the intensity of one of the red, green, or blue component
colors, and must be in the range 0-3 1 . In other words, the low-order six bits of each byte
specify the component's intensity and the high-order two bits should be zero. The fourth
(high-order) byte in the long is unused and should be set to zero. The diagram below
shows the ordering of bytes within the long value.
For example, to create a lighter shade of blue, start with lots of blue, add some green, and
maybe a little bit of red. The three-byte color value would be:
Manifest constants are defined i n GRAPH.H for the default color values corresponding to
color indices 0-15 in color text modes and 1 6-color graphics modes, as shown below:
0 _BLACK 8 GRAY
_
1 _BLUE 9 _LIGHTBLUE
2 _GREEN 10 LIGHTGREEN
_
3 _CYAN 11 LIGHTCYAN
_
4 _RED 12 LIGHTRED
_
5 _MAGENTA 13 _LIGHTMAGENTA
6 _ BROWN 14 _YELLOW
7 _WHffE 15 _BRIGHTWIUTE
The VGA supports a palette of 262, 1 44 colors (256K) in color modes, and the EGA sup
ports a palette of only 64 different colors. Color values for EGA are specified in exactly
the same way as with the VGA; however, the low-order four bits of each byte are simply
ignored.
The _remappalette function assigns a new color value color to the color index given by
index. This remapping affects the current display immediately.
615 _remapallpalette, _remappalette
The _remappalette function works in all graphics modes, but only with EGA, MCGA,
or VGA hardware. An error results if the function is called while using any other
configuration.
The color value used in _remappalette is defined and used exactly as noted above for
_remapallpalette. The range of color indices used with _remappalette depends on the
number of colors supported by the video mode.
I * RM P A L P A L . C : T h i s exampl e i l l u s t ra t e s f u n c t i on s fo r a s s i g n i ng
* c o l o r v a l u e s t o c o l o r i n d i c e s . Fun c t i o n s i l l u s t ra t ed i n c l ude :
* _rema ppa l ette _rema pa l l pa l ette
*I
l on g tmp , p a l [ 2 5 6 ] ;
v o i d ma i n ( )
{
s h o rt red , b l u e , g reen ;
s ho r t i n c , i , mod e , c e l l s , x , y , x i n c , y i n c ;
char buf[40] ;
s t ruct v i deocon f i g vc ;
I * M a k e s u r e a l l p a l ette numb e r s a re v a l i d . * /
f o r ( i = 0 ; i < 2 5 6 ; i ++ >
pa l [ i ] = _B LAC K ;
i f ( mod e = _ERESNOCOLOR
mod e++ ;
i f ( ! _s e t v i d e omod e C mod e
cont i nue ;
I * Set v a r i a bl e s fo r ea c h mod e . */
_g e t v i d e o c o n f i g C & v c ) ;
s w i t c h ( v c . n umc o l o r s >
{
c a s e 256 : / * Ac t i v e b i t s i n t h i s o r d e r : */
cel l s = 13 ;
i nc = 1 2 ; / * ? ? ? ? ? ? ? ? ? ? bbbbbb ? ? gg g g g g ? ? r r r r r r * /
brea k ;
case 16:
i nc = 1 6 ; / * ? ? ? ? ? ? ? ? ? ?bb? ? ? ? ? ?gg? ? ? ? ? ? r r? ? ? ? * /
el se
i nc = 32 : I * ? ? ? ? ? ? ? ? ? ? Bb ? ? ? ? ? ? Gg? ? ? ? ? ? R r ? ? ? ? * /
b r ea k ;
case 4:
cel l s = 2;
i nc = 32 ; I * ? ? ? ? ? ? ? ? ? ? Bb ? ? ? ? ? ? Gg ? ? ? ? ? ? R r ? ? ? ? * /
brea k ;
defa u l t :
conti nue :
x i n c = v c . n umxp i x e l s I c e l l s ;
y i n c = v c . numy p i x e l s I c e l l s ;
611 _remapallpalette, _remappalette
I * F i l l pa l ette a r r a y s i n BGR o r d e r . * /
fo r e i = 0 , b l ue = 0 ; b l ue < 64 ; b l ue + = i n c >
fo r ( g r een = 0 ; g r een < 64 ; g r een += i n c )
fo r ( red 0 ; red < 64 ; red += i n c )
(
-
p a l [ i + S J = pa l [ i J I C pa l [ i J > > 1 ) ;
i f ( i nc = 32 )
i ++ ;
I * I f pa l e t t e s a v a i l a b l e , rema p a l l pa l e t t e s a t on c e . * I
i f ( ! _r ema pa l l pa l et t e C p a l > >
(
_s et v i d eomod e ( _D E FAU LTM O D E ) ;
_o u t t ex t ( " P a l e t t e s not a v a i l a b l e w i t h t h i s a d a p t e r • ) ;
ex i t ( 1 ) ;
I * D r a w c o l o red s q u a res . * /
fo r e i =0, x 0 ; x < C x i n c * c e l l s ) ; x += x i n c
=
fo r ( y = 0 ; y < C y i n c * c e l l s ) ; y + = y i n c )
(
_s e t c o l o r ( i ++ ) ;
_rec t a n g l e ( _G F I L L I NT E R I O R , x , y , x + x i n c , y + y i n c ) ;
I * C h a n g e ea c h p a l ette e n t ry s ep a r a t e l y i n GRB o r d e r . * I
fo r ( i = 0 , g reen 0 ; g reen < 64 ; g reen += i n c )
=
i ++ ;
)
getch ( ) ;
)
_s et v i d eomode ( _D E FAU LTMOD E ) ;
619 remove
Return Value The function returns 0 if the file is successfully deleted. Otherwise, it returns -1 and sets
errno to one of these values:
Value Meaning
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
(
i f ( remo v e ( " remo v e . obj " ) == -1 )
p e r r o r ( " C o u l d not d e l ete ' R EMOV E . O BJ ' " ) ;
el s e
p r i n t f ( " De l eted ' R EMO V E . OBJ ' \ n " ) ;
Output
Remarks The rename function renames the file or directory specified by o/dname to the name given
by newname. The old name must be the path name of an existing file or directory. The new
name must not be the name of an existing file or directory.
The rename function can be used to move a file from one directory to another by giving a
different path name in the newname argument. However, files cannot be moved from one
device to another (for example, from drive A to drive B). Directories can only be renamed,
not moved.
Return Value The rename function returns 0 if it is successful. On an error, it returns a nonzero value
and sets errno to one of the following values:
Value Meaning
v o i d ma i n ( )
(
i nt resul t ;
c h a r ol d [ ] = " R ENAM E R . OBJ " , new [ ] " RE NAM E R . J BO " ;
I * Attempt t o rename f i l e : * /
r e s u l t = ren a me ( o l d , new ) ;
i f ( res u l t ! = 0 )
p r i n t f ( " C o u l d not r e n a me ' % s ' \ n " , o l d ) ;
el se
p r i n t f ( " F i l e ' %s ' r e n a med t o ' %s ' \ n " , o l d , n ew ) ;
Output
#include <Stdio.h>
Remarks The rewind function repositions the file pointer associated with stream to the beginning of
the file. A call to rewind is equivalent to
v o i d ma i n ( )
{
FI LE * s t ream ;
i nt d a ta l , data 2 ;
data l 1;=
data2 = -37 ;
T h e v a l u e s w r i t t e n a re : 1 a n d - 3 7
T h e v a l ues r e a d a re : 1 a n d - 3 7
rmdir 624
Remades The rmdir function deletes the directory specified by dirname. The directory must be
empty, and it must not be the current working directory or the root directory.
Retum Value The rmdir function returns the value 0 if the directory is successfully deleted. A return
value of -1 indicates an error, and errno is set to one of the following values:
Value Meaning
EACCES The given path name is not a directory; or the directory is not
empty; or the directory is the current working directory or the
root directory.
ENOENT Path name not found.
Exampm ��������-
1 * MAKE D I R . C * /
#i n c l u d e < d i r e ct . h>
#i ncl ude <stdl i b . h>
#i n c l u d e < s t d i o . h >
v o i d ma i n { )
[
i nt r e s u l t ;
625 rmdir
Output
#include <Stdio.h>
Remarks The rmtmp function is used to clean up all the temporary files in the current directory.
The function removes only those files created by tmpfile and should be used only in the
same directory in which the temporary files were created.
Return Value The rmtmp function returns the number of temporary files closed and deleted.
I * TM P F I L E . C : T h i s p ro g r a m u s e s tmpfi l e to c r e a t e a t emp o r a ry f i l e ,
* t h en d e l e t e s t h i s f i l e wi t h rmtmp .
*I
v o i d ma i n ( )
(
F I LE *st ream ;
c h a r t emp s t r i ng [ ] = " St r i n g t o be w r i t t en " ;
i nt i ;
/ * C re a t e t empo r a ry f i l es . * /
for e i = l ; i <= 1 0 ; i ++ )
(
i f ( ( s t ream = tmpfi l e ( ) ) == N U L L
p e r r o r C " C o u l d n o t open n e w t emp o r a ry f i l e \ n " ) ;
el se
p r i n t f C " Temp o r a ry f i l e %d w a s c re a t ed \ n " , i ) ;
I * Remov e t empo r a ry f i l es . * /
p r i n t f ( " %d t emp o r a ry f i l es d e l eted \ n " , rmtmp ( ) ) ;
627 rmtmp
Output
#include <Stdlib.h>
Remades The _rotl and _rotr functions rotate the unsigned value by shift bits. The _rotl function
rotates the value left. The _rotr function rotates the value right. Both functions "wrap" bits
rotated off one end of value to the other end.
Return Value Both functions return the rotated value. There is no error return.
#i n c l u d e < s t d l i b . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
{
u n s i gned v a l = 0x0fd 9 3 ;
Output
#include <Stdio.h>
Remarks The scanf function reads data from the standard input stream stdio into the locations given
by argument. Each argument must be a pointer to a variable with a type that corresponds
to a type specifier in format. The format controls the interpretation of the input fields. The
format can contain one or more of the following:
• White-space characters: blank (' '); tab (\t); or newline (\n). A white-space character
causes scanf to read, but not store, all consecutive white-space characters in the input
up to the next non-white-space character. One white-space character in the format
matches any number (including 0) and combination of white-space characters in the
input.
• Non-white-space characters, except for the percent sign ( % ). A non-white-space char
acter causes scanf to read, but not store, a matching non-white-space character. If the
next character in stdio does not match, scanf terminates.
The format is read from left to right. Characters outside format specifications are expected
to match the sequence of characters in stdio; the matching characters in stdio are scanned
but not stored. If a character in stdio conflicts with the format specification, scanf termi
nates. The character is left in stdio as if it had not been read.
When the first format specification is encountered, the value of the first input field is con
verted according to this specification and stored in the location that is specified by the first
argument. The second format specification causes the second input field to be converted
and stored in the second argument, and so on through the end of the format string.
An input field is defined as all characters up to the first white-space character (space, tab,
or newline), or up to the first character that cannot be converted according to the format
specification, or until the field width (if specified) is reached. If there are too many argu
ments for the given specifications, the extra arguments are evaluated but ignored. The re
sults are unpredictable if there are not enough arguments for the format specification.
681 scant
Each field of the fonnat specification is discussed in detail below. If a percent sign ( % ) is
followed by a character that has no meaning as a fonnat-control character, that character
and the following characters (up to the next percent sign) are treated as an ordinary
sequence of characters--that is, a sequence of characters that must match the input. For ex
ample, to specify that a percent-sign character is to be input, use %% •
An asterisk (*) following the percent sign suppresses assignment of the next input field,
which is interpreted as a field of the specified type. The field is scanned but not stored.
The width is a positive decimal integer controlling the maximum number of characters to
be read from stdin. No more than width characters are converted and stored at the corre
sponding argument. Fewer than width characters may be read if a white-space character
(space, tab, or newline) or a character that cannot be converted according to the given for
mat occurs before width is reached.
The optional F and N prefi�es allow the user to specify whether the argument is far or
near, respectively. F should be prefixed to an argument pointing to a far object, while N
should be prefixed to an argument pointing to a near object. Note also that the F and N pre
fixes are not part of the ANSI definition for scanf, but are instead Microsoft extensions,
which should not be used when ANSI portability is desired.
The optional prefix I indicates that the long version of the following type is to be used,
while the prefix h indicates that the short version is to be used. The corresponding
argume111 should point to a long or double object (with the I character) or a short object
(with the h character). The I and h modifiers can be used with the d, i, n, o, x, and u type
characters. The I modifier can also be used with the e, f, and g type characters. The I and h
modifiers are ignored if specified for any other type.
For scanf, N and F refer to the "distance" to the object being read in (near or far) and h
and I refer to the "size" of the object being read in ( 16-bit short or 32-bit long). The list
below clarifies this use of N, F, I, and h:
scant 632
The type characters and their meanings are described in Table R.5.
To read strings not delimited by space characters, a set of characters in brackets ([ ]) can
be substituted for the s (string) type character. The corresponding input field is read up to
the first character that does not appear in the bracketed character set. If the first character
in the set is a caret ( " ), the effect is reversed: the input field is read up to the first character
that does appear in the rest of the character set.
Note that % [a·z] and % [z·a] are interpreted as equivalent to % [abcde...z]. This is a com
mon scanf extension, but note that it is not required by the ANSI specification.
To store a string without storing a terminating null character ('\0'), use the specification
% nc, where n is a decimal integer. In this case, the c type character indicates that the argu- .
ment is a pointer to a character array. The next n characters are read from the input stream
into the specified location, and no null character ('\O') is appended. If n is not specified, the
default value for it is 1 .
The scanf function scans each input field, character by character. It may stop reading a par
ticular input field before it reaches a space character for a variety of reasons: the specified
width has been reached; the next character cannot be converted as specified; the next char
acter conflicts with a character in the control string that it is supposed to match; or the next
character fails to appear in a given character set. For whatever reason, when scanf stops
reading an input field, the next input field is considered to begin at the first unread charac
ter. The conflicting character, if there is one, is considered unread and is the first character
of the next input field or the first character in subsequent read operations on stdio.
scant
t Since the input for a %x fonnat specifier is always interpreted as a hexadecimal number, the input should
not include a leading Ox. (If Ox is included, the 0 is interpreted as a hexadecimal input value.)
Return Value The scanf function returns the number of fields that were successfully converted and as
signed. The return value may be less than the number requested in the call to scanf. The re
turn value does not include fields that were read but not assigned.
The return value is EOF if the end-of-file or end-of-string is encountered in the first at
tempt to read a character.
scant 634
I * SCAN F . C : T h i s p r o g r a m r e c e i v e s f o rma t t ed i n p u t u s i n g s c a n f .
#i n c l ude < s t d i o . h>
*/
v o i d ma i n ( )
(
i nt i ;
fl oat fp ;
char c , s [81] ;
i nt resul t ;
Output
E n t e r a n i n t e g e r , a f l o a t i n g - p o i n t n umb e r , a c h a ra c t e r a n d a s t r i n g :
71
98 . 6
h
Whi te space stops i nput
T h e n um b e r o f f i e l d s i n p u t i s 4
The contents a r e : 7 1 98 . 599998 h Wh i te
635 _scralltextwindow
#include <graph.h>
Remarks The _scrolltextwindow function scrolls the text in a text window (previously defined by
the _settextwindow function). The lines argument specifies the number of lines to scroll.
A positive value of lines scrolls the window up (the usual direction); a negative value
scrolls the window down. Specifying a number larger than the height of the current text
window is equivalent to calling _clearscreen( _GWINDOW ) . A value of 0 for lines has no
effect on the text.
Example __________________________________________________________________�
#i n c l u d e < s t d i o . h >
#i n c l u d e < c on i o . h >
#i n c l u d e < g r a p h . h >
v o i d ma i n ( )
{
s h o r t r ow ;
c h a r b u f [ 40 J ;
I * D e l ete s ome l i n e s . * /
_s ettextpos i t i on C 1 1 , 1 ) ;
fo r ( row = 1 2 ; row < 20 ; row++
del etel i ne ( ) ;
s t a t u s ( " D e l eted 8 l i n e s " ) ;
/ * I n s e rt s ome l i n e s . * /
_s e t t e x t po s i t i on ( 5 , 1 ) ;
for e row = 1 ; row < 6 ; row++
i n s e rt l i n e ( ) ;
s t a t u s < " I n s e rted 5 l i n es " ) ;
I * S c r o l l u p a nd d own . * /
_s c r o l l t ex tw i n d ow C 7 ) ;
-
s t a t u s ( " S c r o l l ed d own 7 l i n e s • ) ;
_s c r o l l t e x tw i n d ow C 5 ) ;
s t a t u s ( " Sc rol l ed u p 5 l i n e s • ) ;
_s etv i d eomod e ( _D E FAU LTMO D E ) ;
I * I n s e rt s ome l i n es by s c ro l l i n g i n b l a n k l i n e s from t h e t o p of t h e
* c u r rent t e x t w i ndow . S a v e a n d r e s t o r e o r i g i n a l wi n d ow .
*I
voi d i nsertl i ne ( )
I
s h o r t l e ft , t o p , r i g h t , bottom :
s t r u c t r c c o o rd re :
I * D i s p l ay a nd c l ea r s t a t u s i n i t s own wi ndow . * /
v o i d s t a t u s ( c h a r *ms g )
I
s h o r t l eft , top , r i g h t , bottom :
s t r u c t r c c o o rd re :
#include <Stdlib.h>
Remam The _searchenv routine searches for the target file in the specified domain. The varname
variable can be any environment variable which specifies a list of directory paths, such as
PATH, LIB, INCLUDE, or other user-defined variables. It is most often PATH, which
searches forfilename on all paths specified in the PATH variable. The _searchenv func
tion is case-sensitive, so the varname variable should match the case of the environment
variable.
The routine first searches for the file in the current working directory. If it doesn't find the
file, it next looks through the directories specified by the environment variable.
If the target file is found in one of the directories, the newly created path is copied into the
buffer pointed to by pathname. You must ensure that there is sufficient space for the con
structed path name. If the filename file is not found, pathname will contain an empty null
terminated string.
Exampm --------�
I * S EA RC H E N . C : T h i s p ro g r a m s e a r c h e s for a f i l e i n a d i r e c t o ry
* s p ec i f i ed by a n e n v i ronment v a r i a b l e .
*I
v o i d ma i n ( )
(
c h a r p a t h bu f f e r [_MAX_PATH ] ;
c h a r sea rchfi l e[ ] = • c l . EXE• ;
c h a r e n v v a r [ ] - • PATH • ;
I * Sea r c h f o r f i l e i n PATH en v i ronment v a r i a b l e : * /
_s ea rc h en v C s e a rc h f i l e , e n v v a r , p a t hbuffer ) ;
i f ( *pa t h bu f f e r ! - \ 0 )
' '
p ri nt f ( • Pa t h f o r S s : Ss \ n • , s e a r c h f i l e , p a t hbuffer ) ;
el se
p r i n t f C " S s n o t fou n d \ n " , s e a r c h f i l e ) ;
Output
P a t h fo r C L . EX E : C : \ B I N \ C L . E X E
segread 640
#include <dos.h>
Remarks The segread function fills the structure pointed to by segregs with the current contents of
the segment registers. The SREGS union is described in the reference section for int86x.
This function is intended to be used with the intdosx and int86x functions to retrieve
segment-register values for later use.
I * S E G READ . C : T h i s p r o g r a m g e t s t h e c u r re n t s egment v a l u e s wi t h s eg r ea d . * /
v o i d ma i n ( )
[
s t ruct S R E G S s e g r eg s ;
u n s i g n e d c s , ds , e s , s s ;
Output
#include <graph.h>
R1matb The _selectpalette function works only under the video modes _MRES4COLOR and
_MRESNOCOLOR. A palette consists of a selectable background color (Color 0) and three
set colors. Under the _MRES4COLOR mode, the number argument selects one of the four
·
Color Index
Color Index
Under the EGA configuration, the three palettes shown in Table R.8 are available in the
_MRESNOCOLOR video mode.
Color Index
Palette 1 .
R1tum Value The function returns the value of the previous palette. There is no error return.
l on g b k c o l o r [ 8 ] { _B LAC K , _B LU E , _G RE E N , _CYAN ,
_WH I T E } ;
=
i f C ! _s e t v i d e omod e C _M R E S4C O L O R
{
p r i n t f C " N o pa l ettes a v a i l a b l e " ) ;
exi t ( 1 ) ;
_selectpalette 644
for ( i = 0 ; i < 4 ; i ++ ) I* P a l e t t e l oo p */
{
_s e l e c t p a l e t t e ( i ) ;
for ( k = 0 ; k < 8 ; k++ I* B a c k g round c o l o r l oop * /
{
_c l ea r s c reen ( _GC LEARSC R E E N ) ;
_s e t b k c o l o r ( b k c o l o r [ k ] ) ;
_s e t t e x t p o s i t i on ( 1 , 1 ) ;
p r i n t f ( " Ba c k g round : % s \ t Pa l e t t e : %d " , b k n a me [ k ] , i ) ;
fo r ( j = 1 ; j < 4 ; j ++ > I* Foreg round c o l o r l oop * /
{
_s e t c o l o r ( j ) ;
_e l l i p s e ( _G F I L L I NT E R I O R , 100 , j * 30 , 220 , 8 0 + ( j * 30 ) ) ;
)
g et c h ( ) ;
)
_set v i d eomod e ( _D E FAU LTMO D E ) ;
645 _setactivepage
#include <graph.h>
Remarks For hardware and mode configurations with enough memory to support multiple screen
pages, _setactivepage specifies the area in memory in which graphics output is written.
The page argument selects the current active page. The default page number is 0.
Screen animation can be done by alternating the graphics pages displayed. Use the
_setvisualpage function to display a completed graphics page while executing graphics
statements in another active page.
These functions can also be used to control text output if you use the text functions
_gettextcursor, _settextcursor, _outtext, _settextposition, _gettextposition,
_settextcolor, _gettextcolor, _settextwindow, and _wrapon instead of the standard
C-language 1/0 functions.
The CGA hardware configuration has only 1 6K of RAM available to support multiple
video pages, and only in the text mode. The EGA and VGA configurations may be
equipped with up to 256K of RAM for multiple video pages in graphics mode.
Return Value If successful, the function returns the page number of the previous active page. If the func
tion fails, it returns a negative value.
v o i d ma i n ( )
{
s hort o l d v p a g e , o l d a pa g e , p a g e , row , c o l , l i n e ;
s t ruct v i d e o c on f i g v c ;
char b u f [ 80 J ;
_g etv i d e o c o n f i g ( & v c ) ;
i f ( v c . numv i deop a g e s < 4
exi t ( 1 ) : / * Fa i l f o r O S / 2 o r monoc h rome * /
o l d a p a g e = _geta c t i v e p a g e C ) :
o l d v p a g e = _ge t v i s u a l p a ge ( ) ;
_d i s p l a y c u r s o r ( _GC U RSO RO F F ) ;
I * D r a w a r rows i n d i fferent p l a c e o n e a c h p a g e , * /
f o r ( p a g e = 1 : p a g e < 4 : p a g e++ )
{
_s eta c t i v e pa g e ( p a g e ) :
_s ettextpos i t i on C 1 2 , 1 6 * pa g e l :
_o uttext ( " > > > > > > > > " l :
w h i l e < ! kb h i t ( ) )
I * Cyc l e t h ro u g h p a g e s 1 to 3 to s h ow mov i ng i ma g e . * /
fo r ( p a g e = 1 : p a g e < 4 ; p a g e++
_s et v i s u a l pa g e C p a g e ) ;
getc h C l :
I * R e s t o r e o r i g i n a l p a g e ( n o rma l l y 0 ) t o r e s t o r e s c reen . * I
_s eta c t i vepa g e C o l d a p a g e l :
_s et v i s ua l p a g e ( o l d v p a g e ) :
_d i s p l a y c u r s o r_C _GC U RS O RO N ) :
647 _setbkcolor
#include <graph.h>
R1ma"'8 The _setbkcolor function sets the current background color to the color value color.
In a color text mode (such as _TEXTCSO), _setbkcolor accepts (and _getbkcolor returns)
a color index. The value for the default colors is given in a table in the description of the
_settextcolor function. For example, _setbkcolor(2L) sets the background color to color
index 2. The actual color displayed depends on the palette mapping for color index 2. The
default is green in a color text mode.
In a text mode, the _setbkcolor function does not affect anything already appearing on the
display; only the subsequent output is affected. In a graphics mode, it immediately changes
all background pixels.
R,,,,,,.,, Value In text modes, setbkcolor returns the color index of the old background color. In graphics
modes, _setbkcolor returns the old color value of color index 0. There is no error return.
#include <Stdio.h>
Rematks The setbuf function allows the user to control buffering for stream. The stream argument
must refer to an open file that has not ·been read or written. If the buffer argument is NULL,
the stream is unbuffered. If not, the buffer must point to a character array of length
BuFSIZ, where BUFSIZ is the buffer size as defined in STDIO.ff. The user-specified buff
er, instead of the default system-allocated buffer for the given stream, is used for 1/0
buffering.
The stderr and (in DOS only) stdaux streams are unbuffered by default, but may be as
signed buffers with setbuf.
The setbuf function has been subsumed by the setvbuf function, which should be the pre
ferred routine for new code. The setbuf function is retained for compatibility with ex
isting code.
Exampm ��������-
v o i d ma i n ( )
{
c h a r b u f [ B U FS I Z ] ;
F I L E * s t r e a m l , * s t ream2 ;
649 setbuf
Output
#include <graph.h>
Remarks The _setcliprgn function limits the display of subsequent graphics output and font text out
put to an area of the screen called the "clipping region." The physical points (xi, yi) and
(x2, y2) are the diagonally opposed sides of a rectangle that defines the clipping region.
This function does not change the view coordinate system. Rather, it merely masks the
screen.
Note that the _setcliprgn function affects graphics and font text output only. To mask the
screen for text output, use the _settextwindow function.
&• �����
I * S C L I P RGN . C * /
#i n c l u d e < s t d l i b . h >
#i n c l u d e < c o n i o . h >
#i n c l u d e < g r a p h . h >
v o i d ma i n ( )
{
/ * F i n d a v a l i d g r a p h i c s mod e . * /
i f ( ! _s e t v i deomod e ( _MAX R E S M O D E )
exi t C 1 ) ;
/ * Set c l i p r e g i o n , t h e n d ra w a n d e l l i p s e l a rg e r t h a n · t h e reg i on . * /
_s etc l i p r g n C 0 , 0 , 200 , 1 2 5 > :
_el l i p s e ( _G F I L L I NT E R I O R , 80 , 50 , 240 , 1 9 0 ) ;
651 _setcliprgn
getch ( ) ;
_s et v i d eomod e ( _ O E FAU LTM O D E ) ;
_setcolor 652
#include <graph.h>
Remarks The _setcolor function sets the current color index to color. The color parameter is
masked but always within range. The following graphics functions use the current color:
_arc, _ellipse, _ftoodfill, _lineto, _outgtext, _pie, _rectangle, and _setpixel.
The _setcolor function accepts an int value as an argument. It is a color index.
The default color index is the highest numbered color index in the current palette.
Note that the _setcolor function does not affect the output of the presentation-graphics
functions.
Return Value This function returns the previous color. If the function fails (e.g., if used in a text mode),
it returns - 1 .
See Also _arc functions, _ellipse functions, _ftoodfill, _getcolor, _lineto functions, _outgtext,
_pie functions, _rectangle functions, _selectpalette, _setpixel functions
I * G P I X E L . C : T h i s p r o g r a m a s s i g n s d i fferent c o l o r s t o r a n d oml y
* s e l ected pi xel s .
*I
v o i d ma i n ( )
(
s h o r t x v a r , yv a r :
s t r u c t v i deocon f i g v c :
1sa _setcolor
I * F i nd a va l i d g r a p h i c s mode . * /
i f ( ! _s e t v i d eomode ( _MA X C O LORMODE ) )
ex i t ( 1 ) ;
_g et v i d e o c on f i g ( &vc > :
I * D r a w f i l l ed e l l i p s e t o t u r n on c e rta i n pi x e l s . * /
_e l l i ps e ( _G F I L L I NT E R I O R , vc . n umx p i x e l s I 6 , v c . n umy p i x e l s I 6 ,
vc . n umx p i x e l s I 6 * 5 , vc . numyp i xel s I 6 * 5 );
I * D r a w ra ndom p i x e l s i n ra ndom c o l o r s . . . * I
whi l e ( ! kbhi t ( ) )
{
I * . . . but o n l y i f t h ey a re a l r e a dy on ( i n s i d e t h e e l l i p s e ) . * /
x v a r = r a n d ( ) % vc . numx p i x e l s ;
y v a r = r a nd ( ) % vc . numy p i x e l s ;
i f ( _g et p i x e l ( x v a r , yv a r ) ! = 0
{
_s e t c o l o r ( r a n d ( ) % 1 6 ) ;
_s e t p i x e l C x v a r , y v a r > :
#include <graph.h>
Remarks The _setfillmask function sets the current fill mask, which determines the fill pattern. The
mask is an 8-by-8 array of bits in which each bit represents a pixel. A 1 bit sets the corre
sponding pixel to the current color, while a 0 bit leaves the pixel unchanged. The pattern is
repeated over the entire fill area.
If no fill mask is set (mask is NULL-the default), only the current color is used in fill
operations.
See Also _ellipse functions, _floodtill, _getfillmask, _pie functions, _rectangle functions
Exampm --------�
/ * G F I L LM S K . C : T h i s p ro g r a m i l l u s t r a t e s _g e t f i l l ma s k a n d _s e t f i l l ma s k . * /
u n s i gned c h a r ma s k 2 [ 8 ] =
c h a r o l dma s k [ 8 ] ;
v o i d ma i n ( )
[
i nt 1 oop ;
/ * F i n d a v a l i d g r a p h i c s mod e . * /
i f ( ! _s e t v i d eomod e ( _MA X R E SMO D E )
exi t ( 1 ) ;
655 _seffillmask
I * Set f i r s t f i l l ma s k a n d d ra w rect a n g l e . * /
_s e t f i l l ma s k C ma s k l l ;
_recta n g l e ( _G F I L L I N T E R I O R , 20 , 20 , 100 , 100 ) ;
getch ( ) ;
I * C a l l rout i n e t h a t s a v e s a n d r e s t o r e s ma s k . * /
e l l i p s ema s k ( 60 , 60 , 1 50 , 1 50 , ma s k2 ) ;
getc h ( l ;
I * Ba c k t o o r i g i n a l ma s k . * /
_r e c t a n g l e ( _G F I L L I NT E R I O R , 1 2 0 , 1 2 0 , 190 , 1 9 0 l ;
getch C l ;
I * D ra w a n e l l i ps e w i t h a s p ec i f i ed f i l l ma s k . * /
v o i d e l l i ps ema s k ( s h ort x l , s h o rt y l , s h o rt x 2 , s h o rt y2 , c h a r _fa r *n ewma s k )
(
u n s i gned c h a r s a vema s k [ 8 ] ;
_g e t f i l l ma s k ( s a v ema s k ) ; I* S a v e ma s k *I
_s e t f i l l ma s k C n ewma s k l ; I* Set n ew ma s k *I
_e l l i ps e ( _G F I L L I NT E R I O R , x l , y l , x 2 , y2 ) ; I* U s e n ew ma s k *I
_s e t f i l l ma s k ( s a v ema s k ) ; I* Res t o re o r i g i n a l *I
_selfant 656
#include <grapb.h>
Remades The _setfont function finds a single font, from the set of registered fonts, that has the char
acteristics specified by the options string. If a font is found, it is made the current font. The
current font is used in all subsequent calls to the _outgtext function. There can be only one
active font at any time.
The options string is a set of characters that specifies the desired characteristics of the font.
The _setfont function searches the list of registered fonts for a font matching the specified
characteristics.
The characteristics that may be specified in the options string are shown in the list below.
Characteristics specified in the options string are not case- or position-sensitive.
Characteristic Description
t'fontname' T}'peface.
You can request as many options as desired, except with nx, which should be used alone.
If mutually exclusive options are requested (such as the pair f/p or r/v), the _setfont func
tion ignores them. There is no error detection for incompatible parameters used with nx.
Options can be separated by blanks in the options string. Any other character is ignored by
_setfont
The t (the typeface specification) in options is specified as a "t" followed by fontname in
single quotes. Choosefontname from the following list:
Fontname Description
A b in the options field causes the _setfont routine to automatically select the "best fit"
font that matches the other characteristics you have specified. If the b parameter is spec
ified and at least one font is registered, _setfont will always be able to set a font and will
return 0 to indicate success.
In selecting a font, the _setfont routine uses the following precedence (rated from highest
precedence to lowest):
I . Pixel height
2. T}'peface
3. Pixel width
4. Fixed or proportional font
You can also specify a pixel width and height for fonts. If a nonexistent value is chosen for
either, and the b option is specified, the _setfont function will chose the closest match. A
smaller font size has precedence over a larger size. If _setfont requests Helv 1 2 with best
fit, and only Helv 1 0 and Helv 14 are available, _setfont will select Helv 1 0.
If a nonexistent value is chosen for pixel height and width, the _setfont function will apply
a magnification factor to a vector-mapped font to obtain a suitable font size. This auto
matic magnification does not apply if the r (raster-mapped font) option is specified, or if a
specific typeface is requested and no best fit (b) option is specified.
_setfont 658
If you specify the nx parameter, _setfont will ignore any other specified options and
supply only the font number corresponding to x.
Note that the font functions affect only the output from the font output function _outgte:xt;
no other C run-time output functions are affected by font usage.
Retum Value The setfont function returns a 0 to indicate success and a -1 to indicate an error. An
erroroccurs if a request for a specific font fails and the b option was not specified, or if
fonts have not yet been registered.
#include <graph.h>
Remarks The _setgtextvector function sets the current orientation for font text output to the vector
specified by x and y. The current orientation is used in calls to the _outgtext function.
The values of x and y define the vector which detennines the direction of rotation of font
text on the screen. The t�xt-rotation options are shown below:
(0, 0) Unchanged
(- 1 , 0) Rotated 1 80 degrees
If other values are input, only the sign of the input is used. For example, (-3, 0) is inter
preted as (-1 , 0).
Relum Value The _setgtextvector function returns the previous vector in a structure of xycoord type. If
you pass the _setgtextvector function the values (0, 0), the function returns the current
vector values in the xycoord structure.
#include <Setjmp.h>
Rematts The setjmp function saves a stack environment that can be subsequently restored using
longimp. Used together this way, setjmp and longimp provide a way to execute a "non
local goto." They are typically used to pass execution control to error-handling or recovery
code in a previously called routine without using the nonnal calling or return conventions.
A call to setjmp causes the current stack environment to be saved in env. A subsequent
call to longjmp restores the saved environment and returns control to the point just after
the corresponding setjmp call. All variables (except register variables) accessible to the
routine receiving control contain the values they had when setjmp was called.
Return Value The setjmp function returns 0 after saving the stack environment. If setjmp returns as a re
sult of a longimp call, it returns the value argument of longjmp, or, if the value argument
of longimp is 0, setjmp returns 1 . There is no error return.
#include <graph.h>
Rematics Some graphics routines ( _lineto and _rectangle) draw straight lines on the screen. The
type of line is controlled by the current line-style mask.
The _sedinestyle function selects the mask used for line drawing. The mask argument is a
1 6-bit array , where each bit represents a pixel in the line being drawn. If a bit is l , the
corresponding pixel is set to the color of the line (the current color). If a bit is 0, the corre
sponding pixel is left unchanged. The template is repeated for the entire length of the line.
The default mask is OxFFFF (a solid line).
#include <locale.h>
locale Name of the locale that will control the specified category
Remades The setlocale function sets the categories specified by category to the locale specified by
locale. The "locale" refers to the locality (country) for which certain aspects of your pro
gram can be customized. Some locale-dependent aspects include the fonnatting of dates
and the display fonnat for monetary values.
The setlocale function is used to set or get the program's current entire locale or simply
portions of the locale infonnation. The category argument specifies which portion of a pro
gram's locale infonnation will be used. The manifest constants used for the category argu
ment are listed below:
The locale argument is a pointer to a string that specifies the name of the locale. If
locale points to an empty string, the locale is the implementation-defined native environ
ment. A value of "C" specifies the minimal ANSI confonning environment for C transla
tion. This is the only locale supported in Microsoft C, version 6.0.
If the locale argument is a null pointer, setlocale returns a pointer to the string associated
with the category of the program's locale. The program's current locale setting is not
changed.
663 setlocale
Return Value If a valid locale and category are given, _setlocale returns a pointer to the string associated
with the specified category for the new locale. If the locale or category is invalid, the
setlocale function returns a null pointer and the program's current locale settings are not
changed.
The pointer to a string returned by setlocale can be used in subsequent calls to restore that
part of the program ' s locale infonnation. Later calls to setlocale will overwrite the string.
#include <fcntl.h>
#include <io.h> Required only for function declarations
Remades The setmode function sets to mode the translation mode of the file given by handle. The
mode must be one of the following manifest constants:
Constant Meaning
Return Value If successful, setmode returns the previous translation mode. A return value of -1 indi
cates an error, and errno is set to one of the following values:
Value Meaning
#i n c l u d e < s t d i o . h >
#i n c l u d e < f c n t l . h >
#i n c l u d e < i o . h >
v o i d ma i n < >
{
i n t res u l t ;
Output
#include <graph.h>
Rematlrl The _setpixel and the _setpixel_w functions set a pixel at a specified location to the
current color.
The _setpixel function sets the pixel at the view-coordinate point (x, y) to the current color.
The _setpixel_w function sets the pixel at the window-coordinate point (wx, wy) to the
current color.
Retum Value The function returns the previous value of the target pixel. If the function fails (for ex
ample, the point lies outside of the clipping region), it will return - 1 .
I * G P I X E L . C : T h i s p r o g r a m a s s i g n s d i fferent c o l o r s t o r a n d oml y
* s e l ected p i x e l s .
*I
v o i d . ma i n ( )
I
s ho r t x va r , y v a r ;
s t ruct v i d e o c on f i g v c ;
667 _setpixel Functions
I * F i nd a v a l i d g r a p h i c s mode . * /
i f { ! _s e t v i d eomode { _MA X C O LORMODE ) )
exi t < 1 ) :
_g et v i d e o c o n f i g { & v c > :
I * D r a w f i l l ed e l l i p s e t o t u r n on c e r t a i n p i x e l s . * /
_e l l i ps e { _G F I L L I N T E R I O R , vc . n umxp i x e l s I 6 , vc . n umyp i x e l s I 6 ,
vc . n umxp i x e l s I 6 * 5 , vc . numyp i xel s I 6 * 5 ) ;
/ * D r a w ra n d om p i x e l s i n r a n d om c o l o r s . . . * /
w h i l e { ! kb h i t { ) )
(
I * . . . b u t on l y i f t h ey a r e a l r e a dy on { i n s i d e t h e e l l i p s e ) . * /
x v a r = r a nd { ) % v c . n umxp i xe l s ;
y v a r = r a nd < > % vc . n umy p i x e l s ;
i f { _g e t p i x e l { x v a r , y v a r ) ! = 0
(
_s e t c o l o r C r a n d ( ) % 16 > :
_s e t p i x e l ( x v a r , y v a r > :
#include <graph.h>
Rematfcs The _settextcolor function sets the current text color to the color index specified by index.
The default text color is the same as the maximum color index.
The settextcolor routine sets the color for the outtext and outmem functions only. It
doesnot affect the color of the printf function or the color oftext output with the
_outgtext font routine. Use the _setcolor function to change the color of font output.
In text color mode, you can specify a color index in the range 0 -3 1 . The colors in the
range 0 - 1 5 are interpreted as normal (non-blinking). The normal color range is defined
below:
Return Value The function returns the color index of the previous text color. There is no error return.
669 _settextcolor
#i n c l u d e < c o n i o . h >
#i n c l ude < s t d i o . h >
#i n c l u d e < g ra p h . h >
c h a r buffer [80] ;
v o i d ma i n { )
(
I * S a v e o r i g i n a l f o r e g r o u n d , b a c k g r ound , a n d t e x t po s i t i on * /
s h o r t b l i n k , fgd , o l dfgd ;
l on g bgd , o l dbgd ;
s t ruct rccoord o l d p o s ;
I * S a v e o r i g i n a l f o r e g r o u n d , b a c k g round , a n d text po s i t i on . * /
o l dfgd = _g e t t e x t c o l o r { ) ;
o l d b g d = _g e t b k c o l o r { ) ;
o l d p o s = _g ettextpos i t i on { ) ;
_c l ea r s c reen { _GC L EARSC R E E N ) ;
I * F i r s t t i me n o b l i n k , s econd t i me b l i n k i n g . * /
fo r { b l i n k = 0 ; bl i n k < = 1 6 ; b l i n k += 1 6 )
(
I * Loop t h ro u g h 8 b a c k g round c o l o r s . * /
for { bgd = 0 ; b g d < 8 ; bgd++ )
(
_s e t b k c o l o r { bgd ) ;
_s ettextpos i t i on { { s h o r t ) bgd + { { b l i n k I 1 6 ) * 9 ) + 3 , 1 ) ;
_s e t t e x t c o l o r { 7 ) ;
s p r i n t f C buffe r , " Ba c k : %d F o re : " , bgd ) ;
_ou t t e x t { buffer ) ;
_settextcolor 670
I
getch ( ) ;
#include <grapb.h>
R1malkl The _settextcursor function sets the cursor attribute (i.e., the shape) to the value specified
by anr. The high-order byte of attr detennines the top line of the cursor within the charac
ter cell. The low-order byte of attr detennines the bottom line of the cursor.
The _settextcursor function uses the same fonnat as the BIOS routines in setting the cur
sor. Typical values for the cursor attribute are listed below:
Ox.0707 Underline
Ox2000 No cursor
RBtum Vala• The function returns the previous cursor attribute, or -1 if an error occurs (such as calling
the function in a graphics screen mode).
I * D I S C U RS . C : T h i s p r o g r a m c h a n g e s t h e c u r s o r s h a pe u s i n g _gettext c u r s o r
* a n d _settext c u r s o r , a nd h i des t h e c u r s o r u s i n g _d i s p l a y c u r s o r .
*I
v o i d ma i n ( >
(
s ho r t o l d c u r s o r ;
s h o r t n ewc u r s or = 0x007 ; / * Ful l bl o c k c u r s o r * /
I * S a v e o l d c u r s o r s h a p e a nd ma k e s u re c u r s o r i s on . * /
ol dcursor = _get t e x t c u r s o r ( } ;
_c l ea r s c reen ( _GC L EARSC R E E N } ;
_d i s p l ay c u rs o r ( _GC U RSORO N } ;
_o ut t e x t < " \ nO l d c u r s o r s h a pe : " ) ;
getch ( l ;
I * C h a n g e c u r s o r s h a pe . * /
_out t ex t ( " \ n N ew c u r s o r s h a pe : " l ;
_s e t t ex t c u r s o r ( n ewc u r s o r } ;
getch ( ) ;
/ * Re s t o r e o r i g i n a l c u r s o r s h a p e . * /
_ou t t ex t ( " \ n " ) ;
_s e t t ex t c u r s o r ( o l d c u r s o r ) ;
673 _settextposition
#include <graph.h>
Remadts The _settextposition function sets the current text position to the display point
(row, column). The outtext and outmem functions (and standard console 1/0 routines,
such as printf) output text at that point.
Element Description
short row Row coordinate
short col Column coordinate
Return Value The function returns the previous text position in an rccoord structure, defined in
GRAPH.ff.
c h a r bu ffe r ( 80 ] :
v o i d ma i n ( )
(
_settextposition 114
I* S a v e o r i g i n a l f o r e g r o u n d , b a c kg r o u n d , a nd t e x t p o s i t i o n */
s h o r t b l i n k , fgd , o l d fgd ;
l ong bgd , o l d b g d ;
s t r u c t r c c o o rd· o l d p o s ;
I * S a v e o r i g i n a l f o r e g r o u n d , b a c k g ro u n d , a nd text p o s i t i on . */
o l d f g d a _g e t tex t c o l o r ( ) ;
o l d b g d = _g e t b k c o l o r C > ;
o l d p o s m _g e t t e x t p o s i t i on ( ) ;
_c l e a r s c r e e n ( _GC LEARSC R E E N ) ;
I * Fi r s t t i me n o b l i n k , s e c o n d t i me b l i n k i n g . */
f o r e b l i n k = 0 ; b l i n k <- 1 6 ; b l i n k +- 1 6 >
I
I * Loop t h r o u g h 8 b a c kg ro u n d c o l o r s . */
fo r ( b g d = 0 ; b g d < 8 ; bgd++ >
(
_s e t b k c o l o r C bgd ) ;
_s e t t e x t p o s i t i on C C s h o r t ) bg d + ( ( b l i n k I 1 6 ) * 9) + 3 , 1 >:
_s e t t e x t c o l o r C 7 > ;
s p r i n t f C b u f fe r , " B a c k : Sd F o r e : • , bgd > :
_o u t t ex t C b u f f e r ) ;
/ * Loop t h ro u g h 1 6 f o r e g r o u n d c o l o r s . */
f o r ( f g d = 0 ; f g d < 1 6 ; f gd++ >
(
_s e t t e x t c o l o r C fgd + b l i n k > :
s p r i n t f ( b u f f e r , • S 2 d • , fg d + b l i n k > :
_o u t t e x t ( b u f f e r ) ;
)
getc h C ) ;
I * R e s t o r e o r i g i n a l f o r e g r o u n d , b a c k g ro u n d , a n d t e x t po s i t i on . */
_s e t t e x t c o l o r ( o l d f g d ) ;
_s e t b k c o l o r ( o l d b g d ) ;
_c l e a r s c r e e n C _GC L EA R S C R E E N ) ;
_s e t t e x t p o s i t i on C o l d p o s . row , o l d p o s . c o l ) ;
675 _settextrows
#include <graph.h>
The _settextrows function specifies the number of screen rows to be used in text modes.
If the constant MAXTEXTROWS is specified for the rows argument, the function
_
will choose the maximum number of rows available. In text modes, this is 50 rows on
VGA, 43 on EGA, and 25 on others. In graphics modes that support 30 or 60 rows,
_MAXTEXTROWS specifies 60 rows.
Rstum Value This function returns the numbers of rows set. The function returns 0 if an error occurred.
#i n c l u d e < g r a p h . h>
#i n c l u d e < s t d l i b . h>
v o i d ma i n ( i n t a rg c , c h a r **a rgv )
(
s h o r t rows ;
i f ( ! C rows = a t o i C a rg v [ l ] ) ) >
(
_outtext < " \ nSyn t a x : STXTROWS [ 25 I 43 I 50 J \ n " ) ;
exi t < 1 ) ;
_settextrows 676
#include <graph.h>
Remades The _settextwindow function specifies a window in row and column coordinates where
all text output to the screen is displayed. The arguments (r1, cl) specify the upper-left
comer of the text window, and the arguments (r2, c2) specify the lower-right comer of the
text window.
Text is output from the top of the text window down. When the text window is full, the
uppermost line scrolls up out of it.
Note that this function does not affect the output of presentation-graphics text (e.g., labels,
axis marks, etc.). It also does not affect the output of the font display routine _outgtext
Use the _setviewport function to control the display area for presentation graphics or
fonts.
•
setvbuf 678
#include <Stdio.h>
int setvbuf( FILE *stream, char *buffer, int mode, size_t size );
Remarks The setvbuf function allows the program to control both buffering and buffer size for
stream. The stream must refer to an open file that has not been read from or written to
since it was opened. The array pointed to by buffer is used as the buffer, unless it is NULL,
and an automatically allocated buffer size bytes long is used.
is used as the size of the buffer. If mode iS _IONBF, the stream is unbuffered and size and
The mode must be IOFBF, IOLBF, or IONBF. If mode is IOFBF or IOLBF, then size
Type Meaning
_IOFBF Full buffering; that is, buffer is used as the buffer and size is
used as the size of the buffer. If buffer is NULL, an automat
ically allocated buffer size bytes long is used.
The legal values for size are greater than 0 and less than 32,768.
Return Value The return value for setvbuf is 0 if successful, and a nonzero value if an illegal type or
buffer size is specified.
619 setvbuf
voi d ma i n ( )
(
c h a r b u f [ 1024 J ;
F I L E * s t r e a m l , *st ream2 ;
Output
#include <graph.h>
R1matks The _setvideomode function selects a screen mode appropriate for a particular hard-
ware/display configuration. The mode argument can be one of the manifest constants
shown in Table R.9 and defined in GRAPH.ff.
D FAULTMODE
_ E Hardware default
mode
A
_M XRESMO E D Highest resolution
in graphics mode
A
_M XCOLORMO E D M aximum colors
in graphics mode
T
_ EXT W 0B 4 Mrr 40 x 25 16 eGA
X B
_TEXTC40 err 40 x 25 16 eGA
_TE T W80 Mrr 80 x 25 16 eGA
MRES4COLOR
_TEXTC80 err 80 x 25 6 eGA
_MRESNOCOLOR
_ C/G 3 20 x 200 4 eGA
MIG 320 x 200 4 CGA
T XT
_HRESBW MIG 640 x 200 2 eGA
_ E MONO Mrr 80 x 25 MDPA
5
_HERCMON0 Hercules graphics 720 x 348 HGe
_MRES16COLOR e/G 320 x 200 16 EGA
_HRES16COLOR e/G 640 x 200 16 EGA
_ERESNOCOLOR Mrr 640 x 350 EGA
_ERESCOLOR C/G 640 x 350 16 EGA
681 _setvideomode
1. M indicates monochrome, C indicates color output, T indicates text, and G indicates graphics generation.
2. For texl modes , size is given in characters (columns
·
x rows). For graphics modes, size is given in pixels
(horizonlal x vertical).
3. For monochrome displays, lhe number of colors is lhe number of gray shades.
4. Adapters are lhe IBM (and compatible) Monochrome Adapter (MDPA), Color Graphics Adapter (CGA),
Enhanced Graphics Adapter (EGA), Video Graphics Array (VGA), Hercules-compatible adapter (HGC), and
Olivelli-compatible adapter (OLIV).
5. ln _HERCMONO mode, lhe texl dimensions are 80 columns by 25 rows, wilh a 9 by 14 characler box. The
bottom IWo scan lines of row 25 are nol visible.
Note that only standard hardware is described here, but display hardware that is strictly
compatible with IBM, Hercules, or Olivetti hardware should also work as described.
_MAXRESMODE and The two special modes _MAXRESMODE and _MAXCOLORMODE select the highest reso
_MAXCOLORMODE
lution or greatest number of colors available with the current hardware, respectively.
These two modes fail for adapters that do not support graphics modes.
Table R. 1 0 lists the video mode selected for different adapter and monitor combinations
when _MAXRESMODE or _MAXCOLORMODE is specified:
* Color monitor is assumed if the start-up text mode was TEXTC80 or TEXTC40 or if the start-up mode
was graphics mode. Composite or other noncolor CGA monitor is assumed if start-up mode was TEXTBW80 or
TEXTBW40.
Hercules Support You must install the Hercules driver MSHERC.COM before running your program. Type
MSHERC to load the driver. This can be done from an AUTOEXEC.BAT file.
If you have both a Hercules monochrome card and a color video card, you should install
MSHERC.COM with the /H (/HALF) option. The /H option causes the driver to use one
instead of two graphics pages. This prevents the two video cards from attempting to use
the same memory. You do not have to use the /H option if you have only a Hercules card.
See your Hercules hardware manuals for more details of compatibility.
To use a mouse, you must follow special instructions for Hercules cards in Microsoft
Mouse Programmer's Reference Guide. (This is sold separately; it is not supplied with
either Microsoft C or the mouse package.)
Return Value The function returns the number of text rows if the function is successful. If an error is en
countered (that is, the mode selected is not supported by the current hardware configura
tion), the function returns 0.
Exampm --
----�
#i n c l u d e < g r a p h . h >
#i n c l u d e < s t d l i b . h >
#i n c l ude < s t r i n g . h >
v o i d e r ro r ( c h a r *ms g ) ;
v o i d ma i n ( i n t a rg c , c h a r *a rgv [ ]
{
s h o r t i , n u m = s i z e o f ( modes ) I s i zeof C s h o rt ) ;
s t ruct v i deoconfi g vc ;
i f ( a rg c < 2 )
e r r o r ( " N o a rg ument g i ven " > :
)
e r r o r ( " I n v a l i d mode s t r i n g " ) ;
v o i d e r ro r ( c h a r *ms g
[
_ou t t ex t C m s g ) ;
ex i t C 1 ) ;
_setvideomoderows 684
Description Sets the video mode and number of text rows for text modes.
#include <graph.h>
Remarks The _setvideomoderows function selects a screen mode for a particular hardware/display
combination. The manifest constants for the screen mode are given in the reference pages
for _setvideomode. The _setvideomoderows function also specifies the number of text
rows to be used in a text mode. If the constant _M AXTEXTROWS is specified for the rows
argument, the function will choose the maximum number of rows available. In text modes,
this is 50 rows on VGA, 43 on EGA, and 25 on others. In graphics modes that support 30
or 60 rows, _MAXTEXTROWS specifies 60 rows.
Return Value The setvideomoderows function returns the numbers of rows set. The function returns 0 if
an error occurred (e.g., if the mode is not supported).
Exampre ������
I * S V M ROWS . C * /
#i n c l u d e < s t d l i b . h >
#i n c l ude < c o n i o . h >
#i n c l ude < g r a p h . h >
v o i d ma i n ( )
(
s t r u c t v i deocon f i g c o n f i g ;
685 _setvideomoderows
I * Set 4 3 - l i n e g r a p h i c s mode i f a v a i l a b l e . * /
i f ( ! _s et v i d eomod e r ow s C _ERESCOLO R , 43 > >
{
_o uttext ( " EGA o r V GA requ i red " ) ;
exi t ( 1 ) ;
)
_get v i d eo c on f i g ( & c o n f i g ) ;
I * Set l og i c a l o r i g i n t o c e n t e r � nd d ra w a rect a ng l e . * /
_s et l o g o r g ( c o n f i g . n umxp i xel s I 2 - 1 , c o n f i g . n umy p i x e l s I 2 - 1 ) ;
_rect a n g l e ( _GBORD E R , - 80 , - 50 , 80 , 50 ) ;
getch ( ) ;
_s e t v i d eomod e ( _D E FAU LTMOD E ) ;
· _setvieworg 686
#include <graph.h>
Remarks The _setvieworg function moves the view-coordinate origin (0, 0) to the physical point
(x, y). All other view-coordinate points move the same direction and distance.
Element Description
Return Value The function returns the physical coordinates of the previous view origin in an xycoord
structure, defined in GRAPH.H.
/ * S V O RG . C : T h i s p r o g r a m s et s t h e v i ew o r 1 g 1 n t o t h e c e n t e r of
* the s c reen , then d r aws a rect a n g l e u s i n g the n ew o r i g i n .
*I
v o i d ma i n ( )
{
s t r u c t v i deocon f i g c o n f i g ;
687 _setvieworg �
I * F i n d a v a l i d g r a p h i c s mode . * I
i f ( ! _set v i d e omod e ( _MA X RESMO D E )
exi t ( 1 > :
_g et v i d e o c o n f i g ( & c o n f i g ) ;
I * Set v i ew o r i g i n t o t h e c e n t e r of t h e s c reen . * /
_s et v i eworg ( c o n f i g . n umxp i x e l s I 2 , c o n f i g . n umy p i xel s I 2 ) ;
_rec t a n g l e ( _GBO R D E R , -80 , - 50 , 80 , 50 ) ;
getc h ( > ;
_s e t v i deomod e ( _D E FAU LTMOD E ) ;
_setviewport 688
#include <graph.h>
void _far _setviewport( short xl, short yl, short x2, short y2 );
Remarks The _setviewport function redefines the graphics viewport. The _setviewport function
defines a clipping region in exactly the same manner as _setcliprgn, and then sets the
view-coordinate origin to the upper-left comer of the region. The physical points (xl, yl)
and (x2, y2) are the diagonally opposed corners of the rectangular clipping region. Any
window transformation done with the _setwindow function applies only to the viewport
and not to the entire screen.
#i n c l u d e < c on i o . h >
#i n c l u d e < s t d l i b . h>
#i n c l u d e < g r a p h . h >
v o i d ma i n ( )
(
/ * Fi nd a v a l i d g ra p h i c s mod e . * /
i f ( ! _s e t v i deomod e ( _MAX RESMODE )
exi t ( 1 ) ;
get c h C l ;
_s e t v i deomod e C _ D E FAU LTM O D E l ;
_setvisua/page 690
#include <graph.h>
Remarks For hardware configurations that have an EGA or a VGA and enough memory to support
multiple-screen pages, the _setvisualpage function selects the current visual page. The
page argument specifies the current visual page. The default page number is 0.
Return Value The function returns the number of the previous visual page. If the function fails, it returns
a negative value.
#include <graph.h>
short _far _setwindow( shortfinvert, double wxl, double wyl, double wx2,
double wy2 );
Remarks The _setwindow function defines a window bounded by the specified coordinates. The
arguments (wxl, wyl) specify the upper-left comer of the window, and the arguments
(wx2, wy2) specify the lower-right comer of the window.
The finvert argument specifies the direction of the coordinates. lfjinvert is TRUE, the
y axis increases from the screen bottom to the screen top (Cartesian coordinates). If
finvert is FALSE, the y axis increases from the screen top to the screen bottom (screen
coordinates).
Any window transformation done with the _setwindow function applies only to the view
port and not to the entire screen.
lf wxl equals wx2 or wyl equals wy2, the function will fail.
Note that this function does not affect the output of presentation-graphics text (e.g., labels,
axis marks, etc.). It also does not affect the output of the font display routine _outgtext.
Return Value The function returns a nonzero value if successful. If the function fails (e.g., if it is not in a
graphics mode), it returns 0.
e n um boo l e a n ( FA L S E , T R U E l :
enum d i s p l ay ( MOV E , D RAW , E RA S E l :
v o i d ma i n ( )
(
s t ru c t xy coord v i ew , phys ;
s t r u c t _wxy coord o l dwi n , newwi n ;
s t r u c t v i d e o c on f i g v c :
d o u b l e x u n i t , y u n i t , x i nc , y i n c :
s h ort c o l o r , k ey , f i n t e r s e c t = FA LS E , fd i s p l ay = T RU E ;
I * F i n d a v a l i d g r a p h i c s mod e . * /
i f ( ! _s e t v i deomod e C _MA X R E SM O D E ) l
exi t ( 1 ) :
_g et v i d eo c o n f i g ( & v c ) ;
I * C a l c u l a t e t h e s i ze of o n e p i x e l i n wi n d ow coord i n a t e s .
* T h e n get t h e c u r r ent w i ndow c o o rd i n a t e s a n d c o l o r .
*/
o l dwi n = _g etwi n d owcoord C 1 , 1 > :
n eww i n = _g etw i n d owcoord ( 2 , 2 > :
x u n i t = x i n c = n eww i n . wx - o l dwi n . wx :
yuni t • y i n c = n ewwi n . wy - o l dwi n . wy ;
n eww i n = o l dwi n = _g e t c u r re n t po s i t i on_w ( ) ;
c o l o r = _g e t c o l o r C > :
whi l e ( 1 )
(
/ * Set f l a g a c c o rd i n g to w h e t h e r c u r r e n t pi xel i s on , t h en
* t u rn p i x e l on .
*/
i f ( _g et p i x e l _w c o l dwi n . wx , o l dwi n . wy ) == c o l o r )
fi n t e r s e c t = T RU E :
el s e
f i n t e r s e c t = FALS E :
_s e t c o l o r C c o l o r > :
_s etp i x e l _w ( o l dwi n . wx , o l dwi n . wy > :
Bsa _setwindaw
I * Get a n d t e s t key . * /
k ey = getc h ( ) ;
swi tc h ( k ey >
(
case 27 : / * ESC Q u i t */
_s et v i d eomod e ( _D E FAU LTMOD E ) ;
exi t ( 0 > :
case 32 : / * S PAC E Move no col or */
fd i s p l a y = MO V E ;
cont i nue ;
case 0 : / * E x t e n d ed c o d e - get next * /
k ey = get c h ( > :
swi t c h ( key )
(
case 72 : I* U P -y *I
n eww i n . wy -= y i nc ;
b r ea k ;
case 77 : I * R I GHT +x *I
n ewwi n . wx += x i n c ;
b r ea k ;
c a s e 80 : I * DOWN +y *I
n eww i n . wy += y i n c ;
b rea k :
case 75: I * L E FT -x *I
n eww i n . wx - = x i n c ;
b r ea k ;
c a s e 82 : I* INS D r a w whi te *I
fdi s p l a y = D RAW ;
con t i n u e ;
c a s e 83 : I* DEL D r a w bl a c k *I
fdi s p l ay = E RAS E ;
con t i n u e ;
brea k ;
I * T r a n s l a t e wi ndow c o o rd i n a t e s t o v i ew , v i ew t o p hy s i c a l .
* T h e n c h e c k p hy s i c a l to ma k e s u re we ' re on s c reen . U p d a t e s c reen
* a nd po s i t i on i f we a r e . I gn o r e if not .
*I
v i ew = _g e t v i ewc oo rd_wxy ( &n ewwi n ) ;
phys = _g e t p hy s c o o rd ( v i ew . x c o o rd , v i ew . y c o o rd > :
i f ( C p hys . x c o o rd >= 0 ) && C p hys . xcoord < v c . n umx p i x e l s ) &&
C p hys . y coo rd >= 0 ) && C p hys . ycoord < v c . n umy p i x e l s ) )
_setwindow 694
I * I f d i s p l a y o n , d ra w t o n ew po s i t i on , e l s e move t o new . * /
i f ( f d i s p l a y ! = MOV E )
(
i f ( f d i s p l a y � E RA S E )
_s e t c o l o r C 0 ) ;
_l i n e t o_w c n ewwi n . wx , n ewwi n . wy ) ;
el se
{
_s e t c o l o r ( 0 ) ;
_mo v e t o_w C n eww i n . wx , n eww i n . wy ) ;
I * I f t h e r e w a s n o i nt e r s e c t , e ra s e ol d p i x e l . * /
i f C ! f i n t e r s ect )
_s e t p i x e l _w C o l dwi n . wx , o l dwi n . wy ) ;
)
o l dwi n = n eww i n ;
)
el se
n eww i n = o l dwi n ;
695 _setwritemode
#include <graph.h>
Remarks The _setwritemode function sets the current logical write mode, which is used when draw
ing lines with the _lineto and _rectangle functions.
The action argument defines the write mode. The possible values are _GAND, _GOR,
_GPRESET, GPSET, and _GXOR. See the description of the _putimage function for
_
Return Value The _setwritemode function returns the previous write mode, or -1 if an error occurs.
#include <Signal.h>
void ( *signal( int sig, void( *June )( int sig [, int subcode ] ) ) ) ( int sig );
Remarks The signal function allows a process to choose one of several ways to handle an interrupt
signal from the operating system.
The sig argument must be one of the manifest constants described in Table R. 1 1 and de
fined in SIGNAL.ff.
SIGUSRl, SIGUSR2, and SIGUSRJ are user-defined signals which can be sent by means of•
DosFlagProcess. For details, see Microsoft Operating System/2 Programmer's Reference.
697 signal
Note that SIGILL, SIGSEGV, and SIGTERM are not generated under DOS and SIGSEGV
is not generated under OS/2. They are included for ANSI compatibility. Thus, you may set
signal handlers for these signals via signal, and you may also explicitly generate these sig
nals by calling raise.
Note also that signal settings are not preserved in child processes created by calls to exec
or spawn. The signal settings are reset to the default in the child process.
The action taken when the interrupt signal is received depends on the value ofjunc. The
June argument must be either a function address or one of the manifest constants defined in
SIGNAL.ff and listed below:
Value Meaning
SIG_ACK Acknowledges receipt of a signal (OS/2 only). This constant
is valid only if a user-defined signal handler is installed. Once
a process receives a given signal, the operating system does
not send any more signals of this type until it receives a
SIG_ACK acknowledgment from the process. The operating
system does not queue up signals of a given type; therefore, if
more than one signal of a given type accumulates before the
process returns a SIG_ACK value, only the most recent signal
is sent to the process after the SIG_ACK value is received by
the operating system. This option has no effect on which han
dler is installed for a given signal. The manifest constant
SIG_ACK is not supported for SIGFPE signals.
Function address Installs the specified function as the handler for the given
signal.
For SIGFPE, the function pointed to by June is passed two arguments, SIGFPE and an
integer error subcode, FPE_xu; then the function is executed. (See the include file
FLOAT.ff for definitions of the FPE_xu subcodes.) The value ofJune is not reset upon re
ceiving the signal. To recover from floating-point exceptions, use setjmp in conjunction
with longimp. (See the example under _fpreset.) If the function returns, the calling
process resumes execution with the floating-point state of the process left undefined.
If the function returns, the calling process resumes execution immediately following the
point at which it received the interrupt signal. This is true regardless of the type of signal
or operating mode.
Before the specified function is executed under DOS versions 3.x or earlier, the value
ofjunc is set to SIG_DFL. The next interrupt signal is treated as described above for
SIG_DFL, unless an intervening call to signal specifies otherwise. This allows the program
to reset signals in the called function.
Under OS/2, the signal handler is not reset to the system-default response. Instead, no sig
nals of a given type are received by a process until the process sends a SIG_ACK value to
the operating system. The program can restore the system-default response from the han
dler by first sending SIG_DFL and then sending SIG_ACK to the operating system.
Since signal-handler routines are normally called asynchronously when an interrupt oc
curs, it is possible that your signal-handler function will get control when a C run-time
operation is incomplete and in an unknown state. Certain restrictions therefore apply to the
C functions that can be used in your signal-handler routine:
1 . Do not issue low-level or standard input and output routines (e.g., printf, read, write,
and fread) .
2. Do not call heap routines or any routine that uses the heap routines (e.g., malloc,
strdup, putenv).
3. Do not use any C function that generates a system call (e.g., getcwd, time).
699 signal
4. Do not use the longjmp function unless the interrupt is caused by a floating-point ex
ception (i.e., sig is SIGFPE). In this case, the program should first reinitialize the
floating-point package by means of a call to _fpreset.
Return Value The signal function returns the previous value offunc associated with the given signal. For
example, if the previous value offunc was SIG_IGN, the return value will be SIG_IGN.
The one exception to this rule is SIG_ACK, which returns the address of the currently in
stalled handler.
A return value of -1 indicates an error, and ermo is set to EINVAL. The possible error
causes are an invalid sig value, an invalidfunc value (that is, a value that is less than
SIG_ACK but not defined), or afunc value of SIG_ACK used when no handler is currently
installed.
See Also abort, exec functions, exit, _exit, _fpreset, spawn functions
#i n c l u d e < s t d i o . h >
Iii n c l u d e < c on i o . h >
#i n c l u d e < s i g n a l . h >
#i n c l u d e < p r o c e s s . h >
#i n c l u d e < s t d l i b . h >
#i f d ef i ned ( OS2 )
#d e f i ne I N C L_NOCOMMON
#d e f i ne I N C L_NO P M
#d e f i n e I N C L_V I O
#d e f i ne I N C L_KBD
/Fi n c l u d e < o s 2 . h >
#i n c l u d e < s t r i n g . h >
Itel s e
/Fi n c l u d e < d o s . h >
#i n c l ude < b i o s . h >
lfoen d i f
signal 700
v o i d ma i n ( }
(
i nt c h ;
I * M o d i fy CTRL+C b e ha v i o r . * /
i f ( s i g n a l ( S I G I NT , c t r l c h a n d l e r }
= S I G_ERR }
(
fp r i n t f ( s t d e r r , " C oul d n ' t s e t S I G I NT \ n " } ;
a b o rt ( } ;
I * I n p u t l oop i l l u s t r a t e s r e s u l t s . * /
do
(
c h = getch C } ;
i f ( c h == 0 >
(
c h = getc h C } ;
i f ( c h == 4 6 } / * T r e a t A LT+C l i k e C T R L+C * /
r a i s e c S I G I NT } ;
el se
p r i n t f ( " Ex t e n ded c o d e : % X \ n " , c h } ;
el se
p r i n t f ( " A SC I I code : % X \ n " , c h } ;
whi l e ( c h ! = 27 } ; / * ESC c o d e * I
I * H a n d l e s S I G I NT C CT R L+C } i n t e r r upt . * /
voi d ctrl chandl er( }
(
i nt c ;
char str[J = • " ;
I * D i s a l l ow CTRL+C d u r i ng h a n d l e r . * /
s i g n a l ( S I G I NT , S I G_I G N } ;
s a feout ( " U s e r b r e a k - a bo r t p r o c es s i n g ? • } ;
c = s a fe i n ( } ;
str[0J = c :
s a feout < s t r } ;
a bo rt ( } ;
el se
101 signal
I * O u t p u t s a s t r i n g u s i n g s y s t em l ev e l c a l l s . * /
v o i d s a feou t C c h a r * s t r )
{
#i f d e f i ned ( OS2 )
V i oWrtTTY C s t r , s t r l en C s t r ) , 0 ) ;
I/e l s e
u n i on REGS i n regs , o u t regs ;
i n regs . h . a h = 0x0e ;
whi 1 e C *str )
{
i n re g s . h . a l = * s t r++ ;
i n t86 C 0 x l 0 , & i n re g s , & o u t r e g s ) ;
)
llen d i f
)
I * I n p u t s a c h a r a c t e r u s i n g s y s t em l ev e l c a l l s . * /
i nt s a f e i n ( )
{
#i f d ef i ned ( OS2 )
K B D K E Y I N FO k k i ;
Output
ASC I I code : 7 4
ASC I I c o d e : 68
ASC I I code : 65
"C
U s e r b rea k - a bo r t p r o c e s s i n g ? n
18
ASC I I code : 6 2
ASC I I code :
sin Functions 702
#include <math.h>
x Angle in radians
Rematks The sin and sinh functions find the sine and hyperbolic sine of x, respectively. The sinl
and sinhl functions are the 80-bit counterparts and use an 80-bit, 1 0-byte coprocessor form
of arguments and return values. See the reference page on the long double functions for
more details on this data type.
Return Value The sin functions return the sine of x. If x is large, a partial loss of significance in the result
may occur, and sin generates a PLOSS error. If x is so large that significance is completely
lost, the sin function prints a TLOSS message to stderr and returns 0. In both cases, errno
is set to ERANGE.
The sinh function returns the hyperbolic sine of x. If the result is too large, sinh sets ermo
to ERANGE and returns ±HUGE_VAL.
sin1, sinhl
See Also ac� functions, asin functions, atan functions, cos functions, tan functions
I * S I N C O S . C : T h i s p r o g r a m d i s p l ay s t h e s i n e , hy p erbol i c s i n e , c o s i n e ,
* a nd hy p e r b o l i c c o s i n e of p i I 2 .
*I
703 sin Functions
v o i d ma i n ( )
(
d o u b l e pi = 3 . 1 4 1 5 9 2 6 5 3 5 ;
doubl e x , y ;
x = pi I 2 ;
y = si n ( x > :
p r i n t f ( " s i n ( %f ) = % f \ n " , x , y >:
y = sinhC x > :
p r i n t f ( " s i n h ( %f ) = % f \ n " , x , y >:
Y = C OS ( X ) ;
p r i n t f C " c o s ( %f > = % f \ n " , x , y >:
y = c os h C x > :
p r i n t f ( " c os h ( %f ) = %f\ n " , x , y >:
Output
s i n ( 1 . 570796 ) =1 . 000000
s i nh ( 1 . 570796 ) =2 . 30 1 2 9 9
C O S ( 1 . 5 7 0 7 9 6 ) = 0 . 000000
c os h ( 1 . 5 7 0 7 9 6 > = 2 . 509 1 7 8
sopen 704
#include <fcntl.h>
#include <Sys\types.h>
#include <Sys\stat.h>
#include <Sbare.h>
#include <io.h> Required only for function declarations
int sopen( char *filename, int oflag, int shflag [, int pmode D );
Remarks The sopen function opens the file specified by filename and prepares the file for sub
sequent shared reading or writing, as defined by oflag and shflag. The integer expression
oflag is fonned by combining one or more of the following manifest constants, defined in
the file FCNTL.H. When two or more constants are used to fonn the argument oflag, the
constants are combined with the OR operator ( I ).
Constant Meaning
O_APPEND Repositions the file pointer to the end of the file before every
write operation.
O_BINARY Opens file in binary (untranslated) mode. (See fopen for a de
scription of binary mode.)
O_CREAT Creates and opens a new file. This has no effect if the file
specified by filename exists.
O_EXCL Returns an error v alue if the file specified by filename exists.
This applies only when used with O_CREAT.
O_RDONLY Opens file for reading only. If this flag is given, neither the
O_RDWR flag nor the O_WRONLY flag can be given.
O_RDWR Opens file for both reading and writing. If this flag is given,
neither 0_RDONLY nor O_WRONLY can be given.
705 sopen
O_TEXT Opens file in text (translated) mode. (See fopen for a descrip
tion of text mode.)
O_TRUNC Opens and truncates an existing file to 0 bytes. The file must
have write pennission; the contents of the file are destroyed.
O_WRONLY Opens file for writing only. If this flag is given, neither
0_RDONLY nor 0_RDWR can be given.
The argument shflag is a constant expression consisting of one of the following manifest
constants, defined in SHARE.ff. If SHARE.COM (or SHARE.EXE for some versions of
DOS) is not installed, DOS ignores the sharing mode. (See your system documentation for
detailed infonnation about sharing modes.)
Constant Meaning
The sopen function should be used only under OS/2 and DOS versions 3.0 and later.
Under earlier versions of DOS, the shflag argument is ignored.
The pmode argument is required only when o_CREAT is specified. If the file does not
exist, pmode specifies the file's pennission settings, which are set when the new file is
closed for the first time. Otherwise, the pmode argument is ignored. The pmode argument
is an integer expression that contains one or both of the manifest constants S_IWRITE and
S_IREAD, defined in SYS\STAT.H. When both constants are given, they are combined
with the OR operator ( I ). The meaning of the pmode argument is as follows:
Value Meaning
If write pennission is not given, the file is read-only. Under DOS and OS/2, all files are
readable; it is not possible to give write-only pennission. Thus, the modes S_IWRITE and
S_IREAD I S_IWRITE are equivalent.
sopen 706
Note that under DOS versions 3.x with SHARE installed, a problem occurs when opening
a new file with sopen under the following sets of conditions:
• With oflag set to any combination that includes O_CREAT I O_RDWR, pmode set to
S_IREAD, and shflag set to anything other than SH_COMPAT.
In either case, the operating system will prematurely close the file during system calls
made within sopen, or the system will generate a sharing violation (INT 24H). To avoid
the problem, open the file with pmode set to S_IWRITE. After closing the file, call chmod
set to S_IREAD, oflag set to O_CREAT I O_RDWR, and shflag set to SH_COMPAT.
and change the mode back to S_IREAD. Another solution is to open the file with pmode
Retum Value The sopen function returns a file handle for the opened file. A return value of -1 indicates
an error, and errno is set to one of the following values:
Value Meaning
EEXIST The o_CREAT and o_EXCL flags are specified, but the
named file already exists.
#include <Stdio.h>
#include <process.h>
int spawnl( int mode, char *cmdname, char •argO, char *argl, ... char •argn, NULL );
int spawnle( int mode, char *cmdname, char *argO, char *argl , ... char *argn, NULL,
char **envp ) ;
int spawnlp( int mode, char *cmdname, char *argO, char *argl, ... char *argn, NULL );
int spawnlpe( int mode, char *cmdname, char *argO, char *argl, ... char *argn, NULL,
char **envp );
. int spawnv( int mode, char *cmdname, char **argv );
int spawnve( int mode, char *cmdname, char **argv, char **envp ) ;
int spawnvp( int mode, char *cmdname, char **argv );
int spawnvpe( int mode, char *cmdname, char **argv, char **envp );
Remalks The spawn family of functions creates and executes a new child process. Enough memory
must be available for loading and executing the child process. The mode argument deter
mines the action taken by the parent process before and during spawn. The following
values for mode are defined in PROCESS.ff:
Value Meaning
The cmdname argument specifies the file which will be executed as the child process, and
can specify a full path (from the root), a partial path (from the current working directory),
or just a file name. If cmdname does not have a file-name extension or does not end with a
period (.), the spawn function first tries the .COM extension, then the .EXE extension, and
finally the .BAT extension (or, in OS/2 protected mode, the .CMD extension). This ability
to spawn batch files is a new feature in Microsoft C version 6.0.
If cmdname has an extension, only that extension is used. If cmdname ends with a period,
the spawn calls search for cmdname with no extension. The spawnlp, spawnlpe,
spawnvp, and spawnvpe routines search for cmdname (using the same procedures) in the
directories specified by the PATH environment variable.
If cmdname contains a drive specifier or any slashes (i.e., if it is a relative path name), the
spawn call searches only for the specified file and no path searching is done.
Arguments are passed to the child process by giving one or more pointers to character
strings as arguments in the spawn call. These character strings form the argument list for
the child process. The combined length of the strings forming the argument list for the
child process must not exceed 128 bytes in real mode. The terminating null character ( '\0 ' )
for each string is not included in the count, but space characters (automatically inserted to
separate arguments) are included.
The argument pointers may be passed as separate arguments (spawnl, spawnle. spawnlp,
and spawnlpe) or a8 an array of pointers (spawnv, spawnve, spawnvp, and spawnvpe).
At least one argument, argO or argv[O], must be passed to the child process. By conven
tion, this argument is the name of the program as it might be typed on the command line
by the user. (A different value will not produce an error.) In real mode, the argv[O] value is
supplied by the operating system and is the fully qualified path name of the executing pro
gram . In protected mode, it is usually the program name as it would be typed on the com
mand line.
709 spawn Functions
The spawnl. spawnle. spawnlp, and spawnlpe calls are typically used in cases where the
number of arguments is known in advance. The argO argument is usually a pointer to
cmdname. The arguments argl through argn are pointers to the character strings forming
the new argument list. Following argn, there must be a NULL pointer to mark the end of
the argument list.
The spawnv. spawnve. spawnvp, and spawnvpe calls are useful when the number of ar
guments to the child process is variable. Pointers to the arguments are passed as an array.
argv. The argument argv[O] is usually a pointer to a path name in real mode or to the pro
gram name in protected mode, and argv[ I ] through argv[n] are pointers to the character
strings forming the new argument list. The argument argv[n+l] must be a NULL pointer to
mark the end of the argument list.
Files that are open when a spawn call is made remain open in the child process. In the
spawnl, spawnlp, spawnv. and spawnvp calls, the child process inherits the environment
of the parent. The spawnle. spawnlpe, spawnve, and spawnvpe calls allow the user to
alter the environment for the child process by passing a list of environment settings
through the envp argument. The argument envp is an array of character pointers, each ele
ment of which (except for the final element) points to a null-terminated string defining an
environment variable. Such a string usually has the form
NAME=value
where NAME is the name of an environment variable and value is the string value to which
that variable is set. (Note that value is not enclosed in double quotation marks.) The final
element of the envp array should be NULL. When envp itself is NULL, the child process in
herits the environment settings of the parent process.
The spawn functions can pass the child process all information about open files, including
the translation mode, through the C_FILE_INFO entry in the environment that is passed in
real mode (_C_FILE_INFO in protected mode).
The C start-up code normally processes this entry and then deletes it from the environ
ment. However. if a spawn function spawns a non-C process (such as CMD.EXE). this
entry remains in the environment. Printing the environment shows graphics characters in
the definition string for this entry, since the environment information is passed in binary
form in real mode. It should not have any other effect on normal operations. In protected
mode, the environment information is passed in text form and therefore contains no
graphics characters.
You must explicitly flush (using mush or flushall) or close any stream prior to the spawn
function call.
spawn Functions 710
Starting with Microsoft C version 6.0, you can control whether or not the open file infor
mation of a process will be passed to its child processes. The external variable _fileinfo
(declared in STDLIB.H) controls the passing of C_FILE_INFO information. If _fileinfo is
0, the C_FILE_INFO information is not passed to the child processes. If _rdeinfo is not 0,
C_FILE_INFO is passed to child processes.
B y default, _fileinfo is 0 and thus the C_FILE_INFO information is not passed to child
processes. There are two ways to modify the default value of _fileinfo:
• Link the supplied object file FILEINFO.OBJ into your program. Use the /NOE option
to avoid multiple symbol definitions.
• Set the _fileinfo variable to a nonzero value directly within your C program.
Retum Value The return value from a synchronous spawn (P_wAIT specified for mode) is the exit sta
tus of the child process. -
The return value from an asynchronous spawn (P_NOWAIT or P_NOWAITO specified for
mode) is the process ID. To obtain the exit code for a process spawned with P_NOWAIT,
you must call the wait or cwait function and specify the process ID. The exit code cannot
be obtained for'a process spawned with P_NOWAITO.
The exit status is 0 if the process terminated normally. The exit status can be set to a non
zero value if the child process specifically calls the exit routine with a nonzero argument.
If the child process did not explicitly set a positive exit status, a positive exit status indi
cates an abnormal exit with an abort or an interrupt. A return value of -1 indicates an
error (the child process is not started). In this case, errno is set to one of the following
values:
Value Meaning
E2BIG In DOS, the argument list exceeds 128 bytes, or the space
required for the environment information exceeds 32K. In
OS/2, the argument list and the space required for environ
ment information combined exceed 32K.
Note that signal settings are not preserved in child processes created by calls to spawn
routines. The signal settings are reset to the default in the child process.
71 1 spawn Functions
The spawn functions, with P_OVERLAY mode, will not work in OS/2 DOS
compatibility mode in programs which are bound with FAPI for dual-mode execution.
Programs linked as DOS mode .EXE files will work, and protected-mode programs will
work. The restriction applies only to bound programs in real mode.
In order to ensure proper overlay initialization and termination, do not use the setjmp or
longimp functions to enter or leave an overlay routine.
#i n c l u d e < s t d i o . h >
#i n c l ude < p r o c e s s . h >
c ha r *my_e n v [ ] =
(
" TH I S=en v i ronment w i l l b e " ,
" PASS ED=to c h i l d . ex e by t h e " ,
" S PAWN L E=a nd " ,
" S PAWN L P E=a nd " ,
" S PAWNV E=a nd " ,
" S PAWN V P Eafu n c t i on s " ,
NULL
};
v o i d ma i n ( i n t a rgc , c h a r * a rgv [ ] l
{
c h a r *a r g s [ 4 ] ;
i nt resul t ;
#include <Stdlib.h>
void _splitpath( char *path, char *drive, char *dir, char *fname, char *ext );
Rematltl The _splitpath routine breaks a full path name into its four components. The path argu
ment should point to a buffer containing the complete path name. The maximum size nec
essary for each buffer is specified by the manifest constants _MAX_DRIVE, _MAX_DIR,
_MAX_FNAME, and _MAX_EXT, defined in STDLIB.H. The other arguments point to the
buffers used to store the path-name elements:
Buff'er Description
drive Contains the drive letter followed by a colon (:) if a drive is
specified in path.
The return parameters will contain empty strings for any path-name components not found
in path.
Exampm ��������--
1 * MAK E PATH . C * /
#i n c l u d e < s t d l i b . h>
#i n c l ude < s t d i o . h >
v o i d ma i n ( )
(
c h a r p a t h_buffer [_MAX_PAT H J ;
c h a r d r i v e [_MAX_D R I V E J ;
c h a r d i r [_MAX_D I R] ;
c h a r fname [_MAX_FNAM E J ;
c h a r ext [_MAX_E X T ] ;
_ma kepa t h ( p a t h_b uff�r . • c • , " \ \ c 60\ \ c l i b r e f \ \ " , • ma kepa t h " , • c • > :
p r i nt f ( " P a t h c re a ted wi t h _ma kepa t h : %s \ n \ n " , p a t h_buffer > :
_s p l i tp a t h ( p a t h_buffe r , d r i v e , d i r , f n a me , ext > :
p r i n t f ( " Pa t h ext r a c t ed w i t h _s p l i t p a t h : \ n " ) ;
pri ntf ( • Dri v e : %s\n " , dri ve ) ;
pri ntf ( • Di r : % s \n " , di r > :
p r i n t f ( • Fi l e n a me : % s \ n " , f n a me > :
p r i n t f ( • Ext : % s \ n " , ext > :
Output
P a t h ext r a c t ed w i t h _s p l i tp a t h :
Dri ve : c :
D i r : \ c 60 \ c l i bref\
F i l e n a me : ma kepa t h
Ext : . c
715 sprinlf
#include <Stdio.h>
Remarks The sprintf function formats and stores a series of characters and v alues in buffer. Each
argument (if any) is converted and output according to the corresponding format specifica
tion in the format. The format consists of ordinary characters and has the same form and
function as the format argument for the printf function. (See printf for a description of the
format and arguments.) A null character is appended to the end of the characters written,
but is not counted in the return value.
Return Value The sprintf function returns the number of characters stored in buffer, not counting the
terminating null character.
I * S P R I NT F . C : T h i s p r o g r a m u s e s s p r i n t f to fo rma t v a r i o u s d a t a a n d
· * p l a c e t h em i n t h e s t r i n g n a med b u f fe r .
*I
v o i d ma i n ( )
(
c h a r b u f f e r [ 200 ] , s [ ] = • comp u t e r • , c = ' l ' :
i nt i = 35 , j :
f l o a t fp = 1 . 7 320534 :
sprintf 116
/ * Fo rma t a n d p r i n t v a r i ous d a t a : */
j = spri ntf ( buffe r , " \tStri ng : %s \ n " , s >:
j += s p r i n t f C buffer + j , " \tCha racter : %c \ n " , c l:
j += s p r i n t f ( buffer + j , " \t l ntege r : %d \ n R I i ):
j += s p r i n t f C buffe r + j , " \ t Rea l : %f\ n " , fp l :
Output
O u t pu t :
St r i n g : c omp u t e r
Cha racter : l
I nt e g e r : 35
Rea l : 1 . 732053
#include <math.h>
Remalb The sqrt functions calculate the square root of x. The sqrtl function is the 80-bit counter
part and uses an 80-bit, I 0-byte coprocessor fonn of arguments and return values.
Return Value The sqrt functions return the square-root result. If x is negative, the function prints a
DOMAIN error message to stderr, sets ermo to EDOM, and returns 0.
Error handling can be modified by using the matherr or _matherrl routine.
Examp• --
---
/ * SO RT . C : T h i s p r o g r a m c a l c u l a t e s a s q u a re root . * /
#i n c l ude <ma t h . h >
#i n c l u d e < s t d i o . h >
#i n c l ude < s t d l i b . h >
v o i d ma i n ( )
I
d o u b l e q u es t i on = 4 5 . 3 5 , a n swe r :
a n sw e r = s q rt ( q u es t i on ) ;
i f ( e rr n o == EDOM >
p r i n t f ( " Doma i n e r ro r \ n " > :
el s e
p r i n t f ( " T h e s q u a re root o f % . 2 f i s % . 2 f\ n " , q u e s t i on , a n swer > :
Output
T h e s q u a re root o f 4 5 . 3 5 i s 6 . 7 3
srand 718
Remarks The srand function sets the starting point for generating a series of pseudorandom in
tegers. To reinitialize the generator, use 1 as the seed argument. Any other value for seed
sets the generator to a random starting point.
The rand function is used to retrieve the pseudorandom numbers that are generated. Call
ing rand before any call to srand will generate the same sequence as calling srand with
seed passed as 1 .
Exampre __________________________________________________________________�
I * RAN D . C : T h i s p r o g r a m s e e d s t h e ra ndom n um b e r g e n e r a t o r w i t h t h e
* t i me , t h e n d i s p l a y s 20 r a n d om i n t e g e r s .
*I
#i n c l u d e < s t d l i b . h >
#i n c l ude < s t d i o . h >
#i n � l u d e < t i me . h >
v o i d ma i n ( )
(
i nt i ;
I * D i s p l a y 10 numbe r s . * /
fo r < i � 0 ; i < 1 0 ; i ++ >
p r i ntf ( • %6d \ n " , r a nd ( ) > ;
Output
1947 1
16395
8268
1 5 582
6489
283 5 6
27042
5276
23070
10930
sscanf 720
#include <Stdio.h>
int sscanf( const char *buffer, const char *format I[, argument :U ••• );
Remarks The sscanf function reads data from buffer into the locations given by each argument.
Every argument must be a pointer to a variable with a type that corresponds to a type speci
fier in format. The format controls the interpretation of the input fields and has the same
form and function as the format argument for the scanf function; see scanf for a complete
description offormat.
Return Value The sscanf function returns the number of fields that were successfully converted and as
signed. The return value does not include fields that were read but not assigned.
The return value is EOF for an attempt to read at end-of-string. A return value of 0 means
that no fields were assigned.
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
(
cha r tokenst r i ng [ ] = " 15 12 14 . . . " ;
cha r s [81] ;
cha r c ;
i nt i:
fl o a t fp ;
721 sscanf
/* I n put v a r i o u s d a t a f rom t o k en s t r i n g : * /
s s c a n f C t o k e n s t r i ng , " % s " , s >:
s s c a n f C t o ken s t r i ng , " %c " , &c > :
s s c a n f C t o k en s t r i ng , " %d " , &i ) :
s s c a n f C t o k e n s t r i ng , " % f " , &fp > :
I * O u t p u t t h e d a ta read * /
p r i n t f C " St r i n g = %s \ n " , s >:
p r i n t f ( " C h a ra ct e r = %c\n " , c >:
p r i n t f C " I n t e ge r : = %d \ n " , i );
p r i n t f ( " Rea l : = %f\ n " , fp > :
Output
St r i n g 15
-
Cha racter 1-
I ntege r : = 1 5
Rea l : 1 5 . 000000
-
stackavail 122
Remades The stackavail function returns the approximate size (in bytes) of the stack space available
for dynamic memory allocation with alloca.
Return Value The stackavail function returns the size in bytes as an unsigned integer value.
Exampm ��
����-
1 * ALLOC A� C : T h i s p ro g r a m c h e c k s t h e s t a c k s p a c e a v a i l a b l e before
* a n d after u s i n g the a l l oc a f u n c t i on t o a l l o c a t e space on the s t a c k .
*I
#i n c l u d e <ma l l oc . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
{
c h a r *buffe r ;
p r i n t f C " By t e s a v a i l a b l e on s t a c k : % u \ n " , s t a c ka v a i l ( ) ) ;
I * Al l o c a t e memo ry for s t r i n g . * /
b u f f e r = a l l oc a < 1 20 * s i z e o f ( c h a r ) ) ;
p r i n t f C " En t e r a s t r i n g : • > :
get s ( b u f f e r ) ;
p r i n t f C " Y o u e n t e red : % s \ n " , buffer ) ;
p r i n t f ( " By t e s a v a i l a b l e o n s t a c k : % u \ n " , s t a c k a v a i l ( ) l ;
Output
Bytes a v a i l a b l e on s t a c k : 2028
Enter a s t r i n g : How muc h s t a c k s p a c e w i l l t h i s s t r i n g t a ke?
Y o u ente red : How m u c h s t a c k space wi l l t h i s s t r i n g t a k e ?
Byt e s a v a i l a b l e o n s t a c k : 1 902
723 stat
#include <Sys\stat.h>
#include <Sys\types.h>
Remarks The stat function obtains infonnation about the file or directory specified by pathname
and stores it in the structure pointed to by buffer. The stat structure, defined in the file
SYS\STAT.ff, includes the following fields:
Field Value
st atime Time of last modification of file (same as st_mtime and
st_ctime).
st ctime Time of last modification of file (same as st_atime and
st_mtime).
st_dev Drive number of the disk containing the file (same as
st_rdev). Real mode only.
st mode Bit mask for file-mode infonnation. The S IFDIR bit is set if
pathname specifies a directory; the S_IFREG bit is set if
pathname specifies an ordinary file. User read/write bits are
set according to the file's pennission mode; user execute bits
are set according to the file-name extension.
Note that ifpathname refers to a device, the size and time fields in the stat structure are
not meaningful.
stat 724
Return Value The stat function returns the value 0 if the file-status information is obtained. A return
value of -1 indicates an error, also, errno is set to ENOENT, indicating that the file name
or path name could not be found.
#i n c l u d e < t i me . h>
#i n c l u d e < sy s \ typ e s . h >
#i n c l u d e < sy s \ s ta t . h >
#i n c l u d e <stdi o . h>
v o i d ma i n ( )
{
s t r u c t s t a t buf ;
i nt fh , resul t ;
c h a r b u f fe r [ ] = " A l i n e t o o u t p u t " ;
I * Check i f sta t i s t i c s a re v a l i d : */
i f ( res ul t != 0 l
p e r r o r ( " P r o b l em g e t t i ng i n f o rma t i on " ) ;
el se
{
I * O u tp u t s ome o f t h e s t a t i s t i c s : * /
p r i n t f ( " Fi l e s i z e % l d \ n " , b u f . s t_s i z e ) ;
pri ntf( " Dri ve %c : \ n " , b u f . s t_d ev + ' A ' ) ;
p r i n t f ( " T i me mod i f i ed : % s " , c t i me ( & b u f . st_a t i me l l ;
Output
F i l e s i ze 761
Dri ve C:
T i me mod i f i ed Wed J u n 1 4 1 2 : 2 0 : 08 1 9 89
725 _status87
#include <float.h>
Remarks The _status87 function gets the floating-point status word. The status word is a com
bination of the 8087 /80287/80387 status word and other conditions detected by the
8087/80287/80387 exception handler, such as floating-point stack overflow and underflow.
Return Value The bits in the value returned indicate the floating-point status. See the FLOAT.ff include
file for a cmnplete definition of the bits returned by _status87.
Note that many of the math library functions modify the 8087 /80287 status word, with un
predictable results. Return values from _clear87 and _status87 become more reliable as
fewer floating-point operations are performed between known states of the floating-point
status word.
Exampm _________________________________________________________________
I * STATUS87 . C : T h i s p r o g r a m c re a t e s va r i o u s f l o a t i n g - po i nt e r r o r s a nd
* t h e n u s e s _s t a t u s 8 7 t o d i s p l a y mes s a ges i n d i c a t i ng t h e s e p r o b l ems .
*I
#i n c l u d e < s t d i o . h >
#i n c l u d e < f l o a t . h >
v o i d ma i n ( )
(
d o u b l e a = l e -40 , b ;
fl oat x , y ;
I * y i s d e n o rma l : * /
b = y;
p r i n t f ( " S t a t u s - % . 4x - i n exa ct u n d e rf l ow , d e n o rma l \ n " , _s ta t u s 8 7 ( ) >:
_status87 726
I * C l ea r u s e r 8087 : * /
_c l e a r87 ( ) ;
Output
S t a t u s = 0000 - c l e a r
S t a t u s = 0030 - i n exa c t , u n d e r f l ow
Sta t u s = 0032 - i n exa ct u n d e r f l ow , d e n o rma l
727 strcat, _fstrcat
Rematits The strcat and _fstrcat functions append string2 to string], terminate the resulting string
with a null character, and return a pointer to the concatenated string (stringl).
to these functions are expected to contain a null character ( '\0 ' ) marking the end of the
The strcat and _fstrcat functions operate on null-terminated strings. The string arguments
Return Value The return values for these functions are described above.
Compatibility strcat
_fstrcat
I * STRCPY . C : T h i s p r o g r a m u s e s s t r c py a n d s t r c a t to b u i l d a p h ra s e . * /
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
strcat, _fstrcat 728
v o i d ma i n { )
(
c h a r s t r i n g [ 80 ] ;
Output
Remarks The strchr and _fstrchr functions return a pointer to the first occurrence of c in string.
The character c may be the null character ('\0'); the terminating null character of string is
included in the search. The function returns NULL if the character is not found.
The strchr and _fstrchr functions operate on null-terminated strings. The string argu
ments to these functions are expected to contain a null character ('\0') marking the end of
the string.
function strchr, with the exception that the arguments and return values are far.
The behavior and return value of fstrchr are identical to those of the model-dependent
Return Value The return values for these functions are described above.
Compatibility strchr
_fstrchr
See Also strcspn, strncat, strncmp, strncpy, strnicmp, strpbrk, strrchr, strspn, strstr
I * STRCHR . C : T h i s p r o g r a m i l l u s t ra t e s s ea r c h i ng f o r a c h a ra c t e r wi t h
* s t r c h r ( s e a r c h fo rwa rd ) o r s t r r c h r ( s e a r c h ba c kwa rd ) .
*I
#i n c l ude < s t r i n g . h >
#i n c l ude < s t d i o . h >
strchr, _fstrchr 730
i nt ch = ' r ' :
char s t r i n g [ ] = " T h e q u i c k brown dog j umps o v e r t h e l a zy fox • :
char fmt l [ J = • 1 2 3 4 5" ;
c ha r fmt2 [ ] = " 1 234567890 1 2 34567890 1 2 3 4 5 6 7 89 0 1 2345678901 234 5 6 7 89 0 " ;
v o i d ma i n ( )
{
c h a r *pdes t :
i nt r e s u l t ;
I * Sea r c h f o rwa rd . * /
p d e s t = s t rc h r C s t r i ng , c h ) ;
resul t = pdest - stri ng + l ;
i f ( pdest ! = NULL )
p r i n t f C " Re s u l t : \ t f i r s t %c found a t p os i t i on %d \ n \ n • , c h , r e s u l t > :
el se
p r i n t f C " Re s u l t : \ t % c n o t found \ n " > :
I * Sea r c h b a c kwa rd . * /
pdes t = s t r rc h r C s t r i n g , c h > :
resul t - pdest - s t r i ng + 1 ;
i f ( pdest ! = NULL )
p r i n t f C " Re s u l t : \ t l a s t %c found a t pos i t i on % d \ n \ n " , c h , r e s u l t > :
el se
p r i n t f ( " Re s u l t : \ t % c not found \ n " > :
Output
St r i n g t o be s e a rched :
T h e q u i c k b rown dog j umps o v • r t h e l a zy fox
1 2 3 4 5
1 23456789012345678901 234567890 1 2345678901 2 34 5 67890
Sea r c h c h a r : r
Re s u l t : f i r s t r found a t po s i t i on 1 2
Remarks The strcmp and _fstrcmp functions compare string] and string2 lexicographically and re
turn a value indicating their relationship, as follows:
Value Meaning
<0 string] less than string2
=0 string] identical to string2
>0 string] greater than string2
The strcmp and _fstrcmp functions operate on null-terminated strings. The string argu
ments to these functions are expected to contain a null character ( '\0 ' ) marking the end of
the string.
Return Value The return values for these functions are described above.
Compatibility strcmp
_fstrcmp
See Also memcmp, memicmp, strncat, strncmp, strncpy, strnicmp, strrchr, strspn
Exampre ��
��
I * STRCM P . C * /
#i n c l u d e < s t r i ng . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
I
c h a r t mp [ 20 J ;
i n t res u l t ;
I * Case sensi ti ve */
p r i n t f ( " C ompa re s t r i n g s : \ n \ t % s \ n \ t % s \ n \ n " , s t r i n g l , s t r i ng2 ) ;
r e s u l t = s t rcmp ( s t r i n g l , s t r i n g 2 ) ;
i f ( resul t > 0 )
s t rcpy ( tmp , " g re a t e r t h a n " ) ;
el s e i f ( resul t < 0 )
s t r c py ( tmp , " l e s s t h a n " l ;
el se
s t rc py ( tmp , " eq u a l t o " l ;
p r i n t f ( " \ t s t rcmp : S t r i n g 1 i s %s s t r i n g 2 \ n " , tmp ) ;
/ * C a s e i n s en s i t i v e ( c o u l d u s e e q u i v a l e n t s t r i cmp l * /
r e s u l t = s t rcmp i ( s t r i n g l , s t r i n g 2 l ;
i f ( resul t > 0 l
s t r c py ( tmp , " g re a t e r t h a n " ) ;
el s e i f ( resul t < 0 l
s t r c py ( tmp , " l e s s t h a n " l ;
el s e
s t rc py ( tmp , " eq u a l t o " l ;
p r i n t f ( " \ t s t r cmp i : St r i n g 1 i s % s s t r i ng 2 \ n " , tmp l ;
Output
Compa re s t r i n g s :
T h e q u i c k b rown dog j umps o v e r t h e 1 a zy fox
The QU I C K b rown dog j umps o v e r t h e l a zy fox
Remarks The strcoll function compares string} and string2 lexicographically and returns a value in
dicating their relationship, as follows:
Value Meaning
The strcoll function operates on null-terminated strings. The string arguments to these
functions are expected to contain a null character ('\0') marking the end of the string.
The strcoll function differs from strcmp in that it uses locale-specific information to pro
vide locale-specific collating sequences.
Return Value The return value for this function is described above.
Remarks The strcpy function copies string2, including the tenninating null character, to the loca
tion specified by string], and returns string] .
The strcpy and _fstrcpy functions operate on null-tenninated strings. The string argu
ments to these functions are expected to contain a null character ('\0 ' ) marking the end of
the string. No overflow checking is perfonned when strings are copied or appended.
Return Value The return values for these functions are described above.
Campallblllty strcpy
_fstrcpy
See Also strcat, strcmp, strncat. strncmp, strncpy, strnicmp, strrchr, strspn
/ * STRC PY . C : T h i s p r o g r a m u s e s s t rcpy a n d s t r c a t to b u i l d a p h ra s e . * /
#i n c l u d e < s t r i ng . h >
#i n c l u d e < s t d i o . h >
735 strcpy, _fstrcpy
v o i d ma i n ( )
(
c h a r s t r i n g [ 80 ] ;
Output
Remarks The strcspn functions return the index of the first character in string 1 belonging to the set
of characters specified by string2. This value is equivalent to the length of the initial sub
string of string] consisting entirely of characters not in string2. Tenninating null charac
ters are not considered in the search. If stringl begins with a character from string2,
strcspn returns 0.
The strcspn and _fstrcspn functions operate on null-tenninated strings. The string argu
ments to these functions are expected to contain a null character ( '\0 ' ) marking the end of
the string.
The _fstrcspn function is a model-independent (large-model) fonn of the strcspn func
tion. The behavior and return value of_fstrcspn are identical to those of the model
dependent function strcspn, with the exception that the arguments and return values
are far.
Return Value The return values for these functions are described above.
Compatibility strcspn
_fstrcspn
Exampm ������
I * STRC S P N . C * /
#i n c l ude < s t r i n g . h >
#i n c l ude < s t d i o . h >
737 strcspn, _fstrcspn
v o i d ma i n ( )
(
c h a r s t r i n g [ ] = � xy z a bc " ;
i n t pos ;
Output
Fi r s t a , b o r c i n xyz a bc i s a t c h a r a c t e r 3
_strdate 138
#include <time.b>
Remades The _strdate function copies the date to the buffer pointed to by datestr, fonnatted
mm/ d d / yy
where mm is two digits representing the month, dd is two digits representing the day of
the month, and y y is the last two digits of the year. For example, the string
1 2 / 0 5 / 88
Relum Value The _strdate function returns a pointer to the resulting text string datestr.
Exampm �����--
1 * STRT I M E . C * /
#i n c l ude < t i me . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
{
c h a r dbuffer [ 9 ] ;
cha r tbuffer [ 9 ] ;
_s t rd a t e C d b u f f e r > :
p r i n t f ( " T h e c u r rent d a te i s % s \ n " , d b u f f e r > :
_s t rt i me ( t b u f f e r ) ;
p r i n t f ( " T h e c u r rent t i me i s % s \ n " , t b u f f e r l :
739 _strdate
Output
T h e c u r rent d a t e i s 0 6 / 2 0 / 8 9
T h e c u r rent t i me i s 0 9 : 33 : 1 3
strdup Functions 740
Remarks The strdup function allocates storage space (with a call to malloc) for a copy of string and
returns a pointer to the storage space containing the copied string. The function returns
NULL if storage cannot be allocated.
The _fstrdup and _nstrdup functions provide complete control over the heap used for
string duplication. The strdup function returns a pointer to a copy of the string argument.
The space for the string is allocated from the heap specified by the memory model in use.
In large-data models (that is, compact-, large-, and huge-model programs), strdup allo
cates space from the far heap. In small-data models (tiny-, small-, and medium-model pro
grams), strdup allocates space from the near heap.
The strdup, _fstrdup, and _nstrdup functions operate on null-terminated strings. The
string arguments to these functions are expected to contain a null character (' \0 ' ) marking
the end of the string.
The _fstrdup function returns a far pointer to a copy of the string allocated in far memory
(the far heap). As with the other model-independent functions, the syntax and semantics of
these functions correspond to those of strdup except for the sizes of the arguments and re
turn values. The _nstrdup function returns a near pointer to a copy of the string allocated
in the near heap (in the default data segment).
Return Value The return values for these functions are described above.
See Also strcat, strcmp, strncat, strncmp, strncpy, strnicmp, strrchr, strspn
Exampm ������-
1 * STRDU P . C * /
#i n c l u d e < s t r i n g . h>
#i n c l u d e < s t d i o . h >
#i n c l u d e < c on i o . h >
Ii i n c l u d e < d o s . h >
v o i d ma i n ( )
(
c h a r b u f f e r [ ] = " T h i s i s t h e b u f f e r text " ;
c h a r * n ews t r i n g ;
Output
O r i g i n a l : T h i s i s t h e buffer text
C o py : T h i s i s the buffer text
strerror, _strerror 742
D11t:1/pllon Gets a system error message (strerror) or prints a user-supplied error message Lstrerror).
Remarks The strerror function maps errnum to an error-message string, returning a pointer to the
string. The function itself does not actually print the message; for that, you need to call an
output function such as printf.
If string is passed as NULL, _strerror returns a pointer to a string containing the system
If string is not equal to NULL, then _strerror returns a pointer to a string containing (in
order) your string message, a colon, a space, the system error message for the last library
call producing an error, and a newline character. Your string message can be a maximum
of 94 bytes long.
Unlike perror, _strerror alone does not print any messages. To print the message re
turned by _strerror to stderr, your program will need an fprintf statement, as shown in
the following lines:
The actual error number for strerror is stored in the variable errno, which should be de
clared at the external level. The system error messages are accessed through the variable
sys_errlist, which is an array of messages ordered by error number. The _strerror func
tion accesses the appropriate error message by using the errno value as an index to the
variable sys_errlist. The value of the variable sys_nerr is defined as the maximum num
ber of elements in the sys_errlist array.
To produce accurate results, _strerror should be called immediately after a library routine
returns with an error. Otherwise, the ermo value may be overwritten by subsequent calls.
Note that the strerror function under Microsoft C version 5.0 is identical to the version
4.0 strerror function. The name was altered to permit the inclusion in Microsoft C version
5.0 of the ANSI-conforming strerror function. The _strerror function is not part of the
ANSI definition but is instead a Microsoft extension to it; it should not be used where
portability is desired. For ANSI compatibility, use strerror instead.
743 strerror, _strerror
Rstum Value The strerror function returns a pointer to the error-message string. The string can be over
written by subsequent calls to strerror.
The _strerror function returns the same value as strerror.
Campatlbll/ly strerror
_strerror
Remarks The strftime function fonnats the tm time value in timeptr according to the supplied
format argument and stores the result in the buffer string. At most, maxsize characters are
placed in the string.
Theformat argument consists of one or more codes; as in printf, the fonnatting codes are
preceded by a % sign. Characters that do not begin with a % sign are copied unchanged to
string. The LC_TIME category of the current locale affects the output fonnatting of
strftime.
The fonnatting codes for strftime are listed below:
Format Description
Return Value The strftime function returns the number of characters placed in string if the total number
of resulting characters, including the terminating null, is not more than maxsi:e.
Otherwise, strftime returns 0, and the contents of the stririg are indeterminate.
Rema tics The stricmp and _fstricmp functions compare string! and string2 lexicographically and
return a value indicating their relationship, as follows:
Value Meaning
The stricmp and _fstricmp functions operate on null-terminated strings. The string argu
ments to these functions are expected to contain a null character ('\0 ' ) marking the end of
the string.
RBtum Value The return values for these functions are described above.
CampaUblllly stricmp
_fstricmp
See Also memcmp, memicmp, strcat, strcpy, stmcat, strncmp, strncpy, strnicmp, strrchr,
strset, strspn
Rsmadcs The strlen and _fstrlen functions return the length in bytes of string, not including the ter
minating null character ('\0').
The _fstrlen function is a model-independent (large-model) fonn of the strlen function.
The behavior and return value of_fstrlen are identical to those of the model-dependent
function strlen, with the exception that the argument is a far pointer.
Return Va/us These functions return the string length. There is no error return.
Compatibility strlen
_fstrlen
Exampm ��������-
1 * ST R L E N . C * /
#i n c l ude < s t r i n g . h >
#i n c l ude < s t d i o . h >
#i n c l ude < c on i o . h >
#i n c l ude < d o s . h >
749 strlen, _fstrlen
v o i d ma i n ( )
(
c h a r b u f fe r [ 6 1 ] = � H ow l on g a m I ? " ;
i n t l en ;
l en = s t r l e n ( b u f f e r ) ;
p r i n t f ( " ' % s ' i s %d c h a r a c t e r s l on g \ n • , buffe r , l e n ) ;
Output
' H ow l on g a m I ? ' i s 14 c h a r a c t e r s l on g
strlwr, _fstrlwr 750
Remarks The strlwr and _fstrlwr functions convert any uppercase letters in the given null
tenninated string to lowercase. Other characters are not affected.
The _fstrlwr function is a model-independent (large-model) fonn of the strlwr function.
The behavior and return value of _fstrlwr are identical to those of the model-dependent
function strlwr, with the exception that the argument and return values are far pointers.
Return Value These functions return a pointer to the converted string. There is no error return.
Exampm _________________________________________________________________
I * STRLW R . C : T h i s p ro g r a m u s e s s t r l w r a n d s t ru p r t o c r e a t e
* uppe r c a s e a n d l ow e rc a s e copi e s of a mi x ed - c a s e s t r i n g .
*I
v o i d ma i n ( )
{
c h a r s t r i n g [ 1 00 ] = " T h e S t r i n g t o End A l l St r i n g s ! " ;
c h a r * c o py l , *copy2 ;
copyl = strlwr( s t rd u p ( s t r i n g ) ) ;
c opy2 = strupr< s t rd u p ( s t r i n g > ) ;
pri ntf ( " M i xed : %s\ n " , stri ng ) ;
pri ntf( " Lowe r : % s \ n " , copy l > :
pri ntf ( " Upper : % s \ n " , copy2 > :
751 strlwr, _fstrlwr
Output
M i x e d : T h e S t r i n g t o E n d Al l S t r i n g s !
Lowe r : t h e s t r i n g to end a l l s t r i n g s !
U p pe r : THE ST R I N G TO E N D A L L STRI N G S !
strncat, _fstrncat 752
Remarks The strncat and _fstrncat functions append, at most, the first count characters of string2
to string], terminate the resulting string with a null character ( '\0 ' ) , and return a pointer to
the concatenated string (string]). If count is greater than the length of string2, the length of
string2 is used in place of count.
The _fstrncat function is a model-independent (large-model) form of the strncat function.
The behavior and return value of _fstrncat are identical to those of the model-dependent
function strncat, with the exception that all the pointer arguments and return values are far
pointers.
Return Value The return values for these functions are described above.
Compatibility strncat
_fstrncat
See Also strcat, strcmp, strcpy, strncmp, strncpy, strnicmp, strrchr, strset, strspn
Example ������
I * ST RN CAT . C * /
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
753 strncat, _fstrncat
v o i d ma i n ( )
{
c h a r stri ng [80] = "Th i s i s the i n i t i a l stri ng ! " ;
c h a r s u f f i x [ ] = • e x t r a text t o a d d t o t h e s t r i n g . . . ;
"
/ * Comb i n e s t r i n g s w i t h no more t h a n 1 9 c h a r a c t e r s of s u f f i x : */
p r i n t f { " Be f o r e : % s \ n " , s t r i n g l ;
st rnca t C stri ng , suffi x , 1 9 l ;
p r i n t f ( " Aft e r : % s \ n " , s t r i n g ) ;
Output
B e f o r e : Th i s i s t h e i n i t i a l s t r i n g !
Aft e r : Th i s i s t h e i n i t i a l s t r i n g ! e x t r a t e x t t o add
strncmp, _fstrncmp 754
int strncmp( const char *string] , const char *string2, size_t count );
int _far _fstmcmp( const char _far *string] , const char _far *string2, size_t count );
RemarkB The stmcmp and _fstrncmp functions lexicographically compare, at most, the first count
characters of string] and string2 and return a value indicating the relationship between the
substrings, as listed below:
Value Meaning
Return Value The return values for these functions are described above.
Campatlblllly strncmp
_fstrncmp
SBB AllO strcat, strcmp, strcpy, strncat, strncpy, strrchr, strset, strspn
755 strncmp, _lstrncmp
Examp• �������-.-�
I * ST RNCM P . C * /
#i n c l ude < s t r i n g . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
(
c h a r tmp [ 20 ] ;
i nt resul t ;
Output
Comp a re s t r i n g s :
T h e q u i c k b rown dog j umps o v e r t h e l a zy fox
The QU I C K b rown fox j umps over the l a zy dog
F u n c t i on : s t rncmp ( f i r s t 1 0 c h a r a c t e r s o n l y )
Res u l t : St r i n g 1 i s g rea t e r t h a n s t r i ng 2
Funct i on : s t r n i cmp ( f i r s t 1 0 c h a r a c t e rs o n l y )
Res u l t : S t r i n g 1 i s equa l t o s t r i ng 2
strncpy, _fstrncpy 756
Remarks The strncpy and _fstrncpy functions copy count characters of string2 to string] and re
turn string]. If count is less than the length of string2, a null character ( '\0 ') is not ap
pended automatically to the copied string. If count is greater than the length of string2, the
string] result is padded with null characters ( '\0 ' ) up to length count.
Note that the behavior of strncpy and _fstrncpy is undefined if the address ranges of the
source and destination strings overlap.
Return Value The return values for these functions are described above.
Compaliblllty strncpy
_fstrncpy
See Also strcat, strcmp, strcpy, strncat, strncmp, strnicmp, strrchr, strset, strspn
757 strncpy, _fstrncpy
Exampm ��������-
1 * STRNCPY . C * /
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
[
c h a r s t r i n g [ 1 00 ] = " Ca t s a re n i ce usua l l y " ;
Output
B e fo r e : C a t s a re n i c e u s u a l l y
Afte r : Dogs a re mea n u s u a l l y
strnicmp, _fstrnicmp 758
int strnicmp( const char *string!, const char *string2, size_t count );
int _far _fstrnicmp( const char _far *string], const char _far *string2, .
· size_t count );
Remarks The strnicmp and _fstrnicmp functions lexicographically compare (without regard to
case), at most, the first count characters of string! and string2 and return a value indicating
the relationship between the substrings, as listed below:
Value Meaning
Return Value The return values for these functions are described above.
See Also strcat, strcmp, strcpy, strncat, strncpy, strrchr, strset, strspn
c Character setting
character c and return a pointer to the altered string. If count is greater than the length of
RematlcB The stmset and fstrnset functions set, at most, the first count characters of string to the
Retum Value The return values for these functions are described above.
Examp� --
---
1 * STRNSET . C * /
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
{
cha r stri n g [ l 5 ] = " Th i s i s a test " ;
Output
Remarks The strpbrk function finds the first occurrence in string] of any character from string2.
The terminating null character ( '\0 ' ) is not included in the search.
The _fstrpbrk function is a model-independent (large-model) form of the strpbrk func
tion. The behavior and return value of _fstrpbrk are identical to those of the model
dependent function strpbrk, with the exception that all the arguments and return values
are far.
Return Value These functions return a pointer to the first occurrence of any character from string2 in
string]. A NULL return value indicates that the two string arguments have no characters in
common.
Compatibility strpbrk
_fstrpbrk
Exampre ��������-
1 * ST R P B R K . C * /
#i n c l ude < s t r i n g . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
(
c h a r s t r i n g [ 1 0 0 J = " T h e 3 men a n d 2 boy s a t e 5 p i g s \ n " ;
cha r *resul t ;
strpbrk, _fstrpbrk 762
Output
1 : T h e 3 men a n d 2 boys a t e 5 p i g s
2 : 3 m e n a n d 2 boys a te 5 p i g s
3 : 2 boy s a t e 5 p i g s
4: 5 pi gs
763 strrchr, _lstrrchr
minating null character ('\0 ' ) is included in the search. (Use strchr to find the first occur
Remarks The strrchr function finds the last occurrence of the character c in string. The string's ter
rence of c in string.)
Return Value These functions return a pointer to the last occurrence of the character in the string. A
NULL pointer is returned if the given character is not found.
Compatibility strrchr
_fstrrchr
See Also strchr, strcspn, strncat, strncmp, strncpy, strnicmp, strpbrk, strspn
Example __ ���������������������������������
I * STRC H R . C : T h i s p r o g r a m i l l u s t r a t e s s e a rc h i n g f o r a c h a r a c t e r w i t h
* s t r c h r < s ea r c h forwa rd ) o r s t r rc h r ( s ea r c h ba c kwa rd ) .
*/
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
strrchr, _fstrrchr 764
i nt ch = ' r ' ;
char s t r i n g [ ] = " Th e q u i c k b rown dog j umps o v e r t h e l a zy fox " ;
cha r fmt l [ J = 1 2 3 4 5" ;
cha r fmt2 [ J = " 1 234567890 1 234567890123456789012345678901 234567890 " ;
v o i d ma i n ( )
{
c h a r *pdes t ;
i n t res u l t ;
p r i n t f { " St r i n g t o b e s e a r c h ed : \ n \ t \ t % s \ n " , s t r i n g ) ;
p r i n t f ( " \ t \ t % s \ n \ t \ t % s \ n \ n " , fmt l , fmt2 ) ;
p r i n t f ( " Se a r c h c h a r : \ t %c \ n " , c h l ;
I * Sea r c h forwa rd . * /
p d e s t = s t rc h r ( s t r i n g , c h l :
res u l t = pdest - s t r i n g + 1 ;
i f ( pdest ! = N U L L )
p r i n t f ( " Re s u l t : \ t f i r s t %c found a t p os i t i on %d \ n \ n " , c h , res u l t l ;
el se
p r i n t f ( " Re s u l t : \ t% c n o t found \ n " l ;
I * S e a r c h b a c kwa rd . * /
pd e s t = s t r rc h r ( s t r i n g , c h l ;
re s u l t = pdest - s t r i n g + 1 ;
i f ( pdest ! = NULL l
p r i n t f ( " Re s u l t : \ t l a s t %c found a t po s i t i o n %d \ n \ n " , c h , r e s u l t l ;
el se
p r i n t f ( " Re s u l t : \ t%c n o t found \ n " ) ;
Output
St r i n g t o b e s e a r c h ed :
T h e q u i c k brown dog j umps o v e r t h e l a zy fox
1 2 3 4 5
1 23 4 5 6 7 890 1 2 345678901 234567 890 1 2 345678901 234 5 6 7 890
Sea r c h c h a r : r
Re s u l t : f i r s t r found a t pos i t i on 1 2
Re s u l t : l a s t r found a t po s i t i on 30
765 strrev, _fstrrev
Remarks The strrev function reverses the order of the characters in string. The tenninating null
character ( '\0 ' ) remains in place.
The _fstrrev function is a model-independent (large-model) fonn of the strrev function.
The behavior and return value of fstrrev are identical to those of the model-dependent
function strrev, with the exception that the argument and return v alue are far pointers.
Return Value These functions return a pointer to the altered string. There is no error return.
I * ST R R E V . C : T h i s p r o g r a m c h e c ks a n i n put s t r i n g to s e e w h et h e r i t i s a
* pa l i nd rome : t h a t i-s , w h e t h e r i t r e a d s t h e s a me f o rwa rd a n d b a c kwa rd .
*/
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s td i o . h >
v o i d ma i n ( )
(
c h a r stri n g [ 100J :
i nt resul t :
I * Re v e r s e s t r i n g a n d c omp a re ( i gnore c a s e ) : * /
res u l t = s t rcmpi ( s t r i ng , s t r rev ( s t rdup ( s t r i n g > > ) ;
i f ( res u l t == 0 >
p r i n t f ( " T h e s t r i n g \ " % s \ " i s a p a l i nd rome \ n \ n " , s t r i n g ) ;
el se
p r i n t f ( " T h e s t r i n g \ " % s \ " i s n o t a pa l i nd rome\ n \ n " , s t r i n g > ;
Output
R1matlt8 The strset function sets all of the characters of string to c, except the tenninating null
character ('\0').
Retum Value These functions return a pointer to the altered string. There is no error return.
Exampm ______________________________________________________________
I * ST RS ET . C * I
#i n c l ude < s t r i n g . h >
#i n c l ude , < s t d i o . h >
v o i d ma i n ( )
(
c h a r s t r i n g [ ] - " Fi l l t h e s t r i n g w i t h s omet h i n g " :
Output
B e f o r e : F i l l t h e s t r i n g w i t h s omet h i n g
Aft e r : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
769 strspn, _fstrspn
Rsmalks The strspn function returns the index of the first character in string] that does not belong
to the set of characters specified by string2. This value is equivalent to the length of the ini
tial substring of string] that consists entirely of characters from string2. The null character
( '\0 ' ) tenninating string2 is not considered in the matching process. If string] begins with
a character not in string2, strspn returns 0.
Rslurn Va/us These functions return an integer value specifying the length of the segment in string] con
sisting entirely of characters in string2.
Compallblllly strspn
_fstrspn
ExamplB __________________________________________________________________�
I * STRS P N . C : T h i s p r o g r a m u s e s s t r s p n t o d e t e rmi n e t h e l en g t h of
* the s egment i n the s t r i n g " c a bb a g e " con s i s t i ng of a ' s , b ' s , a nd e ' s .
* I n o t h e r w o rd s , i t f i n d s t h e f i r s t n on - a bc l et t e r .
*I
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
strspn, _fstrspn 770
v o i d ma i n ( )
{
cha r stri ng [ ] = " cabbage • ;
i nt resul t ;
Output
R1matks The strstr function returns a pointer to the first occurrence of string2 in string1.
R1tum Value These functions return either a pointer to the first occurrence of string2 in string] , or
NULL if they do not find the string.
Compal/blllty strstr
_fstrstr
s.. AIBo strcspn, strncat, strncmp, strncpy, strnicmp, strpbrk, strrchr, strspn
ExampM __�����������������������������---
1 * STRSTR . C * /
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
(
c h a r *pdest ;
i nt resul t ;
Output
St r i n g t o be s e a rched :
T h e q u i c k b r own d o g j umps o v e r t h e l a zy fox
1 2 3 4 5
1 2 34567890 1 2345678901 234567890 1 234567890123456 7890
l a zy found at p o s i t i o n 3 6
_strtime
#include <time.h>
Remalk8 The _strtime function copies the current time into the buffer pointed to by timestr. The
time is formatted
h h : mm : s s
where h h is two digits representing the hour in 24-hour notation, mm is two digits repre
senting the minutes past the hour, and s s is two digits representing seconds. For ex
ample, the string
1 8 : 23 : 44
Retum Value The _strtime function returns a pointer to the resulting text string timestr.
Exampm ��
����---
1 * ST RT I M E . C * /
#i n c l u d e < t i me . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
(
cha r dbuffer [ 9 ] ;
cha r tbuffer [ 9 ] ;
_strtime 774
_s t rd a t e C d b u f f e r >:
p r i n t f C • T h e c u r rent d a t e i s S s \ n • , dbuffer >:
_s t r t i me C t b u f f e r > :
p r i n t f C • T h e c u r r e n t t i me i s S s . \ n • , t b u f f e r >:
Output
#include <Stdlib.h>
Rematits The strtod, _strtold, strtol, and strtoul functions convert 'a character string to a double
precision value, a long-double value, a long-integer value, or an unsigned long-integer
value, respectively. The input string is a sequence of characters that can be interpreted as a
numerical value of the specified type. If the strtod or _strtold function appears in a
compact-, large-, or huge-model program, nptr can be a maximum of 100 characters.
of a number. This may be the null character ( '\0 ' ) at the end of the string. With strtol or
These functions stop reading the string at the first character they cannot recognize as part
strtoul, this terminating character can also be the first numeric character greater than or
equal to base. If endptr is not NULL, a pointer to the character that stopped the scan is
stored at the location pointed to by endptr. If no conversion could be performed (no valid
digits were found or an invalid base was specified), the value of nptr is stored at the loca
tion pointed to by endptr.
The strtod and _strtold functions expect nptr to point to a string with the following form:
[whitespace]) [sign]) [digits]) [.digits]) [ {d I D I e I E ) [sign])digits]]
The first character that does not fit this form stops the scan.
The strtol function expects nptr to point to a string with the following form:
[whitespace]) [sign]) [O]) [{ x I X }]] [digits])
The strtoul function expects nptr to point to a string having this form:
[whitespace]) [{ + 1 - } ]] [O]) [{ x I X } ]] [digits])
strtad, stria/, _strtald, strtaul 776
If base is between 2 and 36, then it is used as the base of the number. If base is 0, the ini
tial characters of the string pointed to by nptr are used to determine the base. If the first
character is 0 and the second character is not 'x' or 'X', then the string is interpreted as an
octal integer; otherwise, it is interpreted as a decimal number. If the first character is 'O'
and the second character is 'x' or 'X', then the string is interpreted as a hexadecimal in
teger. If the first character is ' l ' through '9', then the string is interpreted as a decimal in
teger. The letters 'a' through ' z ' (or ' A' through Z ) are assigned the values 10 through
' '
35; only letters whose assigned values are less than base are permitted.
The strtoul function allows a plus (+) or minus (-) sign prefix; a leading minus sign indi
cates that the return v alue is negated.
Retum Value The strtod and _strtold functions return the value of the floating-point number, except
when the representation would cause an overflow, in which case it returns ±HUGE_VAL.
The functions return 0 if no conversion could be performed or an underflow occurred.
The strtol function returns the value represented in the string, except when the repre
sentation would cause an overflow, in which case it returns LONG_MAX or LONG_MIN.
The function returns 0 if no conversion could be performed.
The strtoul function returns the converted value, if any. If no conversion can be per
formed, the function returns 0. The function returns ULONG_MAX on overflow. In all four
functions, ermo is set to ERANGE if overflow or underflow occurs.
strtoul
I * ST RTO D . C : T h i s p r o g r a m u s e s s t r t o d to c o n v e r t a s t r i n g t o a
* d o u b l e - p r ec i s i on v a l u e ; s t r t o l t o c o n v e r t a s t r i n g t o l o ng
* i nt e g e r v a l ues ; and s t r t o u l t o c o n v e r t a s t r i n g t o u n s i gned
* l on g - i n t e g e r v a l u e s .
*I
v o i d ma i n ( )
(
cha r *stri ng , *stopstri ng ;
doubl e x ;
1 ong 1 ;
i nt ba s e ;
u n s i g n ed l on g u l ;
Output
s t r i n g = 3 . 1 4 1 5 9 2 6Th i s s t opped i t
s t r t od = 3 . 1 4 1 5 9 3
Stopped s c a n a t : T h i s s t opped i t
s t r i ng = - 1 0 1 1 0 1 34932Th i s s t opped i t
s t rt o l = - 2 1 4 7483647
St opped s c a n a t : T h i s s t opped i t
s t r i n g = 1 0 1 1 0 1 34 9 3 2
s t rt o l = 4 5 ( ba s e 2 )
St opped s c a n a t : 34932
s t rt o l = 4423 ( ba s e 4 )
Stopped s c a n a t : 4 9 3 2
s t rt o l = 2 1 34 1 08 ( ba s e 8 )
Stopped s c a n a t : 9 3 2
strtok, _fstrtok 778
char _far * _far _fstrtok( char _far *string], const char _far *string2 );
Remam The strtok function reads string] as a series of zero or more tokens and string2 as the set
of characters serving as delimiters of the tokens in string]. The tokens in string] may be
separated by one or more of the delimiters from string2.
The tokens can be broken out of string] by a series of calls to strtok. In the first call to
strtok for string], strtok searches for the first token in string], skipping leading
delimiters. A pointer to the first token is returned. To read the next token from string I, call
strtok with a NULL value for the string] argument. The NULL string] argument causes
strtok to search for the next token in the previous token string. The set of delimiters may
vary from call to call, so string2 can take any value.
The _fstrtok function is a model-independent (large-model) fonn of the strtok function.
The behavior and return value of _fstrtok are identical to those of the model-dependent
function strtok, with the exception that the arguments and return value are far pointers.
Retum Va/ue The first time strtok i s called, i t returns a pointer to the first token i n string]. In later calls
with the same token string, strtok returns a pointer to the next token in the string. A
NULL pointer is returned when there are no more tokens. All tokens are null-tenninated.
Compatlblllty strtok
_fstrtok
I * STRTOK . C : I n t h i s p r o g r a m , a l oop u s e s s t rt o k t o p r i n t a l l t h e t o ke n s
* ( s epa ra ted b y comma s o r bl a n k s ) i n t h e s t r i n g n amed " s t r i n g • .
*I
#i n c l u d e < s t r i n g . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
{
p r i n t f ( " % s \ n \ nT o k e n s : \ n " , s t r i n g ) ;
/ * E s t a b l i s h s t r i n g a n d get t h e f i r s t t o ken : * /
t o k e n = s t rt o k ( s t r i n g , s eps l ;
whi l e ( token ! = NULL )
{
I * W h i l e t h e r e a re t o ke n s i n " s t r i n g • * /
pri ntf( • %s\ n • , token l ;
I * Get next t o k e n : * /
t o k e n = s t rt o k C N U L L , s e p s l ;
Output
A s t r i ng of , , tokens
a n d s ome more t o k e n s
Tokens :
A
s t ri n g
of
tokens
a nd
s ome
more
tokens
strupr, _fstrupr 780
Remarks These functions convert any lowercase letters in the string to uppercase. Other characters
are not affected.
The _fstrupr function is a model-independent (large-model) form of the strupr function.
The behavior and return value of _fstrupr are identical to those of the model-dependent
function strupr, with the exception that the argument and return value are far pointers.
Return Value These functions return a pointer to the converted string. There is no error return.
/ * STRLWR . C : T h i s p ro g r a m u s e s s t r l w r a n d s t r u p r · t o c re a t e
* upper c a s e a n d l ow e rc a s e cop i e s of a m i x ed - c a s e s t r i n g . ·
*I
v o i d ma i n ( )
{
c h a r s t r i n g [ 1 00 ] = " T h e St r i ng t o End Al l S t r i n g s ! " ;
c h a r * c o py l , *copy2 ;
Output
Remarks The strxfrm function transfonns the string pointed to by string2 into a new fonn that is
stored in stringl. No more than count characters (including the null character) are trans
fonned and placed into the resulting string.
The value of the following expression is the size of the array needed to hold the transfor
mation of the source string:
1 + s t rx f rM( N U L L , · s t r i n g , 0 >
Currently, the C libraries support the "C" locale only; thus strxfrm is equivalent to the
following:
st r n c py ( _s t r i n g l , _s t r i n g 2 , _c ount > :
ret u r n ( s t r l en ( _s t r i ng2 ) > :
Return Value The strxfrm function returns the length of the transfonned string, not counting the tenni
nating null character. If the return value is greater than or equal to count, the contents of
stringl are unpredictable.
Remarks The swab function copies n bytes from src, swaps each pair of adjacent bytes, and stores
the result at dest. The integer n should be an even number to allow for swapping. The
swab function is typically used to prepare binary data for transfer to a machine that uses a
different byte order.
I* SWAB . C * /
#i n c l u d e < s t d l i b . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
{
p r i n t f ( " Be f o r e : \ t%s \ n \ t % s \ n \ n " , f rom , t o ) ;
s wa b ( f rom , t o , s i z e o f ( f rom ) ) ;
p r i n t f ( " Aft e r : \ t % s \ n \ t% s \ n \ n " , f rom , t o ) ;
Output
Remarks The system function passes command to the command interpreter, which executes the
string as an operating-system command. The system function refers to the COMSPEC and
PATH environment variables that locate the command-interpreter file (the file named
COMMAND.COM in DOS or CMD.EXE in OS/2). If command is a pointer to an empty
string, the function simply checks to see whether or not the command interpreter exists.
Return Value If command is NULL and the command interpreter is found, the function returns a nonzero
value. If the command interpreter is not found, it returns the value 0 and sets errno to
ENOENT. If command is not NULL, the system function returns the value 0 if the com
mand interpreter is successfully started. Under OS/2, the system function returns the exit
status from the command interpreter.
A return value of -1 indicates an error, and errno is set to one of the following values:
Value Meaning
E2BIG In DOS, the argument list exceeds 128 bytes, or the space re
quired for the environment information exceeds 32K. In OS/2,
the combined argument list and space required for environ
ment information exceed 32K.
ENOENT The command interpreter cannot be found.
ENOEXEC The command-interpreter file has an invalid format and is not
executable.
ENOMEM Not enough memory is available to execute the command; or
the available memory has been corrupted; or an invalid block
exists, indicating that the process making the call was not allo
cated properly.
785 system
Exampm _________________________________________________________________
I * SYSTEM . C : T h i s p r o g r a m u s e s sy s t em t o TY P E i t s s o u r c e f i l e . * /
v o i d ma i n ( )
{
s y s t e m < " type system . c " > ;
Output
I * SYSTEM . C : T h i s p rog r a m u s e s sy s t em t o TY P E i t s s o u r c e f i l e . * /
v o i d ma i n ( )
{
s y s t e m ( " type system . c " ) ;
tan Functions 786
Description Calculate the tangent (tan and tanl) and hyperbolic tangent (tanh and tanhl).
#include <math.h>
x Angle in radians
Remades The tan functions return the tangent or hyperbolic tangent of their arguments. The list
below describes the differences between the various tangent functions:
Function Description
The tanl and tanhl functions are the 80-bit counterparts and use an 80-bit, 1 0-byte co
processor form of arguments and return values. See the reference page on the long double
functions for more details on this data type.
Return Value The tan function returns the tangent of x. If x is large, a partial loss of significance in the
result may occur; in this case, tan sets errno to ERANGE and generates a PLOSS error. If
x is so large that significance is totally lost, tan prints a TLOSS error message to stderr,
sets ermo to ERANGE, and returns 0.
There is no error return for tanh.
tanl, tanhl
S11 A/BO acos functions, asin functions, atan functions, cos functions, sin functions
#i n c l u d e <ma t h . h>
#i n c l ude < s td i o . h >
v o i d ma i n ( )
(
doubl e pi - 3 . 141 5926535 :
doubl e x , Y:
x = ta n ( p i I 4 > :
y - tanh C x > :
pri ntfC " ta n ( %f ) =%f\ n " , x , y ) ;
p r i n t f C " t a n h C %f ) = % f \ n " , y , x ) ;
Output
t a n h C 0 . 7 6 1 594 ) = 1 . 000000
tell 788
Remarks The tell function gets the current position of the file pointer (if any) associated with the
handle argument. The position is expressed as the number of bytes from the beginning of
the file.
Return Value A return value of -lL indicates an error, and errno is set to EBADF to indicate an invalid
file-handle argument. On devices incapable of seeking, the return value is undefined.
/ * T E L L . C : T h i s p r o g r a m u s e s t e l l t o t e l l t h e f i l e p o i n t e r po s i t i on
* a ft e r a f i l e r ea d .
*I
#i n c l u d e < i o . h >
#i n c l u d e < s t d i o . h >
#i n c l u d e < f c n t l . h >
v o i d ma i n ( )
[
i nt f h ;
l on g p o s i t i on ;
c h a r buffe r [ 500 ] ;
c l os e ( f h ) ;
Output
C u r rent fi l e p o s i t i on i s : 4 2 5
tempnam, tmpnam 790
#include <Stdio.h>
Remarks The tmpnam function generates a temporary file name that can be used to open a tem
porary file without overwriting an existing file. This name is stored in string. If string is
NULL, then tmpnam leaves the result in an internal static buffer. Thus, any subsequent
calls destroy this value. If string is not NULL, it is assumed to point to an array of at least
L_tmpnam bytes (the value of L_tmpnam is defined in STDIO.H). The function will
generate unique file names for up to TMP_MAX calls.
The character string that tmpnam creates consists of the path prefix, defined by the entry
P_tmpdir in the file STDIO.H, followed by a sequence consisting of the digit characters
'O' through 9 ; the numerical value of this string can range from 1 to 65,535. Changing
' '
the definitions of L_tmpnam or P_tmpdir in STDIO.H does not change the operation of
tmpnam
The tempnam function allows the program to create a temporary file name for use in
another directory. This file name will be different from that of any existing file. The
prefix argument is the prefix to the file name. The tempnam function uses malloc to allo
cate space for the file name; the program is responsible for freeing this space when it is no
longer needed. The tempnam function looks for the file with the given name in the follow
ing directories, listed in order of precedence:
If the search through the locations listed above fails, tempnam returns the value NULL.
R1turn Value The tmpnam and tempnam functions both return a pointer to the name generated, unless
it is impossible to create this name or the name is not unique. If the name cannot be
created or if a file with that name already exists, tmpnam and tempnam return the value
NULL.
Compatibility tmpnam
tempnam
I* T E M P NAM . C : T h i s p r o g r a m u s e s tmp n a m t o c re a t e a un i q u e fi l e n a me i n
* t h e c u r r e n t wo r k i n g d i rectory , t h en u s e s temp n a m t o c re a t e a u n i q u e
* f i l e name w i t h a p r e f i x o f s t q .
*I
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
{
c h a r * n a me l , * n a me 2 ;
el se
p r i n t f ( " C a nnot c re a t e a u n i q u e f i l e n a me \ n " ) ;
Output
\ 2 i s s a fe t o u s e a s a tempo ra ry f i l e .
C : \ TM P \ s t q 2 i s s a f e t o u s e a s a tempora ry f i l e .
793 time
Rematks The time function returns the number of seconds elapsed since 00:00:00 Greenwich mean
time (GMT), January 1 , 1 970, according to the system clock. The system time is adjusted
according to the timezone system variable, which is explained in the tzset reference
section.
The return value is stored in the location given by timer. This parameter may be NULL, in
which case the return value is not stored.
Retum Value The time function returns the time in elapsed seconds. There is no error return.
I * CT I M E . C : T h i s p r o g r a m g e t s t h e c u r r e n t t i me i n t i me_t form , t h e n u s e s
* c t i me t o d i s p l a y t h e t i me i n s t r i n g form .
*/
#i n c l u d e < t i me . h >
#i n c l u d e < s t d i o . h >
v o i d ma i n ( )
(
t i me_t l t i me ;
t i me C & 1 t i me ) ;
p r i n t f C " T h e t i me i s % s \ n " , c t i me ( & l t i me ) ) ;
Output
T h e t i me i s T h u J u n 1 5 1 6 : 08 : 18 1 989
tmpfile 794
#include <Stdio.h>
Remarks The tmptile function creates a temporary file and returns a pointer to that stream. If the
file cannot be opened, tmptile returns a NULL pointer.
This temporary file is automatically deleted when the file is closed, when the program ter
minates normally, or when rmtmp is called, assuming that the current working directory
does not change. The temporary file is opened in w+b (binary read/write) mode.
Return Value If successful, the tmpfile function returns a stream pointer. Otherwise, it returns a NULL
pointer.
/ * TM P F I L E . C : T h i s p ro g r a m u s e s tmp f i l e to c re a t e a t empora ry f i l e ,
* t h en d e l e t e s t h i s f i l e w i t h rmtmp .
*I
v o i d ma i n ( )
(
F I LE *st ream ;
c h a r temp s t r i n g [ ] = " St r i n g t o be w r i t t en " ;
i nt i ;
/ * C r e a t e t empo r a ry f i l e s . * /
f o r C i = 1 ; i <= 1 0 ; i ++ >
(
i f ( ( s t r eam = tmp f i l e ( ) ) == N U L L )
p e r ro r ( " C o u l d n o t open n ew temp o r a ry f i l e \ n " > :
el se
p r i n t f ( " Temp o r a ry f i l e % d w a s c re a t ed \ n " , i > :
I * Remov e t empo ra ry f i l es . * /
795 tmpfile
Output
Temp o r a ry f i l e 1 wa s c r e a t ed
Tempo ra ry f i l e 2 wa s c re a t ed
Temp o r a ry f i l e 3 wa s c re a t ed
Tempo ra ry f i l e 4 wa s c r ea ted
Tempo ra ry f i l e 5 wa s c re a t ed
Tempo ra ry f i l e 6 wa s c re a t ed
Temp o r a ry f i l e 7 w a s c re a t ed
Temp o r a ry f i l e 8 wa s c r ea t ed
Tempo ra ry f i l e 9 wa s c re a t ed
Tempo ra ry f i l e 10 wa s c re a ted
1 0 temp o r a ry f i l e s d e l eted
toascii, tolower, toupper Functions 796
#include <ctype.h>
c Character to be converted
Remarks The toascii, tolower, _tolower, toupper, and _toupper routines convert a single charac
ter, as described below:
Function Description
The toascii routine sets all but the low-order 7 bits of c to 0, so that the converted value
represents a character in the ASCII character set. If c already represents an ASCII charac
ter, c is unchanged.
The tolower and _tolower routines convert c to lowercase if c represents an uppercase let
ter. Otherwise, c is unchanged. The _tolower routine is a version of tolower to be used
only when c is known to be uppercase. The result of _tolower is undefined if c is not an
uppercase letter.
The toupper and _toupper routines convert c to uppercase if c represents a lowercase let
ter. Otherwise, c is unchanged. The _toupper routine is a version of toupper to be used
only when c is known to be lowercase. The result of _toupper is undefined if c is not a
lowercase letter.
797 toascii, tolower, toupper Functions
Note that these routines are implemented both as functions and as macros. To conform
with the ANSI specification, the tolower and toupper routines are also implemented as
functions. The function versions can be used by removing the macro definitions through
#undef directives or by not including CTYPE.H. Function declarations of tolower and
toupper are given in STDLIB.H.
If the -Za compile option is used, the macro form of toupper or tolower is not used be
cause it evaluates its argument more than once. Since the arguments are evaluated more
than once, arguments with side effects would produce potentially bad results.
Return Value The toascii, tolower, _tolower, toupper, and _toupper routines return the converted char
acter c. There is no error return.
tolower, toupper
Exampm _________________________________________________________________
I * TOU P P E R . C : T h i s p r o g r a m u s e s t o u p p e r a n d t o l owe r to a n a l y z e a l l
* c h a r a c t e r s between 0x0 a n d 0x7 F . I t a l s o a pp l i e s _t o u p p e r a n d _t o l owe r
* t o a ny c o d e i n t h i s r a n g e f o r w h i c h t h e s e f u n c t i on s ma ke s en s e .
*I
#i n c l u d e < c o n i o . h >
#i n c l u d e < c ty p e . h >
#i n c l u d e < s t r i n g . h >
c h a r ms g [ ) = • some of TH E S E l et t e r s a r e Ca p i t a l s \ r \ n " ;
c h a r *p ;
v o i d ma i n ( )
(
c p ut s C m s g ) ;
toascii, tolower, toupper Functions 798
I * Rev e r s e c a s e of mes s a g e . * /
f o r e p = m s g ; p < m s g + s t r l en C m s g > : p++ )
(
i f ( i s l owe r C *p ) >
p u t c h C _t ouppe r C *p >:
e l s e i f ( i s uppe r C *p >
putc h C _t o l owe r C *p >:
el s e
putc h C *p > :
Output
Some of T H E S E l et t e r s a r e C a p i t a l s
s O M E O F t h e s e L ETT E RS A R E CAP I TA L S
199 tzset
Rematks The tmet function uses the current setting of the environment variable TZ to assign values
to three global variables: daylight, timezone, and tzname. These variables are used by the
ftime and localtime functions to make corrections from Greenwich mean time (GMT) to
local time, and by time to compute GMT from system time.
The value of the environment variable TZ must be a three-letter time-zone name, such as
PST, followed by an optionally signed number giving the difference in hours between
GMT and local time. The number may be followed by a three-letter daylight-saving-time
(DST) zone, such as PDT. For example, "PST8PDT" represents a valid TZ value for the
Pacific time zone. If DST is never in effect, as is the case in certain states and localities,
TZ should be set without a DST zone.
If the TZ value is not currently set, the default is PST8PDT, which corresponds to the
Pacific time zone.
Based on the TZ environment variable value, the following values are assigned to the vari
ables daylight, timezone, and tzname when tmet is called:
Variable Value
The default for daylight is I ; for timezone, 28,800; for tzname[O], PST; and for
tzname[ l ] , PDT. This corresponds to "PST8PDT."
If the DST zone is omitted from the TZ settings, the daylight variable will be 0 and the
ftime, gmtime, and localtime functions will return 0 for their DST flags.
tzset 800.
I * T Z S ET . C : T h i s p r o g r a m f i r s t s et s up t h e t i me zone by pl a c i ng t h e v a ri a b l e
* n a med TZ=EST5 i n t h e e n v i ronment t a b l e . I t t h en u s e s t z s et to s e t t h e
* g l oba l v a r i a b l e s n a med d a y l i g h t , t i me z o n e , a nd t z n a me .
*I
v o i d ma i n ( )
(
(
p r i n t f ( " U n a b l e to s et TZ \ n " > :
exi t ( 1 > :
I
el se
(
t z s et ( ) ;
pri ntf( " dayl i ght = %d\n " , dayl i ght > :
pri ntf ( " t i me z o n e = % l d \ n " , t i mezone > :
pri ntf( " t z n a me [ 0 ] = % s \ n " , t z n a me [ 0 ] > :
Output
d a y l i g ht = 1
t i mezone = 1 8000
t z n a me [ 0 ] = E ST
801 ultoa
Rematics The ultoa function converts value to a null-tenninated character string and stores the result
(up to 33 bytes) in string. No overflow checking is perfonned. The radix argument speci
fies the base of value; it must be in the range 2-36.
Return Value The ultoa function returns a pointer to string. There is no error return.
#i n c l u d e < s t d l i b . h >
#i n c l ude < s t d i o . h >
v o i d ma i n < >
(
c h a r b u f fe r [ 20 ] ;
i nt 1 = 344 5 ;
l on g l = -344 1 1 5 L ;
u n s i gned l on g u l 1 2 34567 890U L ;
=
i t oa { i , b u f fe r , 1 0 ) ;
pri ntf{ " St r i ng of i n t e g e r %d { r a d i x 1 0 ) : % s \ n " , i , b u f f e r > :
i t oa { i , b u f fe r , 1 6 ) ;
p r i ntf { " St r i n g of i n t e g e r %d { ra d i x 1 6 ) : 0x%s \ n " , i , buffer > :
i t oa { i , b u f fe r , 2 ) ;
p r i ntf { " St r i n g of i n t e g e r %d { ra d i x 2 ) : % s \ n " , i , b u f f e r > :
ultoa 802
l t oa C l , buffe r , 1 6 ) ;
p r i n t f ( " St r i ng o f l on g i n t % l d ( ra d i x 1 6 ) : 0x%s \ n • , 1 , buffer ) ;
u l t o a ( u l , buffe r , 1 6 ) ;
p r i n t f ( • st r i ng o f u n s i gned l on g % l u < ra d i x 1 6 ) : 0x% s \ n • , u l , buffer > :
Output
#include <Sys\types.h>
#include <Sys\stat.h>
#include <io.h> Required only for function declarations
Rsmatks The umask function sets the file-pennission mask of the current process to the mode
specified by pmode. The file-pennission mask is used to modify the permission setting of
new files created by creat, open, or sopen. If a bit in the mask is 1 , the corresponding bit
in 'the file's requested pennission value is set to 0 (disallowed). If a bit in the mask is 0, the
corresponding bit is left unchanged. The pennission setting for a new file is not set until
the file is closed for the first time.
The argument pmode is a constant expression containing one or both of the manifest con
they are joined with the bitwise-OR operator ( I ). The meaning of the pmode argument is
stants S_IREAD and S_IWRITE, defined in SYS\STAT.H. When both constants are given,
as follows:
Value Meaning
S_IREAD Reading not allowed (file is write-only)
S_IWRITE Writing not allowed (file is read-only)
For example, if the write bit is set in the mask, any new files will be read-only.
Note that under DOS and OS/2, all files are readable-it is not possible to give write-only
pennission. Therefore, setting the read bit with umask has no effect on the file's modes.
Rltum Va/us The umask function returns the previous value ofpmode. There is no error return.
v o i d ma i n ( )
{
i n t o l dma s k :
I * C r e a t e rea d - on l y f i l e s : * /
o l dma s k = uma s k C S_I W R I T E > :
p r i n t f ( " Ol dma s k = 0x% . 4x \ n " , o l dma s k > :
Output
O l dma s k = 0x0000
805 ungetc
#include <Stdio.h>
c Character to be pushed
stream Pointer to FILE structure
Remarks The ungetc function pushes the character c back onto stream and clears the end-of-file in
dicator. The stream must be open for reading. A subsequent read operation on the stream
starts with c. An attempt to push EOF onto the stream using ungetc is ignored. The
ungetc function returns an error value if nothing has yet been read from stream or if c can
not be pushed back.
Characters placed on the stream by ungetc may be erased if mush, fseek, fsetpos, or
rewind is called before the character is read from the stream. The file-position indicator
will have the same value it had before the characters were pushed back. On a successful
ungetc call against a text stream, the file-position indicator is unspecified until all the
pushed-back characters are read or discarded. On each successful ungetc call against a bi
nary stream, the file-position indicator is stepped down; if its value was 0 before a call, the
value is undefined after the call.
Results are unpredictable if the ungetc function is called twice without a read operation be
tween the two calls. After a call to the fscanf function, a call to ungetc may fail unless
another read operation (such as the getc function) has been performed. This is because the
fscanf function itself calls the ungetc function.
Return Value The ungetc function returns the character argument c. The return value EOF indicates a
failure to push back the specified character.
I * U N GETC . C : T h i s p r o g r a m f i rs t c o n v e r t s a c h a r a c t e r r e p r e s e n t a t i on of a n
* u n s i g n ed i n t e g e r t o a n i n tege r . I f t h e p r o g r a m e n c o u n t e r s a c h a r a c t e r
* t h a t i s n o t a d i g i t , t h e p r og r a m u s e s u n g e t c t o repl a c e i t i n t h e s t ream .
*I
ungetc 806
v o i d ma i n ( )
(
i nt c h ;
i nt resul t - 0 ;
p r i n t f C " En t e r a n i n te.ge r : • ) ;
I * Rea d i n a nd c o n v e rt n umbe r : * /
w h i l e ( C C c h - g e t c h a r ( ) ) I • EO F > && i s d i g i t ( c h > >
r e s u l t - re s u l t * 1 0 + c h - ' 0 ' ; / * U s e d i g i t . */
i f ( c h I• E O F )
ungetc C c h , s td i n ) ; / * Put n o n - d i g i t ba c k . * /
p r i n t f ( " N umber = %d \ n N ext c h a r a c t e r i n s t r e a m = ' %c ' \ n " ,
r e s u l t , g et c h a r C > ) ;
Output
DalJllptlan Pushes back the last character read from the console.
c Character to be pushed
R1111adtl The ungetch function pushes the character c back to the console, causing c to be the next
character read by getch or getche. The ungetch function fails if it is called more than once
before the next read. The c argument may not be EOF.
R""'m .Value The ungetch function returns the character c if it is successful. A return value of EOF indi
cates an error.
#i n c l u d e < c o n i o . h >
#i n c l u d e < c ty p e . h >
#i n c l u d e < s t d i o . h >
voi d ma i n ( )
(
c h a r buffe r [ 100 ] ;
i n t count - 0 ;
i nt ch ;
ungetch 808
c h = getche C l :
whi l e ( i sspace ( ch > / * S k i p p r e c ed i n g w h i t e s p a c e . * /
ch = getche C > :
whi l e ( count < 99 ) I* Gather token . */
(
i f ( i sspace C ch > I * End o f t o k e n . * /
brea k :
buffe r [ c o u n t++] = c h :
c h = g e t c he C l :
)
ungetch ( c h > : I * Put ba c k d e l i mi t e r . * /
buffe r [ c o u n t ] = ' \ 0 ' : / * N u l l t e rmi n a t e t h e t o k e n . * /
pri ntf( " \ ntoken = %s\n " , buffer > :
Output
W h i te
token = W h i t e
809 unlink
Retum Value If successful, unlink returns O; otherwise, it returns -1 and sets ermo to one of the follow
ing constants:
Value Meaning
v o i d ma i n ( )
{
i f ( u n l i n k ( " u n l i n k . obj " ) � -1 )
p e r ro r C " Co u l d n o t d e l ete ' U N L I N K . O BJ ' " > :
el se
p r i n t f C " De l eted ' U N L I N K . OBJ ' \ n " ) ;
Output
#include <graph.h>
Remarks The _unregisterfonts function frees memory previously allocated and used by the
_registerfonts function. The _unregisterfonts function removes the header information
for all fonts and unloads the currently selected font data from memory.
Any attempt to use the _setfont or _outgtext function after calling _unregisterfonts re
sults in an error.
#include <Sys\types.h>
#include <Sys\u�me.h>
Remarks The utime function sets the modification time for the file specified by filename. The
process must have write access to the file; otherwise, the time cannot be changed.
Although the utimbuf structure contains a field for access time, only the modification time
is set under DOS and OS/2 . If times is a NULL pointer, the modification time is set to the
current time. Otherwise, times must point to a structure of type utimbuf, defined in
SYS\UTIME.H. The modification time is set from the modtime field in this structure.
Return Value The utime function returns the value 0 if the file-modification time was changed. A return
value of -1 indicates an error, and errno is set to one of the following values:
Value Meaning
EACCES Path name specifies directory or read-only file
BBB Also asctime, ctime, fstat, ftime, gmtime, localtime, stat, time
I * U T I M E . C : T h i s p r o g r a m u s e s ut i me to s et t h e f i l e-mod i f i c a t i on t i me t o
* t h e c u r r e n t t i me .
*I
uli111e 812
v o i d ma i n ( )
{
I * S h ow fi l e t i me before a n d a ft e r . * /
s y s t e m ( " d i r ut i me . c " ) ;
i f ( u t i me C " u t i me . c " , N U L L ) == -1 )
p e r ro r C " u t i me fa i l ed \ n " ) ;
el se
p r i n t f ( " F i l e t i me mod i f i ed \ n " ) ;
s y s t e m ( " d i r u t i me . c " ) ;
Output
Remarks The va_arg, va_end, and va_start macros provide a portable way to access the arguments
to .a function when the function talces a variable number of arguments. Two versions of the
macros are available: the macros defined in STDARG.H confonn to the proposed ANSI C
standard, and the macros defined in VARARGS.H are compatible with the UNIX System
V definition. The macros are listed below:
Macro Description
Both versions of the macros assume that the function talces a fixed number of required ar
guments, followed by a variable number of optional arguments. The required arguments
are declared as ordinary parameters to the function and can be accessed through the param
eter names. The optional arguments are accessed through the macros in STDARG.H or
VARARGS.H, which set a pointer to the first optional argument in the argument list,
va_arg, va_end, va_start 814
retrieve arguments from the list, and reset the pointer when argument processing is
completed.
The proposed ANSI C standard macros, defined in STDARG.H, are used as follows:
1 . All required arguments to the function are declared as parameters in the usual way. The
va_dcl macro is not used with the STDARG.H macros.
2. The va_start macro sets arg_ytr to the first optional argument in the list of arguments
passed to the function. The argument arg_ytr must have va_list type. The argument
prev_yaram is the name of the required parameter immediately preceding the first
optional argument in the argument list. If prev_yaram is declared with the register
storage class, the macro's behavior is undefined The va_start macro must be used
before va_arg is used for the first time.
3. The va_arg macro does the following:
• Retrieves a value of type from the location given by arg_ytr
• Increments argytr to point to the next argument in the list, using the size of type to
determine where the next argument starts
The va_arg macro can be used any number of times within the function to retrieve ar
guments from the list.
4. After all arguments have been retrieved, va_end resets the pointer to NULL.
The UNIX System V macros, defined in VARARGS.H, operate in a slightly different man
ner, as follows:
1 . Any required arguments to the function can be declared as parameters in the usual way.
2. The last (or only) parameter to the function represents the list of optional arguments.
This parameter must be named va_alist (not to be confused with va_Iist, which is de
fined as the type of va_alist).
3. The va_dcl macro appears after the function definition and before the opening left
brace of the function. This macro is defined as a complete declaration of the va_alist
parameter, including the terminating semicolon; therefore, no semicolon should follow
va_dcl.
4. Within the function, the va_start macro sets argytr to the beginning of the list of op
tional arguments passed to the function. The va_start macro must be used before
va_arg is used for the first time. The argument arg_ytr must have va_list type.
5. The va_arg macro does the following:
• Retrieves a value of type from the location given by argytr
• Increments arg_ytr to point to the next argument in the list, using the size of type to
determine where the next argument starts
815 va_arg, va_end, va_start
The va_arg macro can be used any number of times within the function to retrieve the
arguments from the list.
6. After all arguments have been retrieved, va_end resets the pointer to NULL.
R""m Va/us The va_arg macro returns the current argument; va_start and va_end do not return values.
#i n c l u d e < s t d i o . h >
lld e f i n e ANS I / � C ommen t o u t f o r U N I X v e r s i on *I
Ii i fdef A N S I I * AN S I c ompa t i b l e v e r s i on *I
#i n c l u d e < s td a r g . h>
i nt a v e ra g e ( i n t f i r s t , ... );
llel s e I * U N I X c ompa t i b l e v e r s i o n *I
#i n c l u d e < v a ra r g s . h >
i nt a v e r a g e ( v a_l i s t ) ;
/le n d i f
v o i d ma i n ( )
{
I * C a l l w i t h 3 i nt e g e r s C - 1 i s u s ed a s t e rm i n a t o r ) . * /
p r i n t f ( " A v e r a g e i s : % d \ n " , a ve r a g e ( 2 , 3 , 4 , - 1 ) ) ;
I * C a l l w i t h 4 i nt e g e r s . * /
p r i n t f ( " Av e r a g e i s : % d \ n " , a v e r a g e ( 5 , 7 , 9 , 1 1 , - 1 > > ;
I * C a l l w i t h j u s t - 1 t e rmi n a t o r . * /
p r i n t f ( " Av e r a g e i s : % d \ n " , a v e r a ge ( - 1 > > ;
I * Ret u r n s t h e a v e ra g e o f a v a ri a b l e l i s t o f i n t e g e r s . * /
#i fdef A N S I / * A N S I c ompa t i b l e v e r s i on */
i n t a v e r a g e ( i nt f i r s t , >
{
. . •
i n t c o u n t = 0 , s um = 0 , i = f i r s t ;
v a_l i s t ma r k e r ;
va_arg, va_end, va_start a16
v a_s t a rt ( ma r k e r l ; / * I n i t i a l i ze v a r i a b l e a rgument s . * /
f o r ( s um = c o u n t = 0 ; ( i = v a_a rg ( ma r k e r , i n t ) ) ! = - 1 ; c o u n t++ )
s um += i ;
va_end ( ma r k e r ) ; / * Re s e t v a r i a bl e a rg umen t s . */
ret u r n < s um ? < s um I c o u n t ) 0 );
)
/len d i f
Output
Average i s : 3
Average i s : 8
Average i s : 0
817 vfprintf, vprintf, vsprintf
#include <Stdio.h>
#include <varargs.h> Required for compatibility with UNIX System V
Remarks The vfprintf, vprintf, and vsprintf functions format data and output data to the file
specified by stream, to standard output, and to the memory pointed to by buffer, respective
ly. These functions are similar to their counterparts fprintf, printf, and sprintf, but each
accepts a pointer to a list of arguments instead of an argument list.
Theformat argument has the same fonn and function as theformat argument for the printf
function; see printf for a description offormat.
The argptr parameter has type va_list, which is defined in the include files VARARGS.H
and STDARG.H. The argptr parameter points to a list of arguments that are converted and
output according to the corresponding fonnat specifications in the fonnat.
Return Value The return value for vprintf and vsprintf is the number of characters written, not counting
the tenninating null character. If successful, the vfprintf return value is the number of
characters written. If an output error occurs, it is a negative value.
/ * V P R I N T F . C s h ows h ow t o u s e v p r i n t f f u n ct i o n s t o w r i t e n ew v e r s i o n s
* o f p r i n t f . T h e v s p r i n t f f u n c t i on i s u s e d i n t h e exampl e .
*/
#i n c l u d e <stdi o . h>
#i n c l u d e <graph . h>
#i n c l u d e < s t r i ng . h >
#i n c l u d e < s td a rg . h>
#i n c l u d e <ma l l oc . h >
v o i d ma i n ( )
(
s h o rt fgd .. 0 ;
l on g bgd .. 0 L ;
I * Loop t h r o u g h 8 b a c k g ro u n d c o l o rs . * /
fo r ( b g d = 0 L ; b g d < 8 ; bgd++ >
(
wp r i n t f ( C i n t ) bgd · + 3 , 1 , 7 , bgd , " Ba c k : %d Fo re : " , bgd ) ;
/ * Loop t h r o u g h 1 6 f o r e g r o u n d col o r s . * /
fo r ( fgd = 0 ; fgd < 1 6 ; fgd++ >
wp r i n t f ( - 1 , - 1 , fgd , - l L , • % 2 d • , fgd ) ;
(
s t r u c t r c c o o r d tmppo s ;
s hort ret , s i z e ;
v a_l i s t ma r k e r ;
cha r *buffe r ;
819 vtprintf, vprintf, vsprintf
I * Set text p os i t i on . * /
tmppos - _g ettextpo s i t i on ( ) ;
i f ( row < 1 )
row = tmppos . row ;
i f ( co1 < 1 )
c o l - tmppos . c ol ;
_s ettextpos i t i on ( row , c o l > ;
I * Set f o r e g r o u n d a n d b a c k g round c o l o r s . * /
i f ( c l r >= Ill )
_s ett e x t c o l o r ( c l r ) ;
i f C be 1 r >· Ill )
_s etb k c o l o r ( b c l r ) ;
I * W r i te text to a s t r i n g a n d output t h e s t r i n g . */
va_s ta rt ( ma r k e r , fmt ) ;
ret = v s p r i n t f ( buffe r , fmt , ma r k e r ) ;
v a_en d ( ma r k e r > ;
_ou t t ext ( b u f f e r ) ;
f r e e ( buffer ) ;
r e t u r n ret ;
wait 820
#include <process.h>
R11matks The wait function suspends the calling process until any of the caller's immediate child
processes tenninate. If all of the caller's children have tenninated before it calls the wait
function, the function returns immediately.
If not NULL, termstat points to a buffer containing a tennination-status word and return
code for the child process. The status word indicates whether or not the child process
ended nonnally by calling the OS/2 DosExit function. Supply NULL if you do not need
the child's tennination-status word.
If the child process did tenninate nonnally, the low-order and high-order bytes of the
tennination-status word are as follows:
Byte Contents
Low order 0
High order Low-order byte of the result code passed by the child process
to DosExit. The DosExit function is called if the child
process c alled exit or _exit, if it returned from main, or if it
reached the end of main. The low-order byte of the result
code is either the low-order byte of the argument to _exit or
exit, the low-order byte of the return value from main, or a
random value if the child process reached the end of main.
Note that the OS/2 DosExit function allows programs to return a 1 6-bit result code. How
ever, the wait and cwait functions will return only the low-order byte of that result code.
821 wait
If the child process tenninated for any other reason, the high-order and low-order bytes of
the tennination-status word are as follows:
Byte Contents
Low order Tennination code from DosWait:
Code Meaning
1 Hard-error abort
2 Trap operation
Return Value If wait returns after nonnal tennination of a child process, it returns the child's process ID.
If wait returns after abnonnal tennination of a child process, it returns the number -1 and
sets ermo to EINTR.
Otherwise, wait returns -1 immediately and sets ermo to ECHILD, indicating that no
child processes exist for the calling process.
/ * WA I T . C : T h i s p r o g r a m l a un c h e s s ev e r a l c h i l d p r o c e s s e s a nd wa i t s for
* the f i r s t t o f i n i s h .
*I
#d e f i n e I N C L_NO P M
#d e f i n e I N C L_NOCOMMON
#d e f i n e I N C L_DO S P RO C E S S
#i n c l u d e < o s 2 . h > / * D o s S l eep */
#i n c l u d e < p ro c e s s . h > / * wa i t */
#i n c l u d e < s t d l i b . h >
#i n c l u d e < s td i o . h >
#i n c l u d e < t i me . h >
wait 822
I * M a c r o t o get a r a n d om i n t e g e r w i t h i n a s p ec i f i ed r a n g e */
#d ef i n e g e t r a ndom C mi n , max > C C ra nd C l % C i nt > C C C ma x ) + 1 ) C mi n ) ) ) + ( mi n ) )
-
s t ruct C H I LD
(
i nt pi d ;
cha r n a me [ l 0 J ;
c h i l d [ 4 ] = ( ( 0 , " An n • J , ( 0 , " Be t h " J , ( 0 , " C a r l • J , ( 0 , " Da v e • J J ;
v o i d ma i n ( i n t a r g c , c h a r *a rg v [ J
(
i nt t e rms t a t , p i d , c , tmp ;
I * Spawn c h i l d r en i n ra ndom o r d e r w i t h a r a n d om d e l ay . * /
t m p = get r a n d o m C 0 , 3 > :
fo r e c = tmp ; c < tmp + 4 ; c++ >
chi l d[c % 4] .pid s p a w n l C P_N DWA I T , a rg v [ 0 ] , a rg v ( 0 ] ,
=
c h i l d [ c % 4 ] . n ame , N U L L > :
I * Wa i t f o r t h e f i r s t c h i l d ren . O n l y get I D of f i r s t . * /
p r i n t f C " W h o ' s f i rs t ? \ n " > :
p i d = wa i t ( & t e rm s t a t > :
fo r ( c = 0 ; c < 3 ; c++ )
wa i t ( & t e rms t a t > :
I * C h e c k I D s t o s ee w h o wa s fi r s t . * /
fo r ( c - 0 ; c < 4 ; c++ )
i f ( pi d =- chi l d[cJ .pid >
p r i n t f C " %s wa s fi r s t \ n \ n " , c h i l d [ c J . n ame > :
I * I f t h e r e a re a rg ument s , t h i s must be a c h i l d . * /
el s e
(
/ * Del ay f o r r a n d om t i me . * /
s ra n d C C u n s i g n ed ) t i me C N U L L > * a rg v [ l ] [0 J > :
Dos S l eep C g e t r a n d o m C l , 5 ) * 1000L > :
p r i n t f C " H i , d a d . I t ' s % s . \ n " , a rg v [ l ] > :
823 wait
Output
#include <graph.h>
Remades The _wrapon function controls whether text output with the _outtext function wraps to a
new line or is simply clipped when the text output reaches the edge of the defined text win
dow. The option argument can be one of the following manifest constants:
Constant Meaning
_GWRAPOFF Truncates lines at window border
Note that this function does not affect the output of presentation-graphics routines or font
routines.
Return Value The function returns the previous value of option. There is no error return.
Examp• ��������---
1 * W RAPON . C * /
#i n c l u d e < c o n i o . h >
#i n c l u d e < g r a p h . h >
v o i d ma i n ( )
{
_w r a pon ( _GW RA P O N ) ;
w h i l e ( ! kb h i t ( ) )
_out t e x t < " W r a p o n ! • );
getc h ( ) ;
_o uttext '< " \ n \ n " ) ;
w r a p o 7 < GWRA P O F F ) ;
w h i l e < , ! kb h i t ( ) >
I
12s _wrapon
outtex t ( " W r a p o f f !
_ • );
getc h ( l ;
_outtext ( " \ n \ n " ) ;
Output
W r a p o n ! W r a p on ! W r a p on ! W r a p on ! W r a p on ! Wra p on ! Wra p on ! W r a p
on ! W r a p on ! W r a p on ! W r a p on ! W r a p on ! W r a p on ! W r a p on ! W r a p on !
W r a p on ! W r a p on ! W r a p on ! W r a p on ! W r a p on ! W r a p on ! W ra p on ! W r
a p on ! Wra p on ! Wra p on ! Wra p on ! W r a p on ! W r a p on ! W r a p on ! W r a p o
n ! W r a p on ! W r a p on !
Remadrs The write function writes count bytes from buffer into the file associated with handle. The
write operation begins at the current position of the file pointer (if any) associated with the
given file. If the file is open for appending, the operation begins at the current end of the
file. After the write operation, the file pointer is increased by the number of bytes actually
written.
Retum Value The write function returns the number of bytes actually written. The return value may be
positive but less than count (for example, when write runs out of disk space before count
bytes are written).
A return value of 1 indicates an error. In this case, errno is set to one of the following
-
values:
Value Meaning
If you are writing more than 32K (the maximum size for type int) to a file, the return value
should be of type unsigned int. (See the example that follows.) However, the maximum
number of bytes that can be written to a file at one time is 65,534, since 65,535 (or
OxFFFF) is indistinguishable from -1 and would return an error.
If the file is opened in text mode, each line-feed character is replaced with a carriage
return-line-feed pair in the output. The replacement does not affect the return value.
When writing to files opened in text mode, the write function treats a CTRL+Z character as
the logical end-of-file. When writing to a device, write treats a CTRL+Z character in the
buffer as an output terminator.
827 write
I * W R I T E . C : T h i s p r o g r a m opens a f i l e f o r output a nd u s e s w r i te t o
* w r i te s ome b y t e s to t h e f i l e .
*I
v o i d ma i n ( )
(
i nt fh ;
u n s i gned byt e sw r i tten ;
c l os e < f h l ;
Output
Wrote 3 5 byt e s to fi l e
Index
A jOj l jn, 1 07
jOl,j l l ,jnl, 1 07
abort, 5 1 , 76 yO,y l ,yn, 1 07
abs, 78 _yOl,_y l l ,_ynl, 1 07
Absol ute value _bexpand, 260
abs, 78 _bfree, 3 1 0
cabs, 1 34 _bfreeseg, 1 1 0
cabsl, 1 34 _bheapadd, 406
fabs, 263 _bheapchk, 409
fabsl, 263 _bheapmin, 4 1 1
labs, 44 1 _bheapseg, 1 1 2
access, 24, 80 _bheapset, 4 1 2
·Access 1node, 269, 295, 3 1 5, 326 _bheapwalk, 4 1 5
acos, 46, 82 B inary
acosl, 46, 82 fonnat, conversion to IEEE
alloca, 48, 84 double precision, 1 8 1
Allocation. See Memory allocation int
_amblksiz variable, 63 reading, 389
Appending writing, 597
constants, 523, 704 mode
streams, 295 , 3 1 5 , 326 _fmode, 66
_arc, _arc_w, _arc_wxy fdopen, 269
description, 86 fopen, 296
use, 30 freopen, 3 1 5-3 1 6
Arccosine function, 82 _fsopen, 327
Arcsine function, 90 open, 523
Arctangent function, 94 setmode, 664
Arguments sopen, 704
singularity, 480 vs. text mode, 35
type checking, vi search, 1 32, 447, 466
variable-length number, 62, 8 1 7 BINMODE.OBJ, 66
asctime, 60, 88 _bios_disk, 57, 1 1 5
asin, 46, 90 _bios_equipl ist, 57, 1 1 9
asinl , 46, 90 _bios_keybrd, 57, 1 2 1
assert, 92 _bios_memsize, 57, 1 24
Assertions, 92 _bios_printer, 57, 1 25
atan, atan2, 46, 94 _bios_serialcom, 57, 1 27
atanl, atan21, 46, 94 _bios_timeofday, 57, 1 30
atexit, 5 1 , 96 _bmalloc, 476
atof, atoi, atol, _atold, 22, 98 _bmsize, 5 1 9
Attributes, 29 Bold type, use of, ix
8
Brackets, double, use of, ix
_brealloc, 607
bsearch, 55, 1 32
_bcal loc, 1 3 6 B uffer manipulation
bdos, 5 7 , I O I _fmemccpy, 487
_beginthread, I 03 _fmemchr, 489
Bessel functions _fmemcmp, 49 1
/ described, 48, 1 07 _fmemcpy, 494
829
830 Microsoft C Run-Time Library Reference
c Child process
cw a it
cabs, 46, 1 34 s ignal settings, 707
cabsl, 46, 1 34 termination-status word, 1 77, 707, 820
calloc, 48, 1 36 exec, 25 1
Carry flag floating-point state of p arent, 300
bdos, 1 0 1 s pawn, 707
int86, 426 wait, 820
int86x, 428 chmod, 24, 1 49
intdos, 430 chsize, 24, 1 5 1
intdosx, 432 _clear87, 46, 1 53
Case in file names, 9 clearerr, 37, 1 5 5
cei l , 46, 1 38 _clearscreen, 29, 1 57
Ceil ing function, 1 38 C l i pp ing regions, 650
ceil l , 46, 1 38 clock, 60, 1 59
_cexit, _c_exit, 1 40 clock_t type, 68
cgets, 44, 1 4 1 close, 42, 1 6 1
_chain_intr, 57, 60, 1 43 Comp arison
Character classification and conversion functions max macro, 484
include files, 22 min macro, 506
isalnum, 2 1 , 434 Compatibility mode, 704
iscntrl , 434 com p lex ty pe, 68
isdigit, 434 CONIO.H, 44
isgraph, 434 Console, ungetting characters from, 807
islower, 2 1 , 434 _control87, 46, 1 63
isprint, 2 1 , 434
ispunct, 2 1 , 434
Index 831
F
fgetpos, 280
fseek, 322
fsetpos, 324
fabs, 46, 263 ftell, 332
fabsl, 46, 263 lseek, 468
Far pointers, 298 read and write operations, 43
_fcalloc, 1 36 rewind, 622
fclose, fcloseall, 37, 265 tell, 788
fcvt, 22, 267 File status information, 329, 723
fdopen, 37, 269 filelength, 24, 285
feof, 37, 272 fileno, 37, 287
ferror, 37, 274 Files
_fexpand, 260 changing size, 1 5 1
fflush, 37, 276 closing, 43, 1 6 1
_ffree, 48, 3 1 0 creating, 1 7 1 , 523, 704
834 Microsoft C Run-Time Library Reference
M
use, 6
Library routines, calling, 5
Lines
reading, 282, 376 _makepath, 473
writing, 596 Macros, 1 0- 1 2
_Iineto, 30, 449 malloc, 49, 476
_Iineto_w, 30, 449 MALLOC.H, 48
Local time corrections, 64, 454, 799 Mask. See Permission setting
localeconv, 45 1 MATH.H, 22, 46
Localization matherr
localeconv, 45 1 described, 480
setlocale, 662 use, 47
localtime, 6 1 , 454 _matherrl, 480
locking, 24, 456 max, 484
log, log 10, 459 _memavl , 49, 485
Logarithmic functions, 47, 459 memccpy, 20, 487
log!, log I OI, 459 memchr, 20, 489
long double functions, 46 1 memcmp, 20, 49 1
Long integers, conversion to strings, 47 1 memcpy, 20, 494
longjmp, 463 memicmp, 20, 497
Low-level graphics _memmax, 49, 499
See also individualfunction names memmove, 20, 50 1
color selection, 28-29 Memory allocation
configuration, 26 _amblksiz, 63
coordinates, 26 available memory, determination, 3 1 3
font functions. See Fonts _bcalloc, 1 36
image transfer, 3 1 _bfree, 3 1 0
output _bfreeseg, 1 1 0
_arc, _arc_w, _arc_wxy, 30, 86 _bheapadd, 406
_ellipse, _ellipse_w, _ellipse_wxy, 30, 245 _bheapchk, 409
_getarcinfo, 344 _bheapmin, 41 1
_getwritemode, 392 _bheapseg, 1 1 2
_grstatus, 396 _bheapset, 41 2
_lineto, _lineto_w, 30, 449 _bheapwalk, 4 1 5
_pie, _pie_ w, _pie_ wxy, 30, 567 _bmalloc, 476
_pol ygon, _pol ygon_w, _pol ygon_wxy, 574 _bmsize, 5 1 9
838 Microsoft C Run-Time Library Reference
N
_expand, 260
_fcalloc, 1 36
_ffree, 3 1 0
_fueapchk, 409 _ncalloc, 1 36
_fueapmin, 4 1 1 NDEBUG, 92
_fueapset, 4 1 2 _nexpand, 260
_fueapwalk, 4 1 5 _nfree, 48, 3 1 0
_fmalloc, 476 _nheapchk, 48, 409
_fmsize, 5 1 9 _npeapmin, 4 1 1
_frealloc, 607 _nileapset, 49, 4 1 2
free, 3 1 0 _nheapwalk, 49, 4 1 5
_freect, 3 1 3 _nmalloc, 49, 476
halloc, 400 _nmsize, 49, 5 1 9
_heapadd, 406 Nonlocal goto, 463, 660
_heapchk, 409 _nrealloc, 607
_heapmin, 4 1 1 _nstrdup, 740
_heapset, 4 1 2 Null pointer, 37
_heapwalk, 4 1 5
hfree, 4 1 9
malloc, 476
0
_memavl, 485 Object (.OBJ) files, 6
O_BINARY, 66
oflag. See Open flag
.:.memmax, 499
_msize, 5 1 9
_ncalloc, 1 36 onexit, 52, 52 1
_nfree, 3 1 0 open, 8, 42, 523
_nheapchk, 409 Open flag, 523, 704
_nheapmin, 41 1 Operating system, 1 4
_nheapset, 4 1 2 Optional items, ix
_nheapwalk, 4 1 5 _osmajQr variable, 67
_nmalloc, 476 _osminor variable, 67
_nmsize, 5 1 9 _outgtext, 32, 527
_nrealloc, 607 _outmem, 530
realloc, 607 outp, outpw, 44-45, 532
routines and uses (list), 48 Output. See 1/0
stackavail, 722 _outtext, 3 1 , 535
MEMORY.ff, 20 OVERFLOW, 480
memset, 20, 504 Overlapping moves, 494
Microsoft Windows, 25 Overlay, of parent process, 707
min, 506
mkdir, 23, 507
mktemp, 24, 509
p
mktime, 6 1 , 5 1 1 Palettes, low-level, 28
Model-independent memory routines, 20 Parameters, variable-length number, 62, 8 1 7
modf, 47, 5 1 3 Parent process
modfl, 47, 5 1 3 cwait, 1 77
Modification time, 8 1 1 described, 25 1
Monofont, use of, x overlay and suspension, 707
movedata, 5 1 5 wait, 820
_moveto, 30, 5 1 7 Path names, 9
Index 839
!>L
_pg_analyzechartms, 34, 540 signal, 52, 696
_ analyzepie, 34, 543 spawn family, 53
_pg_analyzescatter, 34, 544 system, 53, 784
_pg_analyzescattenns, 34, 544 wait, 820
_pg_chart, 33, 546 Process ID, 373
_pg_chartms, 33, 546 PROCESS.ff, 5 1
_pg_chartpie, 33, 549 Processor calls, include files, 6 1
_pg_chartscatter, 33, 550 Program segment prefix (PSP), 68
_pg_chartscattenns, 33, 550 Pseudorandom integers, 603, 7 1 8
_pg_defaultchart, 33, 552 _psp, 68
_pg_getchardef, 34, 554 putc, putchar, 38, 589
_pg_getpalette, 34, 555 putch, 44, 59 1
_pg_getstyleset, 34, 558 putenv, 592
_pg_hlabelchart, 34, 559 _putimage, _putimage_w, 32, 594
_pg_initchart, 33, 560 puts, 38
_pg_resetpalette, 34, 56 1 putw, 38, 597
_pg_resetstyleset, 34, 562
_pg_setchardef, 34, 563
_pg_setpalette, 34, 564
Q
_pg_setstyleset, 34, 565 qsort, 55, 599
_pg_vlabelchart, 34, 566 Quick sort algorithm, 599
_pie , _pie_w, _pie_wxy, 30, 567 Quotation marks, use of, x
_pipe, 570
Pipes ·
_pclose, 537
R
_pipe, 570 raise, 52, 60 I
_popen, 576 rand, 603
PLOSS, 480 Random access
Pointers, long, 298 fgetpos, 280
_po lygon, _polygon_w, _polygon_wxy, 574 fseek, 322
_popen, 576 fsetpos, 324
Port l/O. See 1/0, console and port ftell, 332
pow, 47, 578 lseek, 468
Predefined rewind, 622
handles, 43 tell, 788
stream pointers, 39 Random number generator, 603, 7 1 8
types. See Standard types read, 42, 605
printf, 38, 580 Read access. See Pennission setting
Printing. See Write operations
840 Microsoft C Run-Time Library Reference
Strings SYS\TIMEB.H, 6 1
comparing, 73 1 , 733, 744, 746, 754, 758 SYS\TYPES, 6 1
concatenating, 752 SYS\UTIME.H, 6 1
converting sys_errlist
to floating-point values, 98 described, 65
to lowercase, 750 system error messages, 538, 742
to uppercase, 780 sys_nerr, 65, 538, 742
copying, 734, 740, 756 system, 53, 784
initializing, 759, 767 System calls. See DOS system calls
reading from console, 1 4 1 System time. See Time
T
reversing, 765
searching
_fstrchr, 729
_fstrcspn, 736 tan, tanh, 47, 786
_fstrpbrk, 76 1 Tangent, 786
_fstrrchr, 763 tan!, tanhl, 47, 786
_fstrspn, 769 tell, 42, 788
_fstrstr, 77 1 tempnam, tmpnam, 38, 790
_fstrtok, 778 Terminal capabilities, 437
strchr, 729 Text mode
strcspn, 736 vs. binary, 35
strpbrk, 76 1 described, 66, 523
strrchr, 763 setmode, 664
strspn, 769 sopen, 704
strstr, 77 1 stream 1/0, 269, 296, 3 1 5, 327
strtok, 778 Threads
writing _beginthread, 103
to console, 1 68, 1 70 DosExit, 248
to stream, 307 _endthread, 248
strlen, 56 termination, 248
strlwr, 56, 750 Time ·
w
tmpnam, 790
toascii, 2 1 , 796
Tokens, finding in strings, 778
wait, 820
Word. See Binary, int
_tolower, _toupper, 2 1 , 796
tolower, toupper, 2 1 , 796
_toupper, 796 _wrapon, 3 1 , 824
Trigonometric functions write, 42, 826
acos, 82 Write access. See Permission setting
acosl, 82 Write operations
asin, 90 binary int value to stream, 597
asinl, 90 character
atan, atan2, 94 to console, 1 68
atanl, atan21, 94 to file, 826
cos, cosh, 1 66 to stdout, 305, 589
hypot, 42 1 to stream, 305, 589, 805
hypotl, 42 1 to console, 1 69, 1 70, 59 1
sin, sinh, 702 data items from stream, 338
sinl, sinhl, 702 formatted
tan, tanh, 786 cprintf, 1 68
tanl, tanhl, 786 printf, 580
Type checking sprintf, 7 1 5
function declarations, 7-8 stream 1/0, 303
include files, 7 vprintf, 8 1 7
variable arguments, 8 line to stream, 596
TZ environment variable to port, 532
default value, 64 string to stream, 307
focaltime, 454
tzset, 799
tzname variable, 64, 799
x
tzset, 799 XENIX, 9
u y
ultoa, 23, 801 yO, y l , yn, 1 07
umask, 24, 803 _yOI , _y l l, _ynl, 1 07
UNDERFLOW, 48 1
UNIX, 9
ungetc, 39, 805
ungetch, 44, 807
Universal Coordinated Time, 6 1
unlink, 24, 809
_unregisterfonts, 32, 8 1 0
. ... . .
· : -- . •
,. _ ,.
... .
,.
... �r .
. -;· .
: .
- �· :
- . :_.'--
: ·: ,
.··
· _· · , , · ·
,:· ·
. \" · ._; · "
' . .. .... . :.. . ·
. �....
.� - ·.
,;"
. . -. :,;
' . ·
' - : .. _
. . . -�,
•ictosottI.Jniversity'
Training That Makes Sense
At Microsoft University, we believe the proof of excellent PLOT YOUR OWN COURSE
training is in a student's ability to apply it. That' s not a Our curriculum allows you to customize your course of
complicated philosophy. And, it's not a new idea. But it study from timely, fundamental courses for support
does represent an uncommon approach to training in the personnel to highly focused, technical courses for sophisti
'
microcomputer industry, mainly because it requires cated developers . We offer courses on Microsoft Windows;"
extensive technical and educational resources, as well as Microsoft OS/2, Microsoft OS/2 Presentation Manager,
leading-edge programming expertise. Microsoft LAN Manager, Microsoft SQL Server, and
When you attend Microsoft University, our courses Microsoft C.
take you to the heart of our microcomputer software
architecture. Lab sessions provide practical, hands-on TIME IS OF THE ESSENCE
experience and show you how to develop and debug soft To find out more about Microsoft University, call our
ware more efficiently. Our qualified instructors explain the registrar at (206) 867-5507, extension 605 . We 'll send you
philosophy and principles that drive our systems designs. our current course schedule, which describes our courses in
detail and provides complete registration information for our
OUR LAB-BASED DISTINCTION campus facilities in Seattle, Boston, and Baltimore, as well
Because our courses are lab-based, when you graduate from as our growing, nationwide network of Microsoft University
Microsoft University, you 'll begin applying what you 've Authorized Training Centers.
learned immediately. Throughout our courses, you'll be de Microsoft University also offers our courses on-site at
signing a software application that demonstrates the your location, when it's convenient for you and your staff.
principles you've just learned in class. To find out more about hosting an on-site course, contact
The power of our sheepskin pays off in the increased the Microsoft University Sales Manager at (206) 867-5507,
knowledge and time savings as soon as you begin your next extension 605 .
development project. Our courses fill up quickly-so don't delay.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Job Title!Fu11ction:
Street Address:
0 Please send me more information on the following Microsoft City: State: Zip
X605
2'.·
-;. . . " ·
. �:· . �._ � .
;: : · ; ·_;
Other Titles from Microsoft Press