layout | title | permalink |
---|---|---|
page |
MS C 6.0 Run-Time Library Reference |
/pubs/pc/reference/microsoft/mspl13/c/clibref/ |
{% raw %}
Microsoft C - RUN-TIME LIBRARY REFERENCE
────────────────────────────────────────────────────────────────────────────
Microsoft (R) C - RUN-TIME LIBRARY REFERENCE
FOR THE MS-DOS (R)
OPERATING SYSTEM
────────────────────────────────────────────────────────────────────────────
MICROSOFT CORPORATION
PUBLISHED BY
Microsoft Press
A Division of Microsoft Corporation
One Microsoft Way, Redmond, Washington 98052-6399
Copyright (C) 1990 by Microsoft Press
All rights reserved. No part of the contents of this book may be reproduced
or transmitted in any form or by any means without the written permission of
the publisher.
Library of Congress Cataloging-in-Publication Data
Microsoft C run-time library reference.
Includes index.
1. C (Computer program language) 2. Microsoft C
(Computer program) 3. Macro instructions (Electronic
computers) I. Microsoft.
QA76.73.C15M52 1990 005.13'3 89-12240
ISBN 1-55615-225-6
Printed and bound in the United States of America.
1 2 3 4 5 6 7 8 9 HCHC 3 2 1 0 9
Distributed to the book trade in Canada by General Publishing Company, Ltd.
Distributed to the book trade outside the United States and Canada by
Penguin
Books Ltd.
Penguin Books Ltd., Harmondsworth, Middlesex, England
Penguin Books Australia Ltd., Ringwood, Victoria, Australia
Penguin Books N.Z. Ltd., 182-190 Wairau Road, Auckland 10, New Zealand
British Cataloging in Publication Data available.
Sample
Writers: Editors: Programs:
Phil Nelson Amanda Clark Bruce McKinney
Terry Ward Moira Macdonald
Marjorie Manwaring
Bill Nolan
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 registered trademark of Hercules Computer
Technology.
IBM is a registered trademark of International Business
Machines Corporation.
Olivetti is a registered trademark of Ing. C. Olivetti.
Document No. 410840021-520-R00-1088
Part No. 04412
Table of Contents
────────────────────────────────────────────────────────────────────────────
Introduction
About the C Run-Time Library
ANSI C Compatibility
OS/2 and XENIX(R) Programming
Expanded Graphics Library
About This Book
Other Books of Interest
Document Conventions
PART I Overview
────────────────────────────────────────────────────────────────────────────
Chapter 1 Using C Library Routines
1.1 Calling Library Routines
1.2 Using Header Files
1.2.1 Including Necessary Definitions
1.2.2 Including Function Declarations
1.3 File Names and Path Names
1.4 Choosing Between Functions and Macros
1.5 Stack Checking on Entry
1.6 Handling Errors
1.7 Operating-System Considerations
1.8 Floating-Point Support
1.9 Using Huge Arrays with Library Functions
Chapter 2 Run-Time Routines by Category
2.1 Buffer Manipulation
2.2 Character Classification and Conversion
2.3 Data Conversion
2.4 Directory Control
2.5 File Handling
2.6 Graphics
2.6.1 Low-Level Graphics and Character-Font Functions
2.6.2 Presentation-Graphics Functions
2.7 Input and Output
2.7.1 Text and Binary Modes
2.7.2 Stream Routines
2.7.3 Low-Level Routines
2.7.4 Console and Port I/O
2.8 Internationalization
2.9 Math
2.10 Memory Allocation
2.10.1 Near and Far Heaps
2.10.2 Based Heaps
2.11 Process and Environment Control
2.12 Searching and Sorting
2.13 String Manipulation
2.14 System Calls
2.14.1 BIOS Interface
2.14.2 DOS Interface
2.15 Time
2.16 Variable-Length Argument Lists
Chapter 3 Global Variables and Standard Types
3.1 _amblksiz
3.2 daylight, timezone, tzname
3.3 _doserrno, errno, sys_errlist, sys_nerr
3.4 _fmode
3.5 _osmajor, _osminor, _osmode, _osversion
3.6 environ
3.7 _psp
3.8 Standard Types
PART II Run-Time Functions
────────────────────────────────────────────────────────────────────────────
About the Run-Time Reference
abort
abs
access
acos Functions
alloca
_arc Functions
asctime
asin Functions
assert
atan Functions
atexit
atof, atoi, atol, _atold
bdos
_beginthread
Bessel Functions
_bfreeseg
_bheapseg
_bios_disk
_bios_equiplist
_bios_keybrd
_bios_memsize
_bios_printer
_bios_serialcom
_bios_timeofday
bsearch
cabs, cabsl
calloc Functions
ceil, ceill
_cexit, _c_exit
cgets
_chain_intr
chdir
_chdrive
chmod
chsize
_clear87
clearerr
_clearscreen
clock
close
_control87
cos Functions
cprintf
cputs
creat
cscanf
ctime
cwait
dieeetomsbin, dmsbintoieee
difftime
_displaycursor
div
_dos_allocmem
_dos_close
_dos_creat Functions
_dos_find Functions
_dos_freemem
_dos_getdate
_dos_getdiskfree
_dos_getdrive
_dos_getfileattr
_dos_getftime
_dos_gettime
_dos_getvect
_dos_keep
_dos_open
_dos_read
_dos_setblock
_dos_setdate
_dos_setdrive
_dos_setfileattr
_dos_setftime
_dos_settime
_dos_setvect
_dos_write
dosexterr
dup, dup2
ecvt
_ellipse Functions
_enable
_endthread
eof
exec Functions
exit, _exit
exp, expl
_expand Functions
fabs, fabsl
fclose, fcloseall
fcvt
fdopen
feof
ferror
fflush
fgetc, fgetchar
fgetpos
fgets
fieeetomsbin, fmsbintoieee
filelength
fileno
_floodfill, _floodfill_w
floor, floorl
flushall
fmod, fmodl
fopen
FP_OFF, FP_SEG
_fpreset
fprintf
fputc, fputchar
fputs
fread
free Functions
_freect
freopen
frexp, frexpl
fscanf
fseek
fsetpos
_fsopen
fstat
ftell
ftime
_fullpath
fwrite
gcvt
_getactivepage
_getarcinfo
_getbkcolor
getc, getchar
getch, getche
_getcolor
_getcurrentposition Functions
getcwd
_getdcwd
_getdrive
getenv
_getfillmask
_getfontinfo
_getgtextextent
_getimage Functions
_getlinestyle
_getphyscoord
getpid
_getpixel Functions
gets
_gettextcolor
_gettextcursor
_gettextposition
_gettextwindow
_getvideoconfig
_getviewcoord Functions
_getvisualpage
getw
_getwindowcoord
_getwritemode
gmtime
_grstatus
halloc
_hard Functions
_heapadd Functions
_heapchk Functions
_heapmin Functions
_heapset Functions
_heapwalk Functions
hfree
hypot, hypotl
_imagesize Functions
inp, inpw
int86
int86x
intdos
intdosx
is Functions
isatty
itoa
kbhit
labs
ldexp, ldexpl
ldiv
lfind
_lineto Functions
localeconv
localtime
locking
log Functions
long double Functions
longjmp
_lrotl, _lrotr
lsearch
lseek
ltoa
_makepath
malloc Functions
matherr, _matherrl
max
_memavl
memccpy, _fmemccpy
memchr, _fmemchr
memcmp, _fmemcmp
memcpy, _fmemcpy
memicmp, _fmemicmp
_memmax
memmove, _fmemmove
memset, _fmemset
min
mkdir
mktemp
mktime
modf, modfl
movedata
_moveto Functions
_msize Functions
onexit
open
_outgtext
_outmem
outp, outpw
_outtext
_pclose
perror
_pg_analyzechart Functions
_pg_analyzepie
_pg_analyzescatter Functions
_pg_chart Functions
_pg_chartscatter Functions
_pg_chartpie
_pg_defaultchart
_pg_getchardef
_pg_getpalette
_pg_getstyleset
_pg_hlabelchart
_pg_initchart
_pg_resetpalette
_pg_resetstyleset
_pg_setchardef
_pg_setpalette
_pg_setstyleset
_pg_vlabelchart
_pie Functions
_pipe
_polygon Functions
_popen
pow Functions
printf
putc, putchar
putch
putenv
_putimage Functions
puts
putw
qsort
raise
rand
read
realloc Functions
_rectangle Functions
_registerfonts
_remapallpalette, _remappalette
remove
rename
rewind
rmdir
rmtmp
_rotl, _rotr
scanf
_scrolltextwindow
_searchenv
segread
_selectpalette
_setactivepage
_setbkcolor
setbuf
_setcliprgn
_setcolor
_setfillmask
_setfont
_setgtextvector
setjmp
_setlinestyle
setlocale
setmode
_setpixel Functions
_settextcolor
_settextcursor
_settextposition
_settextrows
_settextwindow
setvbuf
_setvideomode
_setvideomoderows
_setvieworg
_setviewport
_setvisualpage
_setwindow
_setwritemode
signal
sin Functions
sopen
spawn Functions
_splitpath
sprintf
sqrt, sqrtl
srand
sscanf
stackavail
stat
_status87
strcat, _fstrcat
strchr, _fstrchr
strcmp, _fstrcmp
strcmpi
strcoll
strcpy, _fstrcpy
strcspn, _fstrcspn
_strdate
strdup Functions
strerror, _strerror
strftime
stricmp, _fstricmp
strlen, _fstrlen
strlwr, _fstrlwr
strncat, _fstrncat
strncmp, _fstrncmp
strncpy, _fstrncpy
strnicmp, _fstrnicmp
strnset, _fstrnset
strpbrk, _fstrpbrk
strrchr, _fstrrchr
strrev, _fstrrev
strset, _fstrset
strspn, _fstrspn
strstr, _fstrstr
_strtime
strtod, strtol, _strtold, strtoul
strtok, _fstrtok
strupr, _fstrupr
strxfrm
swab
system
tan Functions
tell
tempnam, tmpnam
time
tmpfile
toascii, tolower, toupper Functions
tzset
ultoa
umask
ungetc
ungetch
unlink
_unregisterfonts
utime
va_arg, va_end, va_start
vfprintf, vprintf, vsprintf
wait
_wrapon
write
Index
Introduction
────────────────────────────────────────────────────────────────────────────
The Microsoft(R) 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 programming easier by providing
■ Fast and efficient routines to perform common programming tasks (such
as string manipulation), sparing you the time and effort needed to
write such routines
■ Reliable methods of performing operating-system functions (such as
opening and closing files)
The C run-time library is important because it provides basic functions not
provided 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(R) OS/2) and IBM(R) OS/2.
Similarly, the term "DOS" refers to both the MS-DOS(R) 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.
────────────────────────────────────────────────────────────────────────────
About the C Run-Time Library
The Microsoft C run-time library contains a number of new routines and
features which support American National Standards Institute (ANSI) C
compatibility, OS/2 and XENIX(R) programming, and sophisticated graphics
programming.
To ease the task of transporting programs from one operating system to
another, the description of each library routine includes compatibility
boxes, which show at a glance whether the routine is compatible with ANSI C,
MS-DOS, OS/2, UNIX(R), and XENIX. (In this book, references to XENIX systems
also encompass UNIX and other UNIX-like systems.)
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 of the compiler's type-checking ability, the include files
that accompany the C run-time library have been expanded. In addition to the
definitions 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.
OS/2 and XENIX(R) Programming
Microsoft C run-time library routines are designed to maintain maximum
compatibility between MS-DOS, OS/2, and XENIX or UNIX systems. The library
offers a number of operating-system interface routines that allow you to
take advantage of specific DOS and OS/2 features.
Most of the functions in the C library for DOS and OS/2 are compatible with
like-named routines in the C library for XENIX. For additional
compatibility, the math library functions have been extended to provide
exception handling in the same manner as the UNIX System V math functions.
Expanded Graphics Library
The Microsoft C run-time library now contains over one hundred graphics
routines. The core of this library consists of several dozen low-level
graphics routines, which allow your programs to select video modes, set
points, draw lines, change colors, and draw shapes such as rectangles and
ellipses. You can display real-valued data, such as floating-point values,
within windows of different sizes by using various coordinate systems.
Recent additions to the graphics library include presentation graphics and
fonts. The presentation-graphics library provides powerful tools for adding
presentation-quality graphics to your programs. These routines can display
data as a variety of graphs, including pie charts, bar and column charts,
line graphs, and scatter diagrams.
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.
About This Book
This book assumes that you understand the C language and know how to compile
and link programs. If you have questions about these subjects, consult your
compiler documentation.
This book has two parts. Part 1, "Overview," introduces the Microsoft C
library. It describes general rules for using the library and summarizes the
main categories of library routines. Part 1 contains the following chapters:
■ Chapter 1, "Using C Library Routines," gives general rules for
understanding and using C library routines and mentions special
considerations that apply to certain routines. It is recommended that
you read this chapter before using the run-time library; you may also
want to turn to Chapter 1 when you have questions about library
procedures.
■ Chapter 2, "Run-Time Routines by Category," lists the C library
routines by category and discusses considerations that apply to each
category. This chapter makes it easy to locate routines by task. Once
you find the routine you want, turn to the reference page in Part 2
for a detailed description.
■ Chapter 3, "Global Variables and Standard Types," describes variables
and types that are used by library routines. Global variables and
standard types are also described in the reference descriptions of the
routines that use them.
Part 2, "Run-Time Functions," describes the library routines in alphabetical
order. Once you are familiar with the C library rules and procedures, you
will probably use this part most often.
Other Books of Interest
This book provides a guide to the C run-time library provided with the
Microsoft C Professional Development System version 6.0.
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
publications, Microsoft does not endorse these books or recommend them over
others on the same subject.
■ Barkakati, Nabajyoti. The Waite Group's Microsoft C Bible.
Indianapolis, IN: Howard W. Sams, 1988.
A topical guide to the Microsoft C run-time library. A similar volume
is available for the Microsoft QuickC(R) product.
■ Campbell, Joe. C Programmer's Guide to Serial Communications.
Indianapolis, IN: Howard W. Sams & Company, 1987.
A comprehensive guide to the specialized area of serial communication
programming in C.
■ Hansen, Augie. Proficient C: The Microsoft Guide to Intermediate &
Advanced C Programming. Redmond, WA: Microsoft Press, 1987.
An intermediate-level guide to C programming.
■ 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 Programming for the IBM. Indianapolis, IN:
Howard W. Sams & Company, 1987.
The first half of this book teaches C. The second half concentrates on
specifics 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.
■ Plum, Thomas. Reliable Data Structures in C. Cardiff, NJ: Plum Hall,
1985.
An intermediate-level look at data structures using the C language.
■ Plum, Thomas, and Jim Brodie. Efficient C. Cardiff, NJ: Plum Hall,
1985.
A guide to techniques for increasing the efficiency of C programs.
■ Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William
T. Vetterling. Numerical Recipes in C: The Art of Scientific
Computing. New York: Cambridge University Press, 1988.
A comprehensive look at numerical techniques using the C language.
■ Schustack, Steve. Variations in C: Programming Techniques for
Developing Efficient Professional Applications. Redmond, WA: Microsoft
Press, 1985.
An intermediate-level guide to developing business applications in C.
■ Ward, Robert. Debugging C. Indianapolis, IN: Que Corporation, 1986.
An advanced guide to the theory and practice of debugging C programs.
■ Wilton, Richard. Programmer's Guide to PC and PS/2 Video
Systems:Maximum Video Performance from the EGA, VGA, HGC, & MCGA.
Redmond, WA: Microsoft Press, 1987.
An advanced guide to all the PC and PS/2 video modes.
Document Conventions
This book uses the following document conventions :
Example Description
────────────────────────────────────────────────────────────────────────────
STDIO.H Uppercase letters indicate file names,
segment names, registers, and terms 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.
expression Words in italics indicate placeholders
for information 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.
#pragma pack {1|2} 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.
CL options [[files...]] Three dots following an item indicate
that more items having the same form may
appear.
while() A column of three dots tells you that
{ part of the example 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 (+) between 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 have the form "
" and ' ' rather than " " and ' '.
Color Graphics Adapter (CGA) The first time an acronym is used, it is
often spelled out.
PART I Overview
────────────────────────────────────────────────────────────────────────────
The first part of this book provides an overview of the run-time library
provided with the Microsoft C Professional Development System.
Chapter 1 is a general guide to the use of the run-time library routines.
Chapter 2 lists the routines by category.
Chapter 3 tells how to access global variables and types defined in the
run-time library.
Chapter 1 Using C Library Routines
────────────────────────────────────────────────────────────────────────────
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
conventions, 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.
1.1 Calling Library Routines
To use a C library routine, simply call it in your program, just as if it is
defined there. For instance, suppose you write the following program and
name it SAMPLE.C:
#include <stdio.h>
main()
{
printf( "Microsoft C" );
}
The program prints Microsoft C by calling the printf routine, which is
part of the standard C library. Calling a library routine normally involves
two groups of files:
1. Header ("include") files that contain declarations and type
definitions required by library routines
2. Library files that contain the library routines in compiled form
Header files and library files are both included with Microsoft C. Header
files are used when compiling, and library files are used when linking.
You include the necessary header files in your program source code with
#include directives. The description of each library routine in Part 2,
"Reference," tells you what header file the routine requires. Since printf
requires the STDIO.H header file, the SAMPLE.C program contains the
following line:
#include <stdio.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 executable file.
Normally, the code for standard library routines is contained in the
"default library" that you create when installing Microsoft C. Since the
linker automatically 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:
link sample,,,;
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:
link sample,,, graphics.lib;
For more information about libraries and linking, consult the installation
documentation for your compiler.
1.2 Using Header Files
As stated in the previous section, you should include C header files when
using library routines. This section describes particular reasons why header
files are required.
1.2.1 Including Necessary Definitions
Many C library routines use constants, type definitions, or macros defined
in a header file. To use the routine, you must include the header file
containing the needed definition(s). The following list gives examples:
Definition Example
────────────────────────────────────────────────────────────────────────────
Macro If a library routine is implemented as a
macro, the macro definition appears in a
header file. For instance, the toupper
macro is defined in the header file
CTYPE.H.
Manifest constant Many library routines refer to constants
that are defined in header files. For
instance, the open routine uses
constants such as O_CREAT, which is
defined in the header file FCNTL.H.
Type definition Some library routines return a structure
or take a structure as an argument. For
example, stream input/output routines
use a structure of type FILE, which is
defined in STDIO.H.
1.2.2 Including Function Declarations
The Microsoft C header files also contain function declarations for every
function in the C library. These declarations are in the style recommended
by the ANSI C standard. Given these declarations, the compiler can perform
"type checking" on every reference to a library function, making sure that
you have used the correct return type and arguments. Function declarations
are sometimes called "prototypes," since the declaration serves as a
prototype or template for every subsequent reference to the function.
A function declaration lists the name of the function, its return type, and
the number 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
arguments of type double. Given this declaration, the compiler can check
every reference 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 appear near the beginning of the source file, prior to
any use of the functions they declare.
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 returns 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 automatically 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
programs whose function declarations do not contain argument-type lists. For
instance, if your program contains the declaration
char *calloc( );
you can later include the following declaration:
char *calloc(unsigned, unsigned);
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 declarations 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 format 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.
■ 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 arguments (the mode flag, the path name, and the first argument
pointer) are type checked.
1.3 File Names and Path Names
Many library routines take strings representing paths and file names as
arguments. If you plan to transport your programs to the XENIX operating
system, you should remember that XENIX uses file- and path-name conventions
that are different from those used by DOS and OS/2. If you do not plan to
transport your programs to XENIX, you can skip this section.
Case Sensitivity
The DOS and OS/2 operating systems are not case sensitive (they do not
distinguish between uppercase and lowercase letters). Thus, SAMPLE.C and
Sample.C refer to the same file in DOS and OS/2. However, the XENIX
operating system is case sensitive. In XENIX, SAMPLE.C and Sample.C refer to
different 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:
#include <STDIO.H>
#include <stdio.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 programs 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.
1.4 Choosing Between Functions and Macros
This book uses the words "routine" and "function" interchangeably. However,
the term "routine" actually encompasses both functions and macros. Because
functions and macros have different properties, you should pay attention to
which form you are using. The descriptions in the reference section indicate
whether routines are implemented as functions or as macros.
Most routines in the Microsoft C library are functions. They consist of
compiled C code or assembled Microsoft Macro Assembler (MASM) code. However,
a few library routines are implemented as macros that behave like functions.
You can pass arguments to library macros and invoke them in the same way you
invoke functions.
The main benefit of using macros is faster execution time. A macro is
expanded (replaced by its definition) during preprocessing, creating in-line
code. Thus, macros do not have the overhead associated with function calls.
On the other hand, each use of a macro inserts the same code in your
program, whereas a function definition occurs only once regardless of how
many times it is called. Functions and macros thus offer a trade-off between
speed and size.
Apart from speed and size issues, macros and functions have some other
important differences:
■ 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 effects 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 instance, 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 arguments. 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.
The following example demonstrates how some macros can produce unwanted side
effects. It uses the toupper routine from the standard C library.
#include <ctype.h>
int a = 'm';
a = toupper(a++);
The example increments a when passing it as an argument to the toupper
routine, which is implemented as a macro. It is defined in CTYPE.H:
#define toupper(c) ( (islower(c)) ? _toupper(c) : (c) )
The definition uses the conditional operator (? :). The conditional
expression evaluates the argument c twice: once to check if it is
lowercase and again to create 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 always 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:
#include <ctype.h>
int a = 'm';
a = toupper(a);
You can force the compiler to use the function version of a routine by
enclosing the routine's name in parentheses:
#include <ctype.h>
int a = 'm';
a = (toupper) (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.
A second way to do this is to "undefine" the macro definition with the
#undef directive:
#include <ctype.h>
#undef toupper
Since the macro definition no longer exists, subsequent references to
toupper use the function version.
A third way to make sure the compiler uses the function version is to
declare the function explicitly:
#include <ctype.h>
int toupper(int _c);
Since this function declaration appears after the macro definition in
CTYPE.H, it causes the compiler to use the toupper function.
1.5 Stack Checking on Entry
For certain library routines, the compiler performs stack checking on entry.
(The "stack" is a memory area used for temporary storage.) Upon entry to
such a routine, the stack is checked to determine if it has enough room for
the local variables used by that routine. If it does, space is allocated by
adjusting the stack pointer. Otherwise, a "stack overflow" run-time error
occurs. If stack checking is disabled, the compiler assumes there is enough
stack space; if there is not, you might overwrite memory locations in the
data segment and receive no warning.
Typically, stack checking is enabled only for functions with large
local-variable requirements (more than about 150 bytes), since there is
enough free space between the stack and data segments to handle functions
with smaller requirements. If the function is called many times, stack
checking slows execution slightly.
Stack checking is enabled for the following library functions:
execvp printf spawnvpe system
execvpe scanf sprintf vprintf
fprintf spawnvp sscanf write
fscanf
1.6 Handling Errors
Many library routines return a value that indicates an error condition. To
avoid unexpected results, your code should always check such error values
and handle all of the possible error conditions. The description of each
library routine in the reference section lists the routine's return
value(s).
Some library functions do not have a set error return. These include
functions that return nothing and functions whose range of return values
makes it impossible to return a unique error value. To aid in error
handling, some functions in this category set the value of a global variable
named errno.
If the reference description of a routine states that it sets the errno
variable, you can use errno in two ways:
1. Compare errno to the values defined in the header file ERRNO.H.
2. Handle errno with the perror or strerror library routines. The perror
routine prints a system error message to the standard error (stderr).
The strerror routine stores the same information in a string for later
use.
When you use errno, perror, and strerror, remember that the value of errno
reflects 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 determine 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 it matherr or _matherrl. Your routine must follow the rules
listed in the matherr reference description.
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.
1.7 Operating-System Considerations
The library routines listed in this section behave differently under
different operating system versions. For more information on an individual
routine, see the description of that routine in the reference section.
Routine Restrictions
────────────────────────────────────────────────────────────────────────────
locking These routines are effective only in
sopen OS/2 and in DOS versions 3.0 and later.
_fsopen
dosexterr The dosexterr routine provides error
handling for system call 0x59 (get
extended error) in DOS versions 3.0 and
later.
dup The dup and dup2 routines can cause
dup2 unexpected results in DOS versions
earlier than 3.0. If you use dup or dup2
to create a duplicate file handle for
stdin, stdout, stderr, stdaux, or stdprn
, calling the close function with one
handle causes errors in later I/O
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
spawn of functions under DOS versions earlier
than 3.0, the value of the arg0 argument
(or argv[0] to the child process) is not
available to the user; a null string (""
) is stored in that position instead. In
OS/2, the arg0 argument contains the
command name; in DOS versions 3.0 and
later, it contains the complete command
path.
Microsoft C defines global variables that indicate the version of the
current operating 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.
1.8 Floating-Point Support
Microsoft math library routines require floating-point support to perform
calculations 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 require floating-point support are listed below:
acos cos fmod modfl
acosl cosl fmodl pow
asin cosh fmsbintoieee powl
asinl coshl _fpreset sin
atan dieeetomsbin frexp sinl
atanl difftime frexpl sinh
atan2 dmsbintoieee gcvt sinhl
atan2l ecvt hypot sqrt
atof exp hypotl sqrtl
_atold expl ldexp _status87
bessel fabs ldexpl strtod
cabs fabsl log _strtold
cabsl fcvt logl tan
ceil fieeetomsbin log10 tanl
ceill floor log10l tanh
_clear87 floorl modf tanhl
_control87
Note that the bessel routine does not correspond to a single function, but
to twelve functions named j0, j1, jn, y0, y1, yn, _j0l, _j1l, _jnl, _y0l,
_y1l, and _ynl. 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 values are used in a
program 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 format 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
type specifiers in the format string. The presence of floating-point
arguments allows 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 following program produces an error at
run time:
main( ) /* This example causes an error */
{
long f = 10L;
printf("%f", f);
}
In the preceding example, the functions for floating-point support are not
loaded because
■ No floating-point arguments are given in the call to printf.
■ No floating-point values are used elsewhere in the program.
As a result, the following error occurs:
Floating point not loaded
Here is a corrected version of the above call to printf in which the long
integer value is cast to double:
main( ) /* This example works correctly */
{
long f = 10L;
printf("%f", (double) f);
}
1.9 Using Huge Arrays with Library Functions
In programs that use small, compact, medium, and large memory models,
Microsoft C allows you to use arrays exceeding the 64K (kilobyte) limit of
physical memory in these models by explicitly declaring the arrays as _huge.
However, generally, you cannot pass _huge data items as arguments to C
library functions. In the compact-model library used by compact-model
programs and in the large-model library used by both large-model and
huge-model programs, only the functions listed below use argument arithmetic
that works with _huge items:
bsearch _fmemcmp _fmemset lsearch
fread _fmemcpy halloc memccpy
fwrite _fmemicmp hfree memchr
_fmemccpy _fmemmove lfind
_fmemchr
With this set of functions, you can read from, write to, search, sort, copy,
initialize, 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 memcmplibrary routines are available in two
versions: 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 inserts in-line code into your program. Your
compiler documentation explains how to select the intrinsic versions of
library routines.)
Chapter 2 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
categorized lists of routines in this chapter can help.
The descriptions here are intended only to give you a brief overview of the
capabilities of the run-time library. For a complete description of the
behavior, syntax, 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
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 terminated with a null character ('\0'). Therefore, the
buffer-manipulation routines always take a length or count argument.
Function declarations for the buffermanipulation 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, _fmemccpy Copy characters from one buffer to
another until a 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, _fmemicmp Compare a specified number of characters
from two buffers without regard to the
case of the letters (uppercase and
lowercase treated as equivalent)
memmove, Copy a specified number of characters
_fmemmove from one buffer to another
memset, _fmemset Use a given character to initialize a
specified number of bytes in the buffer
swab Swaps bytes of data and stores them at
the specified location
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.)
2.2 Character Classification and Conversion
The character classification and conversion routines allow you to test
individual characters in a variety of ways and to convert between uppercase
and lowercase characters.
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)
The classification routines identify characters by finding them in a table
of classification codes. Using these routines to classify characters is
generally faster than writing a test expression such as the following:
if ((c >= 0) || c <= 0x7f))
All of these routines are implemented in two versions: as functions and as
macros. 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.
2.3 Data Conversion
The data-conversion routines convert numbers to strings of ASCII characters
and vice versa. These routines are implemented as functions, all of which
are declared in the include file STDLIB.H. The atof function, which converts
a string to a floating-point value, is also declared in MATH.H.
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
strtol Converts string to a long integer
_strtold Converts string to long double
strtoul Converts string to an unsigned long
integer
ultoa Converts unsigned long to string
2.4 Directory Control
The directory-control routines let a program access, modify, and obtain
information 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 IO.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).
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
The access, chmod, _fullpath, _makepath, remove, rename, _splitpath, stat,
and unlink routines operate on files specified by a path name or file name.
The chsize, filelength, fstat, isatty, locking, and setmode routines work
with files designated by a file handle.
The mktemp and umask routines have functions that are slightly different
from the other routines. The mktemp routine creates a unique file name, and
the programmer can use mktemp to create unique file names that do not
conflict with the names of existing files. The umask routine sets the
default permission mask for any new files created in a program. The mask can
override the permission setting given in the open or creat call for the new
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 GRAPHICS.LIB library provides support for
low-level graphics and character-font routines. The library PGCHART.LIB
supports presentation-graphics routines.
2.6.1 Low-Level Graphics and Character-Font Functions
The low-level graphics and font functions are declared in the include file
GRAPH.H.
The library can be divided into the eight categories listed below, which
correspond to the different tasks involved in creating and manipulating
graphic objects.
Most graphics routines work only in DOS. Two categories of routines
("configuring mode and environment" and "creating text output") work in OS/2
as well as DOS.
Category Task
────────────────────────────────────────────────────────────────────────────
Configuring mode and environment Select the proper display mode for the
(OS/2 and DOS) hardware and establish memory areas for
writing and displaying of images
Setting coordinates Specify the logical origin and the
active display area within the screen
Setting low-level graphics Specify a palette mapping for low-level
palettes graphics 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 (OS/2 and Write text on the screen
DOS)
Transferring images Store images in memory and retrieve them
Displaying fonts Display text in character fonts
compatible with Microsoft Windows(tm)
The following sections explain each of these categories.
2.6.1.1 Configuring Mode and Environment
Routines that configure the mode and environment establish the graphics or
text mode of operation, determine the current graphics environment, and
control the display of the cursor.
All of the routines listed in this section are available in OS/2 as well as
DOS.
Routine Use
────────────────────────────────────────────────────────────────────────────
_clearscreen Erases the screen and fills it with the
current background 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 function 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
2.6.1.2 Setting Coordinates
The "set coordinates" routines set the current text or graphics position and
convert pixel coordinates between the various graphic coordinate systems.
The Microsoft C graphics functions recognize three sets of coordinates:
1. Fixed physical coordinates
2. View coordinates defined by the application
3. Window coordinates that can include floating-point values
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
_getcurrentposition_w Determines current position in window
coordinates
_getphyscoord Converts view coordinates to physical
coordinates
_getviewcoord Converts physical coordinates to view
coordinates
_getviewcoord_w Converts window coordinates to view
coordinates
_getviewcoord_wxy Converts window coordinates in _wxycoord
structure to view coordinates
_getwindowcoord Converts view coordinates to window
coordinates
_setcliprgn Limits graphic output to a region of the
screen
_setvieworg Positions the view-coordinate origin
_setviewport Limits graphics output to a region of
the screen and positions the
view-coordinate origin to the upper-left
corner of that region
_setwindow Defines a floating-point window
coordinate system
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 display. The x axis extends in the positive direction left to
right, while the y axis extends 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 previous section.)
The _setvieworg function allows you to move the viewport origin to a new
position relative to the physical screen.
Routines that refer to coordinates on the physical screen or viewport
require integer 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 instead of integers.
The _getcurrentposition and _getcurrentposition_w routines allow you to
determine the location of the current graphics-output point.
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 physical coordinates of any view-coordinate point can be determined with
the _getphyscoord function, and the view coordinates of any physical point
can be determined with the _getviewcoord function.
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.
The _setwindow function defines the current viewport as a real-coordinate
window bound by the specified floating-point values.
2.6.1.3 Setting Low-Level Graphics Palettes
Use the low-level palette routines to select or remap color palettes.
Routine Use
────────────────────────────────────────────────────────────────────────────
_remapallpalette Changes all color indexes in the current
palette
_remappalette Changes a single color index in the
current palette
_selectpalette Selects a predefined 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 16 can be displayed at a
time. In this mode, the palette contains 16 "color indices," or slots to
which you can assign color values.
The _remappalette routine changes a single color index to a specified color
value. The _remapallpalette routine changes all of the available palette
entries simultaneously.
2.6.1.4 Setting Attributes
The low-level output functions that draw lines, arcs, ellipses, and other
basic figures do not specify color or line-style information. Instead, the
low-level graphics functions rely on a set of attributes that are set
independently by the following functions:
Routine Use
────────────────────────────────────────────────────────────────────────────
_getarcinfo Determines the endpoints in viewport
coordinates of the most recently drawn
arc or pie
_getcolor Gets the current color
_getfillmask Gets the current fill mask
_getlinestyle Gets the current line-style mask
_getwritemode Gets the current logical write mode
_setcolor Sets the current color
_setfillmask Sets the current fill mask
_setlinestyle Sets the current line-style mask
_setwritemode Sets logical write mode for line drawing
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 1, 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 16-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.
2.6.1.5 Creating Graphics Output
The graphics output functions use a set of specified coordinates and draw
various figures. They use the current or default attributes for line-style
mask, fill mask, write mode, background color, and foreground color.
The name of each function announces its task or the figure it draws, as the
following list indicates:
Routine Use
────────────────────────────────────────────────────────────────────────────
_arc, _arc_w, _arc_wxy Draw an arc
_ellipse, _ellipse_w, Draw an ellipse or circle
_ellipse_wxy
_floodfill, _floodfill_w Flood-fill an area of the screen with
the current color
_getcurrentposition, Obtain the current graphic-output
_getcurrentposition_w position used by _lineto and _outgtext
_getpixel, _getpixel_w Obtain a pixel's color
_lineto, _lineto_w Draw a line from the current graphic
output position to a specified point
_moveto, _moveto_w Move the current graphic-output position
to a specified point
_pie, _pie_w, _pie_wxy Draw a pie-slice-shaped figure
_polygon, _polygon_w, Draw or scan-fill a polygon
_polygon_wxy
_rectangle, _rectangle_w, Draw or scan-fill a rectangle
_rectangle_wxy
_setpixel, _setpixel_w Set a pixel's color
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. Functions that end with _w take double values as arguments and use
the window coordinate system. Functions that end with _wxy use _wxycoord
structures to define the coordinates and use the window coordinate system.
Circular figures, such as arcs and ellipses, are centered within a "bounding
rectangle" specified by two points that define the diagonally opposed
corners 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.
2.6.1.6 Creating Text Output
The next group of routines provides text output in both graphics and text
modes. Unlike the standard console I/O library routines, these functions
recognize text-window boundaries and use the current text color.
All of the routines listed in this section work in OS/2 as well as DOS.
Routine Use
────────────────────────────────────────────────────────────────────────────
_displaycursor Sets the cursor on or off upon exit from
a graphics routine
_gettextcolor Obtains the current text color
_gettextcursor Returns the current cursor attribute
(text modes only)
_gettextposition Obtains the current text-output position
_gettextwindow Gets the current text window boundaries
_outmem Prints text of a specified length from a
memory
buffer
_outtext Outputs a text string to the screen at
the current text position
_scrolltextwindow Scrolls the current text window up or
down
_settextcolor Sets the current text color
_settextcursor Sets the current cursor attribute (text
modes only)
_settextposition Relocates the current text position
_settextwindow Defines the current text-display window
_wrapon Enables or disables line wrap
The _outtext and _outmem routines provide no formatting. If you want to
output integer or floating-point values, you must convert the values into a
string variable (using the sprintf function) before calling these routines.
The _outtext routine recognizes the \n (newline character) and \r (carriage
return) 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
functions in this set use view coordinates.
Routine Use
────────────────────────────────────────────────────────────────────────────
_getimage, Store a screen image in memory
_getimage_w,
_getimage_wxy
_imagesize, Return the size (in bytes) of the buffer
_imagesize_w, needed to store the image
_imagesize_wxy
_putimage, Retrieve an image from memory and
_putimage_w display it
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 buffer larger than 64K.
2.6.1.8 Displaying Fonts
The functions listed in this section control the display of font-based
characters on the screen.
Routine Use
────────────────────────────────────────────────────────────────────────────
_getfontinfo Obtains the current font characteristics
_getgtextextent Determines the width in pixels of
specified text in the current font
_getgtextvector Gets orientation of font text output
_outgtext Outputs text in the current font to the
screen at the specified pixel position
_registerfonts Initializes font library
_setfont Finds a single font that matches a
specified set of characteristics and
makes this font the current font for use
by the _outgtext function
_setgtextvector Sets the current orientation for font
text output
_unregisterfonts Frees memory allocated by _registerfonts
2.6.2 Presentation-Graphics Functions
The presentation-graphics functions are declared in the PGCHART.H include
file. The library can be divided into the three categories listed below,
corresponding to the different tasks involved in creating and manipulating
graphic objects:
Category Task
────────────────────────────────────────────────────────────────────────────
Displaying presentation graphics Initialize video structures for
presentation graphics and establishes
the default chart type. Display
presentation-graphics chart: bar,
column, pie, scatter, or line chart.
Analyzing Analyze data (does not display chart).
presentation-graphics data
Manipulating Modify basic chart structures (e.g.,
presentation-graphics structures palettes, cross-hatching styles).
2.6.2.1 Displaying Presentation Graphics
The functions listed in this section initialize the presentation-graphics
library and display the specified graph type.
Because the _pg_initchart routine initializes the presentation-graphics
library, it must be called before any other function in the
presentation-graphics library. The _pg_defaultchart function initializes the
variables in the chart environment.
The other routines in this category display the specified graph. The
single-series versions plot one set of data, and the multiseries versions
(those ending with an ms suffix) plot several sets of data in the same chart
style.
Presentation-graphics programs can display text in different font sizes by
taking advantage of font-based characters (see Section 2.6.1.8, "Displaying
Fonts.") Call the _registerfonts and _setfont routines to select a font
before calling the _pginitchart routine. Subsequent charts use the selected
font. You can later call the _unregisterfonts routine to restore the default
character font and free the memory previously allocated for fonts.
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 environment for a specified
chart type
_pg_initchart Initializes the presentation-graphics
library
2.6.2.2 Analyzing Presentation-Graphics Charts
These routines calculate default values for the specified graph type but do
not display the chart. The single-series versions analyze one set of data,
and the multiseries versions analyze several sets of data in the same chart
style.
Routine Use
────────────────────────────────────────────────────────────────────────────
_pg_analyzechart Analyzes a single series of data for a
bar, column, or line chart
_pg_analyzechartms Analyzes a multiseries of data for a
bar, column, or line chart
_pg_analyzepie Analyzes data for a pie chart
_pg_analyzescatter Analyzes a single series of data for a
scatter diagram
_pg_analyzescatterms Analyzes a multiseries of data for a
scatter diagram
2.6.2.3 Manipulating Presentation-Graphics Structures
These functions control low-level aspects of the presentation-graphics
package.
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
_pg_getstyleset Retrieves the contents of the current
styleset
_pg_setstyleset Sets the contents of the current
styleset
_pg_resetstyleset Resets the contents of the current
styleset to the default value for the
current screen mode
_pg_getchardef Retrieves the current 8-by-8-pixel bit
map for a specified character
_pg_setchardef Sets the 8-by-8-pixel bit map for a
specified
character
2.7 Input and Output
The input and output (I/O) routines of the standard C library allow you to
read and write data to and from files and devices. In C, there are no
predefined file structures; all data items are treated as sequences of
bytes. The following three types of I/O functions are available:
1. Stream
2. Low-level
3. Console and port
The "stream" I/O functions treat data as a stream of individual characters.
By choosing among the many stream functions available, you can process data
in different sizes and formats, from single characters to large data
structures. Stream I/O also provides buffering, which can significantly
improve performance.
The "low-level" I/O routines do not perform buffering and formatting.
Instead, they invoke the operating system's input and output capabilities
directly. These routines let you access files and peripheral devices at a
more basic level than the stream functions.
The "console and port" I/O routines allow you to read or write directly to a
console (keyboard and screen) or an I/O port (such as a printer port). The
port I/O routines simply read and write data in bytes. With console I/O
routines, some additional options are available, such as detecting whether a
character has been typed at the console. You can 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 I/O system call routines.
These are described in Section 2.14, "System Calls."
File I/O 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 for processing a given file.
────────────────────────────────────────────────────────────────────────────
2.7.1 Text and Binary Modes
Many C programs use data files for input and output. Under DOS and OS/2,
data files are normally processed in text mode. In this mode, each
carriage-return-line-feed (CR-LF) combination is translated into a single
line-feed character during input. During output, each line-feed character is
translated into a CR-LF combination.
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
O_BINARY flag in the oflag argument. For more information about fopen
and open, see the reference description 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.
You can change the value of _fmode in two ways:
1. Link with the file BINMODE.OBJ (supplied with Microsoft C). This
changes the initial setting of _fmode to the O_BINARY flag, causing
all files except stdin, stdout, and stderr to be opened in binary
mode.
2. Change the value of _fmode directly by setting it to the O_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 opening it in text mode. Specify the letter t when using fopen, or
specify the O_TEXT flag when using open.
By default, the stdin, 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.
2.7.2 Stream Routines
Stream I/O functions handle data as a continuous stream of characters. To
use the stream functions, you must include the file STDIO.H in your program.
This file defines constants, types, and structures used in the stream
functions, and contains function declarations and macro definitions for the
stream routines.
When a file is opened for I/O using the stream functions, the opened file is
associated with a structure of type FILE (defined in STDIO.H) containing
basic information 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 collected in an intermediate storage location called a
"buffer". In write operations, 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.
Buffering produces efficient I/O because the system can transfer a large
block of data in a single operation rather than performing an I/O 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.
Some of the constants defined in STDIO.H may be useful in your program. The
manifest constant EOF is defined to be the value returned at end-of-file.
NULL is the null pointer. FILE is the structure that maintains information
about a stream. BUFSIZ defines the default size of stream buffers, in bytes.
Routine Use
────────────────────────────────────────────────────────────────────────────
clearerr Clears the error indicator for a stream
fclose Closes a stream
fcloseall Closes all open streams
fdopen Associates a stream with an open file
handle
feof Tests for end-of-file on a stream
ferror Tests for error on a stream
fflush Flushes a stream
fgetc Reads a character from a stream
(function version)
fgetchar Reads a character from stdin (function
version)
fgetpos Gets the position indicator of a stream
fgets Reads a string from a stream
fileno Gets the file handle associated with a
stream
flushall Flushes all streams
fopen Opens a stream
fprintf Writes formatted data to a stream
fputc Writes a character to a stream (function
version)
fputchar Writes a character to stdout (function
version)
fputs Writes a string to a stream
fread Reads unformatted data from a stream
freopen Reassigns a FILE pointer to a new file
fscanf Reads formatted data from a stream
fseek Moves file position to a given location
fsetpos Sets the position indicator of a stream
_fsopen Opens a stream with file sharing
ftell Gets current file position
fwrite Writes unformatted data items to a
stream
getc Reads a character from a stream
getchar Reads a character from stdin
gets Reads a line from stdin
getw Reads a binary int item from a stream
printf Writes formatted data to stdout
putc Writes a character to a stream
putchar Writes a character to stdout
puts Writes a line to a stream
putw Writes a binary int item to a stream
rewind Moves file position to beginning of a
stream
rmtmp Removes temporary files created by
tmpfile
scanf Reads formatted data from stdin
setbuf Controls stream buffering
setvbuf Controls stream buffering and buffer
size
sprintf Writes formatted data to a string
sscanf Reads formatted data from a string
tempnam Generates a temporary file name in given
directory
tmpfile Creates a temporary file
tmpnam Generates a temporary file name
ungetc Places a character in the buffer
vfprintf Writes formatted data to a stream
vprintf Writes formatted data to stdout
vsprintf Writes formatted data to a string
2.7.2.1 Opening a Stream
A stream must be opened using the fdopen, fopen, freopen, or _fsopen
function before input and output can be performed on that stream. When
opening a stream, the named stream can be opened for reading, writing, or
both, and can be opened in either text or binary mode.
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
FILE *infile
infile = fopen ("test.dat", "r");
you can use the FILE pointer variable infile to refer to the stream.
2.7.2.2 Using Predefined Stream Pointers
When a program begins execution, the C start-up code automatically opens
several streams: standard input, standard output, and standard error. By
default, the standard input, standard output, and standard error streams are
directed to the console (keyboard and screen). This means that when a
program expects input from the "standard input," it receives that input from
the console. Similarly, a program that writes to the "standard output"
prints its data to the console. Error messages generated by the library
routines are sent to the "standard error," meaning that error messages
appear on the user's console.
Under DOS, two additional streams are opened: standard auxiliary and
standard print. (These streams are not available in OS/2.) The assignment of
standard auxiliary and standard print depends on the machine configuration.
These streams usually refer to the first serial port and a printer port, but
those ports may not be available on some systems. Be sure to check your
machine configuration before using these streams.
You can refer to the standard streams with the following predefined stream
pointers:
Pointer Stream
────────────────────────────────────────────────────────────────────────────
stdin Standard input
stdout Standard output
stderr Standard error
stdaux Standard auxiliary (DOS only)
stdprn Standard print (DOS only)
You can use these pointers in any function that requires a stream pointer as
an argument. Some functions, such as getchar and putchar, are designed to
use stdin or stdout automatically. The pointers stdin, 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
output 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 complete discussion of redirection.
Within your program, you can use freopen to redirect stdin, 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.
2.7.2.3 Controlling Stream Buffering
As mentioned earlier, stream routines can use in-memory buffers to speed I/O
operations. Files opened using the stream routines are buffered by default,
except for stdaux and stdprn, which are normally unbuffered. The stdout and
stderr streams are flushed whenever they are full or (if you are writing to
a character device) after each library call.
By using the setbuf or setvbuf function, you can cause a stream to be
unbuffered, 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.H 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.
────────────────────────────────────────────────────────────────────────────
2.7.2.4 Closing Streams
The fclose and fcloseall functions close a stream or streams. The fclose
routine closes a single specified stream; fcloseall closes all open streams
except stdin, stdout, stderr, stdaux, and stdprn. If your program does not
explicitly close a stream, the stream is automatically closed when the
program terminates. How-ever, it is a good practice to close a stream when
your program is finished with it, as the number of streams that can be open
at a given time is limited.
2.7.2.5 Reading and Writing Data
The stream functions allow you to transfer data in a variety of ways. You
can read and write binary data (a sequence of bytes), or specify reading and
writing by characters, lines, or more complicated formats.
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 increased by one byte so that the next operation
begins with the first unread character. 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 position 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-oriented 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 associated with a character-oriented device.
2.7.2.6 Detecting Errors
When an error occurs in a stream operation, an error indicator for the
stream is set. You can use the ferror macro to test the error indicator and
determine whether an error has occurred. Once an error has occurred, the
error indicator for the stream remains set until the stream is closed, or
until you explicitly clear the error indicator by calling clearerr or
rewind.
2.7.3 Low-Level Routines
Low-level input and output calls do not buffer or format 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
functions do not require the include file STDIO.H. However, some common
constants 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-permission mask
write Writes data to a file
2.7.3.1 Opening a File
You must open a file before performing I/O functions on it. The open
function opens a file; it can also create the file when opening it. In OS/2
and DOS versions 3.0 and later, you can use sopen to open a file with
file-sharing attributes. The creat function can create and open a file.
The file can be opened for reading, writing, or both, and opened in either
text or binary mode (see Section 2.7.1, "Text and Binary Modes"). The
include file FCNTL.H must be included when opening a file, as it contains
definitions for flags used in open. In some cases, the files SYS\TYPES.H and
SYS\STAT.H must also be included; for more information, see the reference
description for the open function.
These functions return a file handle, which is normally assigned to an
integer variable. You use the variable to refer to the opened file.
2.7.3.2 Reading and Writing Data
Use the read and write routines to read and write to files. These operations
begin at the current position in the file. The current position is updated
each time a read or write operation occurs.
The lseek function allows you to place the file pointer anywhere in the
file. The next operation occurs at the position you specified. The tell
function indicates the current position of the file pointer. The eof routine
tests for the end of the file.
Low-level I/O routines set the errno variable when an error occurs. Chapter
3, "Global Variables and Standard Types," describes errno.
Character-oriented devices, such as the console, do not have file pointers.
The lseek and tell routines have undefined results if used on a handle
associated with a device.
2.7.3.3 Closing Files
The close function closes an open file. Open files are automatically closed
when a program terminates. However, it is a good practice to close a file
when your program is finished with it, as there is a limit to the number of
files that can be open at one time.
2.7.3.4 Using Predefined Handles
When a program begins execution, three files are automatically opened:
standard input, standard output, and standard error. In DOS, two additional
files are opened: standard auxiliary and standard print. (These files are
not available in OS/2.)
Low-level routines can access these files using the following predefined
handles:
Stream Handle
────────────────────────────────────────────────────────────────────────────
stdin 0
stdout 1
stderr 2
stdaux (DOS only) 3
stdprn (DOS only) 4
You can use these file handles 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.
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.
2.7.4 Console and Port I/O
The console and port I/O routines are implemented as functions and are
declared in the include file CONIO.H. These functions perform reading and
writing operations on your console or on the specified port. The cgets,
cscanf, getch, getche, and kbhit routines take input from the console, while
cprintf, cputs, putch, and ungetch write to the console. The input or output
of these functions can be redirected.
Routine Use
────────────────────────────────────────────────────────────────────────────
cgets Reads a string from the console
cprintf Writes formatted data to the console
cputs Writes a string to the console
cscanf Reads formatted data from the console
getch Reads a character from the console
getche Reads a character from the console and
echoes it
inp Reads one byte from the specified I/O
port
inpw Reads a two-byte word from the specified
I/O port
kbhit Checks for a keystroke at the console
outp Writes one byte to the specified I/O
port
outpw Writes a two-byte word to the specified
I/O port
putch Writes a character to the console
ungetch "Ungets" the last character read from
the console so that it becomes the next
character read
────────────────────────────────────────────────────────────────────────────
NOTE
Programs that need only run under DOS can also use a number of direct DOS
I/O system calls ( _dos_open, _dos_read, _dos_close, etc.) These are
described in detail in Section 2.14, "System Calls."
────────────────────────────────────────────────────────────────────────────
The console or port does not have to be opened or closed before I/O is
performed, so there are no open or close routines in this category. The port
I/O 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 I/O 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 I/O 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 program 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 formatting 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").
The math library provides two versions of some routines. The first version
of the routine supports double arguments and return values. The second
version supports 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 l. 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
atan2, atan2l 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
Microsoft (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
fieeetomsbin Converts IEEE single-precision number to
Microsoft binary format
floor, floorl Find the largest integer less than or
equal to the
argument
fmod, fmodl Find the floating-point remainder
fmsbintoieee Converts Microsoft binary
single-precision number to IEEE format
_fpreset Reinitializes the floating-point-math
package
frexp, frexpl Calculate an exponential value
hypot, hypotl Calculate the hypotenuse of right
triangle
ldexp, ldexpl Calculate the product of the argument
and 2exp
ldiv Divides one long integer by another,
returning the quotient and remainder
log, logl Calculate the natural logarithm
log10, log10l Calculate the base-10 logarithm
_lrotl, _lrotr Shift an unsigned long int item left (
_lrotl) or right ( _lrotr)
matherr, _matherrl Handle math errors
max, min Return the larger or smaller of two
values
modf, modfl Break down the argument into integer and
fractional parts
pow, powl Calculate a value raised to a power
rand Gets a pseudorandom number
_rotl, _rotr Shift an unsigned int item left ( _rotl)
or right
( _rotr)
sin, sinl Calculate the sine
sinh, sinhl Calculate the hyperbolic sine
sqrt, sqrtl Find the square root
srand Initializes a pseudorandom series
_status87 Gets the floating-point status word
tan, tanl Calculate the tangent
tanh, tanhl Calculate the hyperbolic tangent
The bessel routine does not correspond to a single function, but to twelve
functions named j0, j1, jn, y0, y1, yn, _j0l, _j1l, _jnl, _y0l, _y1l,
and _ynl.
The matherr and _matherrl routines are invoked by the math functions when
errors 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
definition 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
_bfreeseg Frees a based heap
_bheapseg Allocates a based heap
calloc, _bcalloc, _fcalloc, Allocate storage for an array
_ncalloc
_expand, _bexpand, _fexpand, Expand or shrink a block of memory
_nexpand without moving its location
free, _bfree, _ffree, _nfree Free an allocated block
_freect Returns approximate number of items of
given size that could be allocated in
the near heap
halloc Allocates storage for huge array
_heapadd, _bheapadd Add memory to a heap
_heapchk, _bheapchk, _fheapchk Check a heap for consistency
, _nheapchk
_heapmin, _bheapmin, Release unused memory in a heap
_fheapmin, _nheapmin
_heapset, _bheapset, _fheapset Fill free heap entries with a specified
, _nheapset value
_heapwalk, _bheapwalk, Return information about each entry in a
_fheapwalk, _nheapwalk heap
hfree Frees a block allocated by halloc
malloc, _bmalloc, _fmalloc, Allocate a block of memory
_nmalloc
_memavl Returns approximate number of bytes
available for allocation in the near
heap
_memmax Returns size of largest contiguous free
block in the near heap
_msize, _bmsize, _fmsize, Return size of an allocated block
_nmsize
realloc, _brealloc, _frealloc, Reallocate a block to a new size
_nrealloc
stackavail Returns size of stack space available
for allocation with alloca
Some memory-management routines, such as malloc, are available in different
versions that begin with _b, _f, or _n. These variations are described in
the following section.
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 program'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
expand 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 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.
2.10.1 Near and Far Heaps
As mentioned in the previous section, heap memory can reside inside or
outside your program's default data segment, depending on what memory model
your program uses. When it lies inside the default data segment, the heap is
called the "near heap," since it can be accessed with near pointers. The
"far heap" is memory that spans one or more segments outside the default
data segment. The far heap can be accessed only with far pointers.
In various memory models, malloc automatically allocates memory from the
near heap or far heap, as appropriate. The C library also includes near and
far versions of malloc, free, and other memory-management routines, which
allow you to specify the near and far heaps explicitly. These have the same
names as standard memory routines, but are preceded by _n (for near) or _f
(for far).
For instance, the _nmalloc routine always allocates memory from the near
heap and returns a near pointer, no matter which memory model your program
uses. Use _nfree to release memory allocated with _nmalloc.
Similarly, _fmalloc always allocates memory from the far heap and returns a
far pointer, regardless of memory model. Use the _ffree routine to release
memory allocated with _fmalloc.
2.10.2 Based Heaps
You can also allocate memory from a "based heap," which is a single segment
that lies outside the default data segment. Based-heap routines generally
use the same names as standard memory routines, but begin with _b. For
instance, _bmalloc allocates a memory block from the based heap and _bfree
frees the block.
Based heaps offer the following advantages:
■ Localized data. Based heaps allow you to group related data in a
single segment. 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 segment, 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 as many based-heap segments as needed (within the confines of
available memory).
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 program less portable.
────────────────────────────────────────────────────────────────────────────
2.11 Process and Environment Control
The process-control routines allow you to start, stop, and manage processes
from within a program. Environment-control routines allow you to get and
change information about the operating-system environment.
A "process" is a program being executed by the operating system. It consists
of the program's code and data, plus information about the process, such as
the number of open files. Whenever you execute a program at the
operating-system level, you start a process.
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
────────────────────────────────────────────────────────────────────────────
abort Aborts a process without flushing
buffers or calling functions registered
by atexit and onexit
assert Tests for logic error
atexit Schedules routines for execution at
program
termination
_beginthread Creates an execution thread (OS/2 only)
_cexit Performs the exit termination procedures
(such as flushing buffers) and returns
control to the calling program
_c_exit Performs the _exit termination
procedures and returns control to the
calling program
cwait Suspends the calling process until a
specified child process terminates (OS/2
only)
_endthread Terminates an execution thread (OS/2
only)
execl Executes child process with argument
list
execle Executes child process with argument
list and given environment
execlp Executes child process using PATH
variable and argument list
execlpe Executes child process using PATH
variable, given environment, and
argument list
execv Executes child process with argument
array
execve Executes child process with argument
array and given environment
execvp Executes child process using PATH
variable and argument array
execvpe Executes child process using PATH
variable, given environment, and
argument array
exit Calls functions registered by atexit and
onexit, then flushes all buffers and
closes all open files before terminating
the process
_exit Terminates process without processing
atexit or onexit functions or flushing
buffers
getenv Gets the value of an environment
variable
getpid Gets process ID number
longjmp Restores a saved stack environment
onexit Schedules routines for execution at
program
termination
_pclose Waits for a child command and closes a
pipe on the associated stream
perror Prints error message
_pipe Creates a pipe
_popen Creates a pipe and asynchronously
executes a child copy of the command
processor
putenv Adds or changes the value of an
environment
variable
raise Sends a signal to the calling process
setjmp Saves a stack environment
signal Handles an interrupt signal
spawnl Executes child process with argument
list
spawnle Executes child process with argument
list and given environment
spawnlp Executes child process using PATH
variable and argument list
spawnlpe Executes child process using PATH
variable, given environment, and
argument list
spawnv Executes child process with argument
array
spawnve Executes child process with argument
array and given environment
spawnvp Executes child process using PATH
variable and argument array
spawnvpe Executes child process using PATH
variable, given environment, and
argument array
system Executes an operating system command
wait Suspends the calling process until any
of the caller's immediate child
processes terminate (OS/2 only)
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
registered 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 overlays 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).
There are eight forms each of the spawn and exec routines (see Table 2.1).
The differences among the forms involve the method of locating the file to
be executed 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 arguments 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 arguments is constant or is known at compile time. The
argument-array method is useful when the number of arguments must be
determined at run time.
Several process-control routines take advantage of the multitasking
capability of OS/2. The _beginthread and _endthread routines create and
terminate execution threads. The cwait and wait routines suspend the calling
process until one child process terminates. The _pipe, _popen, and _pclose
routines create and manipulate pipes, which link processes for sequential
execution.
Table 2.1 Forms of the spawn and exec Routines
╓┌───────────────────┌──────────────────┌────────────────────┌───────────────►
Argument-Passing
Routines Locating the File Convention Environment
Settings
─────────────────────────────────────────────────────────────────────────────
execl, spawnl Do not use PATH Argument list Inherited from
parent
execle, spawnle Do not use PATH Argument list Pointer to
environment table
for child process
passed as last
argument
execlp, spawnlp Use PATH Argument list Inherited from
parent
Argument-Passing
Routines Locating the File Convention Environment
Settings
parent
execlpe, spawnlpe Use PATH Argument list Pointer to
environment table
for child process
passed as last
argument
execv, spawnv Do not use PATH Argument array Inherited from
parent
execve, spawnve Do not use PATH Argument array Pointer to
environment table
for child process
passed as last
argument
execvp, spawnvp Use PATH Argument array Inherited from
Argument-Passing
Routines Locating the File Convention Environment
Settings
execvp, spawnvp Use PATH Argument array Inherited from
parent
execvpe, spawnvpe Use PATH Argument array Pointer to
environment table
for child process
passed as last
argument
─────────────────────────────────────────────────────────────────────────────
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 turn off assertion checking without
modifying the source file.
2.12 Searching and Sorting
Search and sort routines provide binary-search, linear-search, and
quick-sort capabilities. They are all declared in SEARCH.H.
Routine Use
────────────────────────────────────────────────────────────────────────────
bsearch Performs binary search
lfind Performs linear search for given value
lsearch Performs linear search for given value,
which is added to array if not found
qsort Performs 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
perform various other operations.
Routines beginning with _f are model-independent versions of the
corresponding routines and are useful in mixed-model programs. These
routines can be called from any point in the program, regardless of which
model is being used.
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, _nstrdup Duplicate a string
strerror Maps an error number to a message string
_strerror Maps a user-defined error message to a
string
stricmp, _fstricmp Compare two strings without regard to
case
strlen, _fstrlen Find length of string
strlwr, _fstrlwr Convert string to lowercase
strncat, _fstrncat Append characters of a string
strncmp, _fstrncmp Compare characters of two strings
strncpy, _fstrncpy Copy characters of one string to another
strnicmp, _fstrnicmp Compare characters of two strings
without regard
to case
strnset, _fstrnset Set characters of a string to a given
character
strpbrk, _fstrpbrk Find first occurrence of a character
from one string in another
strrchr, _fstrrchr Find last occurrence of a given
character in string
strrev, _fstrrev Reverse string
strset, _fstrset Set all characters of a string to a
given character
strspn, _fstrspn Find first substring from a given
character set in a string
strstr, _fstrstr Find first occurrence of a given string
in another string
strtok, _fstrtok Find next token in a string
strupr, _fstrupr Convert a string to uppercase
All string functions work on null-terminated character strings. When working
with character arrays that do not end with a null character, you can use the
buffer-manipulation routines, described in Section 2.1.
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.
2.14.1 BIOS Interface
The functions in this category provide direct access to the BIOS interrupt
services. They are all declared in BIOS.H.
Routine Use
────────────────────────────────────────────────────────────────────────────
_bios_disk Issues service requests for both hard
and floppy disks, using INT 0x13
_bios_equiplist Performs an equipment check, using INT
0x11
_bios_keybrd Provides access to keyboard services,
using
INT 0x16
_bios_memsize Obtains information about available
memory, using INT 0x12
_bios_printer Performs printer output services, using
INT 0x17
_bios_serialcom Performs serial communications tasks,
using
INT 0x14
_bios_timeofday Provides access to system clock, using
INT 0x1A
────────────────────────────────────────────────────────────────────────────
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 DOS 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 0x48
_dos_close Closes a file, using DOS system call
0x3E
_dos_creat Creates a new file and erases any
existing file having the same name,
using DOS system call 0x3C
_dos_creatnew Creates a new file and returns an error
if a file having the same name exists,
using DOS system
call 0x5B
_dos_findfirst Finds first occurrence of a given file,
using DOS system call 0x4E
_dos_findnext Finds subsequent occurrences of a given
file, using DOS system call 0x4F
_dos_freemem Frees a block of memory, using DOS
system
call 0x49
_dos_getdate Gets the system date, using DOS system
call 0x2A
_dos_getdiskfree Gets information on a disk volume, using
DOS system call 0x36
_dos_getdrive Gets the current default drive, using
DOS system call 0x19
_dos_getfileattr Gets current attributes of a file or
directory, using DOS system call 0x43
_dos_getftime Gets the date and time a file was last
written, using DOS system call 0x57
_dos_gettime Gets the current system time, using DOS
system
call 0x2C
_dos_getvect Gets the current value of a specified
interrupt vector, using DOS system call
0x35
_dos_keep Installs terminate-and-stay-resident
(TSR) programs using DOS system call
0x31
_dos_open Opens an existing file, using DOS system
call 0x3D
_dos_read Reads a file, using DOS system call 0x3F
_dos_setblock Changes the size of a previously
allocated block, using DOS system call
0x4A
_dos_setdate Sets the current system date, using DOS
system
call 0x2B
_dos_setdrive Sets the default disk drive, using DOS
system
call 0x0E
_dos_setfileattr Sets the current attributes of a file,
using DOS system call 0x43
_dos_setftime Sets the date and time that the
specified file was last written, using
DOS system call 0x57
_dos_settime Sets the system time, using DOS system
call 0x2D
_dos_setvect Sets a new value for the specified
interrupt vector, using DOS system call
0x25
_dos_write Sends output to a file, using DOS system
call 0x40
dosexterr Obtains in-depth error information from
DOS system call 0x59
_enable Enables interrupts
FP_OFF Returns offset portion of a far pointer
(OS/2
and DOS)
FP_SEG Returns segment portion of a far pointer
(OS/2
and DOS)
_harderr Establishes a hardware error handler
_hardresume Returns to DOS after a hardware error
_hardretn Returns to the application after a
hardware error
int86 Invokes DOS interrupts
int86x Invokes DOS interrupts with segment
register values
intdos Invokes DOS system call using registers
other than DX and AL
intdosx Invokes DOS system call using registers
other than DX and AL with segment
register values
segread Returns current values of segment
registers (OS/2 and DOS)
The _harderr routine is used to define a hardware-error interrupt handler.
The _hardresume and _hardretn routines are used within a hardware error
handler to define the return from the error.
The dosexterr function obtains and stores the error information returned by
DOS system call 0x59 (extended error handling). This function is provided
for use with 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 carry
flag is set; since your program cannot detect whether the carry flag is set,
it cannot determine 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.
The intdosx routine is similar to the intdos routine, but is used when ES is
required 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 system 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
similar; 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 correct 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 system calls noted above. More detailed information on these system
calls can be found in the MS-DOS Encyclopedia (Duncan, ed.; Redmond, WA:
Microsoft Press, 1988)or the Programmer's PC Sourcebook (Hogan; Redmond, WA:
Microsoft Press, 1988).
────────────────────────────────────────────────────────────────────────────
NOTE
The DOS interface I/O routines are generally incompatible with console,
low-level, and stream I/O routines. Do not mix different types of I/O
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 system 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
difftime Computes the difference between two
times
ftime Puts current system time in variable of
type
struct tm
gmtime Converts time from integer to struct tm
localtime Converts time from integer to struct tm
with local correction
mktime Converts time to a calendar value
_strdate Returns the current system date as a
string
strftime Formats a date and time string
_strtime Returns the current system time as a
string
time Gets current system time as a long
integer
tzset Sets external time variables from the
environment time variable
utime Sets file-modification time
The time and ftime functions return the current time as the number of
seconds elapsed since midnight Universal Coordinated Time (UTC) on January
1, 1970. 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 function 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 remainder of
the time functions are declared in the include file TIME.H.
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
describes the global variables daylight, timezone, and tzname, includes a
discussion 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."
2.16 Variable-Length Argument Lists
The va_arg, va_end, and va_start routines are macros that provide a portable
way to access the arguments to a function when the function takes a variable
number of arguments. Two versions of the macros are available: the macros
defined in the VARARG.H include file, which are compatible with the UNIX
System V definition, and the macros defined in STDARG.H, which conform to
the ANSI C standard.
Routine Use
────────────────────────────────────────────────────────────────────────────
va_arg Retrieves argument from list
va_end Resets pointer
va_start Sets pointer to beginning of argument
list
For more information on the differences between the two versions and for an
explanation of how to use the macros, see their descriptions in Part 2 of
this book.
Chapter 3 Global Variables and Standard Types
────────────────────────────────────────────────────────────────────────────
The Microsoft C Run-Time Library contains definitions for a number of
variables and standard types used by library routines. You can access these
variables and types by including in your program the files in which they are
declared, or by giving appropriate declarations in your program, as shown in
the following sections.
3.1 _amblksiz
The _amblksiz variable controls memory heap granularity.
It is declared in the MALLOC.H include file as follows:
extern unsigned int _amblksiz;
The _amblksiz variable controls the amount of memory used in the heap for
dynamic memory allocation.
Memory space is always requested from the operating system in blocks
containing _amblksiz bytes. The first time a program calls a
memory-allocation function 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 8K (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:
_amblksiz = 2048;
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).
3.2 daylight, timezone, tzname
The daylight, timezone, and tzname variables are global timezone variables
used in time functions.
They are declared in the TIME.H include files as follows:
extern int daylight;
extern long timezone;
extern char *tzname [2];
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.
timezone Difference in seconds between Greenwich
mean time and the local time. Default
value is 28,800.
tzname[0] Three-letter time zone name derived from
the TZ environment variable. Default
value is "PST" (Pacific standard time).
tzname[1] Three-letter daylight-saving-time zone
name derived from the TZ environment
variable. Default value is PDT. If the
DST zone is omitted from TZ, tzname[1]
is an empty string.
3.3 _doserrno, errno, sys_errlist, sys_nerr
The _doserrno, errno, sys_errlist, and sys_nerr variables contain error
codes, and are used by the perror and _strerror routines to print error
information.
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 declarations are as follows:
extern int _doserrno;
extern int errno;
extern char *sys_errlist[ ];
extern int sys_nerr;
The errno variable is set to an integer value to reflect the type of error
that has occurred in a system-level call. Each errno value is associated
with an error message, which can be printed with the perror routine or
stored in a string with the strerror routine.
Note that only some routines set the errno variable. If a routine sets
errno, the description of the routine in the reference section says so
explicitly.
The value of errno reflects the error value for the last call that set
errno. However, this value is not necessarily reset by later successful
calls. To avoid confusion, test for errors immediately after a call.
The include file ERRNO.H contains the definitions of the errno values.
However, 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
involving 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 information. The sys_nerr variable tells how many elements
the sys_errlist array contains.
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.
Table 3.1 errno Values and Their Meanings
╓┌───────────┌──────────────────────────────────────────────────────────┌────►
Constant Meaning Value
─────────────────────────────────────────────────────────────────────────────
E2BIG Argument list too long 7
Constant Meaning Value
─────────────────────────────────────────────────────────────────────────────
E2BIG Argument list too long 7
EACCES Permission denied 13
EBADF Bad file number 9
EDEADLOCK Resource deadlock would occur 36
EDOM Math argument 33
EEXIST File exists 17
EINVAL Invalid argument 22
EMFILE Too many open files 24
ENOENT No such file or directory 2
ENOEXEC Exec format error 8
Constant Meaning Value
─────────────────────────────────────────────────────────────────────────────
ENOEXEC Exec format error 8
ENOMEM Not enough memory 12
ENOSPC No space left on device 28
ERANGE Result too large 34
EXDEV Cross-device link 18
─────────────────────────────────────────────────────────────────────────────
3.4 _fmode
The _fmode variable controls the default file-translation mode.
It is declared in the STDLIB.H include file as follows:
extern int _fmode;
By default, the value of _fmode is O_TEXT, causing files to be translated in
text mode (unless specifically opened or set to binary mode). When _fmode is
set to O_BINARY, the default mode is binary. You can set _fmode to the flag
O_BINARY by linking with BINMODE.OBJ or by assigning it the O_BINARY value.
3.5 _osmajor, _osminor, _osmode, _osversion
The _osmajor, _osminor, _osmode, and _osversion variables specify the
version number of the operating system or the current mode of operation.
They are declared in the STDLIB.H include file as follows:
extern unsigned char _osmajor;
extern unsigned char _osminor;
extern unsigned char _osmode;
extern unsigned char _osversion;
The _osmajor, _osminor, and _osversion variables specify the version number
of DOS or OS/2 currently in use. The _osmajor variable holds the "major"
version number and the _osminor variable stores the "minor" version number.
Thus, under DOS version 3.20, _osmajor is 3 and _osminor is 20. The
_osversion variable holds both values; its low byte contains the major
version number and its high byte the minor version number.
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
indicates real mode operation and a value of OS2_MODE indicates protected
operation.
3.6 environ
The environ variable is a pointer to the strings in the process environment.
It is declared in the STDLIB.H include file as follows:
extern char *environ [ ];
The environ variable provides access to memory areas containing
process-specific information.
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 operating-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
settings, the environment table changes size; its location in memory may
also change, depending on the program's memory requirements. The environ
variable 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
termination 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.
Standard Type Description
────────────────────────────────────────────────────────────────────────────
clock_t The clock_t type, defined in TIME.H,
stores time values. It is used by the
clock function.
complex The complex structure, defined in
MATH.H, stores the real and imaginary
parts of complex numbers. It is used by
the cabs function.
diskfree_t The diskfree_t structure, defined in
DOS.H, stores disk information used by
the _dos_getdiskfree routine.
diskinfo_t The diskinfo_t structure, defined in
BIOS.H, records information about disk
drives returned by the _bios_disk
routine.
div_t, ldiv_t The div_t and ldiv_t structures, defined
in STDLIB.H, store the values returned
by the div and ldiv functions,
respectively.
dosdate_t The dosdate_t structure, defined in
DOS.H, records the current system date
used in the _dos_getdate and
_dos_setdate routines.
dostime_t The dostime_t structure, defined in
DOS.H, records the current system time
used in the _dos_gettime and
_dos_settime routines.
DOSERROR The DOSERROR structure, defined in
DOS.H, stores values returned by DOS
system call 59H (available under DOS
versions 3.0 and later).
exception The exception structure, defined in
MATH.H, stores error information for
math routines. It is used by the matherr
routine.
FILE The FILE structure, defined in STDIO.H,
is the structure used in all stream
input and output operations. The fields
of the FILE structure store information
about the current state of the stream.
find_t The find_t structure, defined in DOS.H,
stores file-attribute information
returned by the _dos_findfirst and
_dos_findnext routines.
fpos_t The fgetpos and fsetpos functions use
the fpos_t object type, defined in
STDIO.H, to record all the information
necessary to uniquely specify every
position within the file.
jmp_buf The jmp_buf type, defined in SETJMP.H,
is an array type rather than a structure
type. A buffer of this type is used by
the setjmp and longjmp routines to save
and restore the program
environment.
lconv The lconv type is a structure containing
formatting rules for numeric values in
different countries. It is defined in
LOCALE.H.
onexit_t The onexit routine is declared as an
onexit_t pointer type, which is defined
in STDLIB.H.
ptrdiff_t The ptrdiff_t type is used for the
signed integral result of the
subtraction of two pointers.
REGS The REGS union, defined in DOS.H, stores
byte and word register values to be
passed to and returned from calls to the
DOS interface functions.
sig_atomic_t The sig_atomic_t type, defined in
SIGNAL.H, is the integral type of an
object that can be modified as an atomic
entity, even in the presence of
asynchronous interrupts. It is used in
conjunction with the signal routine.
size_t The size_t type, defined in STDDEF.H and
several other include files, is the
unsigned integral result of the sizeof
operator.
SREGS The SREGS structure, defined in DOS.H,
stores the values of the ES, CS, SS, and
DS registers. This structure is used by
the DOS interface functions that require
segment register values (int86x, intdosx
, and segread).
stat The stat structure, defined in
SYS\STAT.H, contains file-status
information returned by the stat and
fstat routines.
time_t The time_t type, defined in TIME.H,
represents time values in the mktime and
time routines.
timeb The timeb structure, defined in
SYS\TIMEB.H, is used by the ftime
routine to store the current system
time.
tm The tm structure, defined in TIME.H, is
used by the asctime, gmtime, and
localtime functions to store and
retrieve time information.
utimbuf The utimbuf structure, defined in
SYS\UTIME.H, stores file access and
modification times used by the utime
function to change file-modification
dates.
va_list The va_list array type, defined in
STDARG.H, is used to hold information
needed by the va_arg macro and the
va_end routine. The called function
declares a variable of type va_list,
which may be passed as an argument to
another function.
PART II 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 provided with the
Microsoft C Professional Development System.
Each reference entry gives syntax, return values, and other useful
information about the library functions. Information on compatibility is
supplied to assist you in writing portable programs.
About the Run-Time Reference
The following pages describe, in alphabetical order, the more than 400
functions in the Microsoft run-time library. In some cases, related routines
are clustered in the same description. For example, the based, near, and far
versions of _heapwalk are in the same discussion, as are the regular and
long double versions of the math functions, such as acos and atan.
Differences are noted where appropriate. Refer to Chapter 2, "Run-Time
Routines by Category," or to the index to locate any function that does not
appear in the expected position within the alphabetical reference.
The discussion of each function (or group of functions) is divided into the
following sections:
■ Description. Summarizes the routine's effect, names the include
file(s) containing its declaration, illustrates the syntax, and
briefly describes the arguments.
■ Remarks. Gives a more detailed description of the routine and how it
is used.
■ Return Value. Describes the value returned by the routine.
■ Compatibility. Tells whether the routine is compatible with ANSI C,
MS-DOS, OS/2, UNIX, and XENIX.
■ See Also. Names related routines.
■ Example. Gives a complete program showing the use of the routine.
abort
────────────────────────────────────────────────────────────────────────────
Description
Aborts the current process and returns an error code.
#include <process.h> Required only for function declarations;
#include <stdlib.h> use either PROCESS.H or STDLIB.H
void abort( void );
Remarks
The abort function prints the message
abnormal program termination
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 function. 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.
Compatibility
ANSI DOS OS/2 UNIX XENIX
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
Example
/* ABORT.C: This tries to open a file and aborts if the attempt fails. */
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *stream;
if( (stream = fopen( "NOSUCHF.ILE", "r" )) == NULL )
{
perror( "Couldn't open file" );
abort();
}
else
fclose( stream );
}
Output
Couldn't open file: No such file or directory
abnormal program termination
abs
────────────────────────────────────────────────────────────────────────────
Description
Calculates the absolute value.
#include <stdlib.h> Required only for function declarations;
#include <math.h> use either STDLIB.H or MATH.H
int abs( int n );
n Integer value
Remarks
The abs function returns the absolute value of its integer argument n.
Return Value
The abs function returns the absolute value of its argument. There is no
error return.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
cabs, fabs, labs
Example
/* ABS.C: This program computes and displays the absolute values of
* several numbers.
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
int ix = -4, iy;
long lx = -41567L, ly;
double dx = -3.141593, dy;
iy = abs( ix );
printf( "The absolute value of %d is %d\n", ix, iy);
ly = labs( lx );
printf( "The absolute value of %ld is %ld\n", lx, ly);
dy = fabs( dx );
printf( "The absolute value of %f is %f\n", dx, dy );
}
Output
The absolute value of -4 is 4
The absolute value of -41567 is 41567
The absolute value of -3.141593 is 3.141593
access
────────────────────────────────────────────────────────────────────────────
Description
Determines file-access permission.
#include <io.h> Required only for function declarations
#include <errno.h> Required for definition of errno
constants
int access( char *pathname, int mode );
pathname File or directory path name
mode Permission setting
Remarks
With files, the access function determines 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
────────────────────────────────────────────────────────────────────────────
00 Check for existence only
02 Check for write permission
04 Check for read permission
06 Check for read and write permission
With directories, access determines 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 permission
setting does not allow the specified
access.
ENOENT File or path name not found.
Compatibility
▼ ANSI DOS OS/2 UNIX XENIX
See Also
chmod, fstat, open, stat
Example
/* ACCESS.C: This example uses access to check the file named "data"
* to see if it exists and if writing is allowed.
*/
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
void main()
{
/* Check for existence */
if( (access( "access.c", 0 )) != -1 )
{
printf( "File exists\n" );
/* Check for write permission */
if( (access( "access.c", 2 )) != -1 )
printf( "File has write permission\n" );
}
}
Output
File exists
File has write permission
acos Functions
────────────────────────────────────────────────────────────────────────────
Description
Calculate the arccosine.
#include <math.h>
#include <errno.h> Required for definition of errno
constant
double acos( double x );
long double acosl( long double x );
x Value whose arccosine is to be
calculated
Remarks
The acos functions return the arccosine of x in the range 0 to π radians.
The value of x must be between -1 and 1. The acosl function is the 80-bit
counterpart, which 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
The acos functions return the arccosine result. If x is less than -1 or
greater than 1, the function sets errno 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
ANSI DOS OS/2 UNIX XENIX
acosl
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
asin functions, atan functions, cos functions, matherr, sin functions, tan
functions
Example
/* ASINCOS.C: This program prompts for a value in the range -1 to 1.
* Input values outside this range will produce DOMAIN error messages.
* If a valid value is entered, the program prints the arcsine and the
* arccosine of that value.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
void main()
{
double x, y;
printf( "Enter a real number between -1 and 1: " );
scanf( "%lf", &x );
y = asin( x );
printf( "Arcsine of %f = %f\n", x, y );
y = acos( x );
printf( "Arccosine of %f = %f\n", x, y );
}
Output
Enter a real number between -1 and 1: .32696
Arcsine of 0.326960 = 0.333085
Arccosine of 0.326960 = 1.237711
alloca
────────────────────────────────────────────────────────────────────────────
Description
Allocates memory on the stack.
#include <malloc.h> Required only for function declarations
void *alloca( size_t size );
size Bytes to be allocated from stack
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 /O options), the stack pointer may not be restored properly in functions
that have no local variables and that also reference the alloca function.
The following program demonstrates the problem:
/* Compile with CL /Lp /AM /Ox /Fc */
#include <malloc.h>
void main( void )
{
func( 10 );
}
void func( register int i )
{
alloca( i );
}
To ensure that the stack pointer is properly restored, make sure that any
function referencing 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.
Compatibility
▼ ANSI DOS OS/2 UNIX ▼ XENIX
See Also
calloc functions, malloc functions, realloc functions
Example
/* ALLOCA.C: This program checks the stack space available before
* and after using the alloca function to allocate space on the stack.
*/
#include <malloc.h>
#include <stdio.h>
void main()
{
char *buffer;
printf( "Bytes available on stack: %u\n", stackavail() );
/* Allocate memory for string. */
buffer = alloca( 120 * sizeof( char ) );
printf( "Enter a string: " );
gets( buffer );
printf( "You entered: %s\n", buffer );
printf( "Bytes available on stack: %u\n", stackavail() );
}
Output
Bytes available on stack: 2028
Enter a string: How much stack space will this string take?
You entered: How much stack space will this string take?
Bytes available on stack: 1902
_arc Functions
────────────────────────────────────────────────────────────────────────────
Description
Draw elliptical arcs.
#include <graph.h>
short _far _arc( short x1, short y1, short x2, short y2, short x3,
short y3, short x4, short y4 );
short _far _arc_w( double x1, double y1, double x2, double y2, double x3,
double y3, double x4, double y4 );
short _far _arc_wxy( struct _wxycoord _far *pwxy1,
struct _wxycoord _far *pwxy2,
struct _wxycoord _far *pwxy3, struct _wxycoord _far *pwxy4);
x1, y1 Upper-left corner of bounding rectangle
x2, y2 Lower-right corner of bounding rectangle
x3, y3 Second point of start vector (center of
bounding rectangle is first point)
x4, y4 Second point of end vector (center of
bounding rectangle is first point)
pwxy1 Upper-left corner of bounding rectangle
pwxy2 Lower-right corner of bounding rectangle
pwxy3 Second point of start vector (center of
bounding rectangle is first point)
pwxy4 Second point of end vector (center of
bounding rectangle is first point)
Remarks
The _arc functions draw elliptical arcs. The center of the arc is the center
of the bounding rectangle, which is defined by points (x1, y1) and (x2, y2)
for _arc and _arc_w and by points pwxy1 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.
Return Value
These functions return a nonzero value if the arc is successfully drawn;
otherwise, they return 0.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_ellipse functions, _lineto functions, _pie functions, _rectangle
functions, _setcolor
Example
/* ARC.C: This program draws a simple arc. */
#include <graph.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
short x, y;
struct xycoord xystart, xyend, xyfill;
/* Find a valid graphics mode */
if( !_setvideomode( _MAXRESMODE ) )
exit( 1 );
/* Draw arcs */
x = 100; y = 100;
_arc( x - 60, y - 60, x, y, x - 30, y - 60, x - 60, y - 30 );
_arc( x + 60, y + 60, x, y, x, y + 30, x + 30, y );
/* Get endpoints of second arc and enclose the figure, then fill it. */
_getarcinfo( &xystart, &xyend, &xyfill );
_moveto( xystart.xcoord, xystart.ycoord );
_lineto( xyend.xcoord, xyend.ycoord );
_floodfill( xyfill.xcoord, xyfill.ycoord, _getcolor() );
getch();
_setvideomode( _DEFAULTMODE );
}
asctime
────────────────────────────────────────────────────────────────────────────
Description
Converts a tm time structure to a character string.
#include <time.h>
char *asctime( const struct tm *timeptr );
timeptr Time/date structure
Remarks
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)
int tm_mday Day of the month (0 -31)
int tm_mon Months since January (0 -11)
int tm_year Years since 1900
int tm_wday Days since Sunday (0 - 6)
int tm_yday Days since January 1 (0 -365)
int tm_isdst Daylight-saving-time flag
The string result produced by asctime contains exactly 26 characters and has
the form of the following example:
Wed Jan 02 02:03:55 1980\n\0
A 24-hour clock is 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 destroys the
result of the previous call.
Return Value
The asctime function returns a pointer to the character string result. There
is no error return.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
ctime, ftime, gmtime, localtime, time, tzset
Example
/* ASCTIME.C: This program places the system time in the long integer
aclock,
* translates it into the structure newtime and then converts it to
* string form for output, using the asctime function.
*/
#include <time.h>
#include <stdio.h>
struct tm *newtime;
time_t aclock;
void main()
{
time( &aclock ); /* Get time in seconds */
newtime = localtime( &aclock ); /* Convert time to struct tm form
*/
/* Print local time as a string */
printf( "The current date and time are: %s\n", asctime( newtime ) );
}
Output
The current date and time are: Thu Jun 15 06:57:59 1989
asin Functions
────────────────────────────────────────────────────────────────────────────
Description
Calculate the arcsine.
#include <math.h>
#include <errno.h>
double asin( double x );
long double asinl( long double x );
x Value whose arcsine is to be calculated
Remarks
The asin functions calculate the arcsine of x in the range -π/2 to π/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, 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
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
ANSI DOS OS/2 UNIX XENIX
asinl
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
acos functions, atan functions, cos functions, matherr, sin functions, tan
functions
Example
/* ASINCOS.C: This program prompts for a value in the range -1 to 1.
* Input values outside this range will produce DOMAIN error messages.
* If a valid value is entered, the program prints the arcsine and the
* arccosine of that value.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
void main()
{
double x, y;
printf( "Enter a real number between -1 and 1: " );
scanf( "%lf", &x );
y = asin( x );
printf( "Arcsine of %f = %f\n", x, y );
y = acos( x );
printf( "Arccosine of %f = %f\n", x, y );
}
Output
Enter a real number between -1 and 1: .32696
Arcsine of 0.326960 = 0.333085
Arccosine of 0.326960 = 1.237711
assert
────────────────────────────────────────────────────────────────────────────
Description
Prints an error message and aborts the program.
#include <assert.h>
#include <stdio.h>
void assert( int expression );
expression C expression specifying assertion being
tested
Remarks
The assert routine prints a diagnostic message and calls the abort routine
if expression is false (0). The diagnostic message has the form
Assertion failed: expression, file filename, line linenumber
where filename is the name of the source file and linenumber 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 errors. 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" identifier NDEBUG can be used to remove
assert calls from the program. If NDEBUG is defined (by any value) with a /D
command-line option or with a #define directive, the C preprocessor removes
all assert calls from the program source.
The assert routine is implemented as a macro.
Return Value
None.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
abort, raise, signal
Example
/* ASSERT.C: In this program, the analyze_string function uses the
* assert function to test several conditions related to string and
* length. If any of the conditions fails, the program prints a
* message indicating what caused the failure.
*/
#include <stdio.h>
#include <assert.h>
#include <string.h>
void analyze_string( char *string ); /* Prototype */
void main()
{
char test1[] = "abc", *test2 = NULL, test3[] = "";
printf ( "Analyzing string '%s'\n", test1 );
analyze_string( test1 );
printf ( "Analyzing string '%s'\n", test2 );
analyze_string( test2 );
printf ( "Analyzing string '%s'\n", test3 );
analyze_string( test3 );
}
/* Tests a string to see if it is NULL, empty, or longer than 0 characters
*/
void analyze_string( char * string )
{
assert( string != NULL ); /* Cannot be NULL */
assert( *string != '\0' ); /* Cannot be empty */
assert( strlen( string ) > 2 ); /* Length must be greater than 2 */
}
Output
Analyzing string 'abc'
Analyzing string '(null)'
Assertion failed: string != NULL, file assert.c, line 28
abnormal program termination
atan Functions
────────────────────────────────────────────────────────────────────────────
Description
Calculate the arctangent of x (atan and atanl) and the arctangent of y/x
(atan2 and atan2l).
#include <math.h>
double atan( double x );
double atan2( double y, double x );
long double atanl( long double x );
long double atan2l( long double y, long double x );
x, y Any number
Remarks
The atan family of functions calculates the arctangent of x, and the atan2
family of functions calculates the arctangent of y/x. The atan group returns
a value in the range -π/2 to π/2 radians, and the atan2 group returns a
value in the range -π toπ 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 atan2l 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.
Compatibility
atan, atan2
ANSI DOS OS/2 UNIX XENIX
atanl, atan2l
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
acos functions, asin functions, cos functions, matherr, sin functions, tan
functions
Example
/* ATAN.C: This program calculates the arctangent of 1 and -1. */
#include <math.h>
#include <stdio.h>
#include <errno.h>
void main()
{
double x1, x2, y;
printf( "Enter a real number: " );
scanf( "%lf", &x1 );
y = atan( x1 );
printf( "Arctangent of %f: %f\n", x1, y );
printf( "Enter a second real number: " );
scanf( "%lf", &x2 );
y = atan2( x1, x2 );
printf( "Arctangent of %f / %f: %f\n", x1, x2, y );
}
Output
Enter a real number: -862.42
Arctangent of -862.420000: -1.569637
Enter a second real number: 78.5149
Arctangent of -862.420000 / 78.514900: -1.480006
atexit
────────────────────────────────────────────────────────────────────────────
Description
Processes the specified function at exit.
#include <stdlib.h> Required only for function declarations
int atexit( void ( *func )( void ) );
func Function to be called
Remarks
The atexit function is passed the address of a function (func) to be called
when the program 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).
Compatibility
ANSI DOS OS/2 ▼ UNIX ▼ XENIX
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.
See Also
abort, exit, _exit, onexit
Example
/* ATEXIT.C: This program pushes four functions onto the stack of
functions
* to be executed when atexit is called. When the program exits, these
* programs are executed on a "last in, first out" basis.
*/
#include <stdlib.h>
#include <stdio.h>
void fn1( void ), fn2( void ), fn3( void ), fn4( void );
void main()
{
atexit( fn1 );
atexit( fn2 );
atexit( fn3 );
atexit( fn4 );
printf( "This is executed first.\n" );
}
void fn1()
{
printf( "next.\n" );
}
void fn2()
{
printf( "executed " );
}
void fn3()
{
printf( "is " );
}
void fn4()
{
printf( "This " );
}
Output
This is executed first.
This is executed next.
atof, atoi, atol, _atold
────────────────────────────────────────────────────────────────────────────
Description
Convert strings to double (atof), long double (_atold) integer (atoi), or
long (atol).
#include <math.h> atof, _atold
#include <stdlib.h> atof, _atold, atoi, atol
double atof( const char *string );
long double _atold( const char *string );
int atoi( const char *string );
long atol( const char *string );
string String to be converted
Remarks
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:
[[whitespace]] [[{sign}]] [[ IK0digits]] [[.digits]]
[[{d| D | e | E}[[sign]digits]]
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
optionally signed decimal integer.
The atoi and atol functions do not recognize decimal points or exponents.
The string argument for these functions has the form
[[whitespace]] [[sign]]digits
where whitespace, sign, and digits are exactly as described above for atof.
Return Value
Each function returns the double, long double, int, or long value produced
by interpreting the input characters as a number. The return value is 0 (for
atoi), 0L (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.
Compatibility
atof, atoi, atol
ANSI DOS OS/2 UNIX XENIX
_atold
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
ecvt, fcvt, gcvt
Example
/* ATOF.C: This program shows how numbers stored as strings can be
* converted to numeric values using the atof, atoi, and atol functions.
*/
#include <stdlib.h>
#include <stdio.h>
void main()
{
char *s; double x; int i; long l;
s = " -2309.12E-15"; /* Test of atof */
x = atof( s );
printf( "atof test: ASCII string: %s\tfloat: %e\n", s, x );
s = "7.8912654773d210"; /* Test of atof */
x = atof( s );
printf( "atof test: ASCII string: %s\tfloat: %e\n", s, x );
s = " -9885 pigs"; /* Test of atoi */
i = atoi( s );
printf( "atoi test: ASCII string: %s\t\tinteger: %d\n", s, i );
s = "98854 dollars"; /* Test of atol */
l = atol( s );
printf( "atol test: ASCII string: %s\t\tlong: %ld\n", s, l );
}
Output
atof test: ASCII string: -2309.12E-15 float: -2.309120e-012
atof test: ASCII string: 7.8912654773d210 float: 7.891265e+210
atoi test: ASCII string: -9885 pigs integer: -9885
atol test: ASCII string: 98854 dollars long: 98854
bdos
────────────────────────────────────────────────────────────────────────────
Description
Invokes the DOS system call.
#include <dos.h>
int bdos( int dosfunc, unsigned int dosdx, unsigned int dosal );
dosfunc Function number
dosdx DX register value
dosal AL register value
Remarks
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 21H 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 Value
The bdos function returns the value of the AX register after the system call
has completed.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
intdos, intdosx
Example
/* BDOS.C: This example calls DOS function 0x9 (display string)
* to display a $-terminated string.
*/
#include <dos.h>
/* Function 0x09 assumes that DS will contain segment of the string.
* This will be true for all memory models if the string is declared near.
*/
char _near str[] = "Hello world!\r\n$";
void main()
{
/* Offset of string must be in DX, segment in DS. AL is not needed,
* so 0 is used.
*/
bdos( 0x09, (int)str, 0 );
}
Output
Hello world!
_beginthread
────────────────────────────────────────────────────────────────────────────
Description
Begins thread in OS/2 process.
#include <process.h> Multithread version of PROCESS.H
#include <stddef.h> Declaration of threadid variable
int _far _beginthread( void( _far *start_address )( void _far * ),
void _far *stack_bottom, unsigned stack_size, void _far *arglist );
start_address Starting address
stack_bottom Address of the thread stack
stack_size Stack size for thread
arglist Argument list for thread
Remarks
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.
The stack_size argument must be even and nonzero.
If you are writing multithread programs that make C run-time calls from
child threads, be sure to allocate a sufficiently large stack. For example,
the C function printf requires more than 500 bytes of stack space. To be
safe, allocate at least 2,048 bytes for a thread's stack. (If your child
thread makes no run-time calls, stack space is generally not a problem.)
As a general rule, you should have 2K of stack space free when calling any
API (Applications Program Interface) routine (e.g., OS/2 system calls).
The arglist is a parameter, the size of a far pointer, to be passed to the
newly created thread. Typically it is the address of a data item, such as a
character string, to be passed to the new thread. The arglist may be NULL if
not needed, but _beginthread should be provided with some value to pass to
the child thread.
All threads will be terminated if any thread calls abort, exit, _exit, or
DosExit. A good practice in multithread programming is to make the first
thread the main thread and wait until other threads have terminated before
exiting the program.
The OS/2 function DosCreateThread should not be called directly to create
threads. The _beginthread function performs 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 return value of -1 indicates an error, and errno is set to one
of the following values:
Value Meaning
────────────────────────────────────────────────────────────────────────────
EAGAIN Too many threads
EINVAL Invalid argument, "bad stack"
Compatibility
▼ ANSI ▼ DOS OS/2 ▼ UNIX ▼ XENIX
See Also
_endthread
Example
/* BEGTHRD.C illustrates multiple threads using functions:
* _beginthread _endthread
*
* Also the global variable:
* _threadid
*
* This program requires the multithread library. For example, compile
* with the following command line:
* CL /MT THREADS.C
*/
#define INCL_NOCOMMON
#define INCL_NOPM
#define INCL_DOSPROCESS
#define INCL_VIO
#include <os2.h>
#include <process.h> /* _beginthread, _endthread */
#include <stddef.h> /* _threadid */
#include <stdlib.h>
#include <conio.h>
void Bounce( int c ); /* Prototypes */
void CheckKey( void *dummy );
/* GetRandom returns a random integer between min and max. */
#define GetRandom( min, max ) ((rand() % (int)(((max) + 1) - (min))) +
(min))
#define STACK_SIZE 4096
BOOL repeat = TRUE; /* Global repeat flag and video variable */
VIOMODEINFO vmi = { sizeof( VIOMODEINFO ) };
void main()
{
PCHAR stack;
CHAR ch = 'A';
/* Get display screen's text row and column information. */
VioGetMode( &vmi, 0 );
/* Launch CheckKey thread to check for terminating keystroke. */
_beginthread( CheckKey, NULL, STACK_SIZE, NULL );
/* Loop until CheckKey terminates program. */
while( repeat )
{
/* On first loops, launch character threads. */
_beginthread( Bounce, NULL, STACK_SIZE, (void *)ch++ );
/* Wait one second between loops. */
DosSleep( 1000L );
}
}
/* CheckKey - Thread to wait for a keystroke, then clear repeat flag. */
void CheckKey( void *dummy )
{
getch();
repeat = 0; /* _endthread implied */
}
/* Bounce - Thread to create and control a colored letter that moves
* around on the screen.
*
* Params: ch - the letter to be moved
*/
void Bounce( int ch )
{
/* Generate letter and color attribute from thread argument. */
char blankcell[2] = { 0x20, 0x07 };
char blockcell[2] = { ch , (ch % 16) + 1 };
int xold, xcur, yold, ycur;
BOOL first = TRUE;
/* Seed random number generator and get initial location. */
srand( *_threadid );
xcur = GetRandom( 0, vmi.col - 1 );
ycur = GetRandom( 0, vmi.row - 1 );
while( repeat )
{
/* Pause between loops. */
DosSleep( 100L );
/* Blank out our old position on the screen, and draw new letter.
*/
if( first )
first = FALSE;
else
VioWrtCellStr( blankcell, 2, yold, xold, 0 );
VioWrtCellStr( blockcell, 2, ycur, xcur, 0 );
/* Increment the coordinate for next placement of the block. */
xold = xcur;
yold = ycur;
xcur += GetRandom( -1, 1 );
ycur += GetRandom( -1, 1 );
/* Correct placement (and beep) if about to go off the screen. */
if( xcur < 0 )
xcur = 1;
else if( xcur == vmi.col )
xcur = vmi.col - 2;
else if( ycur < 0 )
ycur = 1;
else if( ycur == vmi.row )
ycur = vmi.row - 2;
/* If not at screen border, continue, otherwise beep. */
else
continue;
DosBeep( (ch - 'A') * 100, 175 );
}
/* _endthread given (but not really needed) to terminate. */
_endthread();
}
Bessel Functions
────────────────────────────────────────────────────────────────────────────
Description
Compute the Bessel function.
#include <math.h>
double j0( double x );
double j1( double x );
double jn( int n, double x );
double y0( double x );
double y1( double x );
double yn( int n, double x );
long double _j0l( long double x );
long double _jnl( int n, long double x );
long double _j1l( long double x );
long double _y0l( long double x );
long double _y1l( long double x );
long double _ynl( int n, long double x );
x Floating-point value
n Integer order
Remarks
The j0, j1, and jn routines return Bessel functions of the first kind─orders
0, 1, and n, respectively.
The y0, y1, 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, 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 Bessel functions are explained more fully in most mathematics reference
books, such as the Handbook of Mathematical Functions (Abramowitz and
Stegun; Washington: U.S. Government Printing Office, 1964). These functions
are commonly used in the mathematics of electromagnetic wave theory.
Return Value
These functions return the result of a Bessel function of x.
For y0, y1, 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.
Compatibility
j0, j1, jn, y0, y1, yn
▼ ANSI DOS OS/2 UNIX XENIX
_j0l, _j1l, _jnl, _y0l, _y1l, _ynl
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
matherr
Example
/* BESSEL.C: This program illustrates Bessel functions, including:
* j0 j1 jn y0 y1 yn
*/
#include <math.h>
#include <stdio.h>
void main()
{
double x = 2.387;
int n = 3, c;
printf( "Bessel functions for x = %f:\n", x );
printf( " Kind\t\tOrder\t\Function\tResult\n\n" );
printf( " First\t\t0\tj0( x )\t\t%f\n", j0( x ) );
printf( " First\t\t1\tj1( x )\t\t%f\n", j1( x ) );
for( c = 2; c < 5; c++ )
printf( " First\t\t%d\tjn( n, x )\t%f\n", c, jn( c, x ) );
printf( " Second\t0\ty0( x )\t\t%f\n", y0( x ) );
printf( " Second\t1\ty1( x )\t\t%f\n", y1( x ) );
for( c = 2; c < 5; c++ )
printf( " Second\t%d\tyn( n, x )\t%f\n", c, yn( c, x ) );
}
Output
Bessel functions for x = 2.387000:
Kind Order Function Result
First 0 j0( x ) 0.009288
First 1 j1( x ) 0.522941
First 2 jn( n, x ) 0.428870
First 3 jn( n, x ) 0.195734
First 4 jn( n, x ) 0.063131
Second 0 y0( x ) 0.511681
Second 1 y1( x ) 0.094374
Second 2 yn( n, x ) -0.432608
Second 3 yn( n, x ) -0.819314
Second 4 yn( n, x ) -1.626833
_bfreeseg
────────────────────────────────────────────────────────────────────────────
Description
Frees a specified based heap.
#include <malloc.h> Required only for function declarations
int _bfreeseg( _segment seg );
seg Segment selected
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.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
_bheapseg, calloc functions, free functions, malloc functions, realloc
functions
Example
/* BHEAPSEG.C: This program C illustrates dynamic allocation of based
* memory using functions _bheapseg, _bfreeseg, _bmalloc, and _bfree.
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
void main()
{
_segment seg;
char _based( seg ) *outstr, _based( seg ) *instr;
char _based( seg ) *pout, _based( seg ) *pin;
char tmpstr[80];
int len;
printf( "Enter a string: " );
gets( tmpstr );
/* Request a based heap. Use based so that memory won't be taken from
* near heap.
*/
if( (seg = _bheapseg( 1000 )) == _NULLSEG )
exit( 1 );
/* Allocate based memory for two strings. */
len = strlen( tmpstr );
if( ((instr = _bmalloc( seg, len + 1 )) == _NULLOFF) ||
((outstr = _bmalloc( seg, len + 1 )) == _NULLOFF) )
exit( 1 );
/* Copy a lowercased string to dynamic memory. The based memory is
* far when addressed as a whole.
*/
_fstrlwr( _fstrcpy( (char _far *)instr, (char _far *)tmpstr ) );
/* Copy input string to output string in reversed order. When reading
* and writing individual characters from a based heap, the compiler
will
* try to process them as near, thus speeding up the processing.
*/
for( pin = instr + len - 1, pout = outstr;
pout < outstr + len; pin--, pout++ )
*pout = *pin;
*pout = '\0';
/* Display strings. Again strings as a whole are far. */
printf( "Input: %Fs\n", (char _far *)instr );
printf( "Output: %Fs\n", (char _far *)outstr );
/* Free blocks and release based heap. */
_bfree( seg, instr );
_bfree( seg, outstr );
_bfreeseg( seg );
}
Output
Enter a string: Was I god
Input: was i god
Output: dog i saw
_bheapseg
────────────────────────────────────────────────────────────────────────────
Description
Allocates a based heap.
#include <malloc.h> Required only for function declarations
_segment _bheapseg( size_t size );
size Segment size to allocate
Remarks
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 information.)
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.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
calloc functions, free functions, malloc functions, realloc functions
Example
/* BHEAPSEG.C: This program C illustrates dynamic allocation of based
* memory using functions _bheapseg, _bfreeseg, _bmalloc, and _bfree.
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
void main()
{
_segment seg;
char _based( seg ) *outstr, _based( seg ) *instr;
char _based( seg ) *pout, _based( seg ) *pin;
char tmpstr[80];
int len;
printf( "Enter a string: " );
gets( tmpstr );
/* Request a based heap. Use based so that memory won't be taken from
* near heap.
*/
if( (seg = _bheapseg( 1000 )) == _NULLSEG )
exit( 1 );
/* Allocate based memory for two strings. */
len = strlen( tmpstr );
if( ((instr = _bmalloc( seg, len + 1 )) == _NULLOFF) ||
((outstr = _bmalloc( seg, len + 1 )) == _NULLOFF) )
exit( 1 );
/* Copy a lowercased string to dynamic memory. The based memory is
* far when addressed as a whole.
*/
_fstrlwr( _fstrcpy( (char _far *)instr, (char _far *)tmpstr ) );
/* Copy input string to output string in reversed order. When reading
* and writing individual characters from a based heap, the compiler
will
* try to process them as near, thus speeding up the processing.
*/
for( pin = instr + len - 1, pout = outstr;
pout < outstr + len; pin--, pout++ )
*pout = *pin;
*pout = '\0';
/* Display strings. Again, strings as a whole are far. */
printf( "Input: %Fs\n", (char _far *)instr );
printf( "Output: %Fs\n", (char _far *)outstr );
/* Free blocks and release based heap. */
_bfree( seg, instr );
_bfree( seg, outstr );
_bfreeseg( seg );
}
Output
Enter a string: Was I god
Input: was i god
Output: dog i saw
_bios_disk
────────────────────────────────────────────────────────────────────────────
Description
Calls BIOS disk services using system call INT 0x13.
#include <bios.h>
unsigned _bios_disk( unsigned service, struct diskinfo_t *diskinfo );
service Disk function desired
diskinfo Disk parameters
Remarks
The _bios_disk routine uses system call INT 0x13 to provide several
disk-access functions. The service parameter selects the function desired,
while the diskinfo structure provides 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.
The diskinfo structure provides the following parameters:
Element Description
────────────────────────────────────────────────────────────────────────────
unsigned drive Drive number
unsigned head Head number
unsigned track Track number
unsigned sector Starting sector number
unsigned nsectors Number of sectors to read, write, or
compare
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
formatted in a single call. The buffer
field points to a set of sector markers.
The format of the markers depends on the
type of disk drive; see a technical
reference to the PC BIOS to determine
the marker format. There is no return
value.
_DISK_READ Reads one or more disk sectors into
memory. This service uses all fields 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 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 the
return value, as listed below:
Bits Meaning
────────────────────────────────────────────────────────────────────────────
0x01** Invalid request or a bad
command
0x02** Address mark not found
0x04** Sector not found
0x05** Reset failed
0x07** Drive parameter activity
failed
0x09** Direct Memory Access (DMA)
overrun
0x0A** Bad sector flag detected
0x10** Data read (ECC) error
0x11** Corrected data read (ECC)
error
0x20** Controller failure
0x40** Seek error
0x80** Disk timed out or failed
to respond
0xAA** Drive not ready
0xBB** Undefined error
0xCC** Write fault on drive
0xE0** Status error
_DISK_RESET Forces the disk controller to do a hard
reset, preparing for floppy-disk I/O.
This is useful after an error occurs in
another operation, such as a read. If
this service is specified, the
diskinfo argument is ignored.
_DISK_STATUS Obtains the status of the last disk
operation. If this service is specified,
the diskinfo argument is ignored.
_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
function 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).
Return Value
The _bios_disk function returns the value in the AX register after the BIOS
interrupt.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
Example
/* BDISK.C: This program first attempts to verify a disk by using an
* invalid disk head number. After printing the return value error code,
* the program verifies the disk by using a valid disk head code.
*/
#include <conio.h>
#include <stdio.h>
#include <bios.h>
void main()
{
unsigned status = 0;
struct diskinfo_t disk_info;
disk_info.drive = 0;
disk_info.head = 10; /* Invalid head number */
disk_info.track = 1;
disk_info.sector = 2;
disk_info.nsectors = 8;
printf( "Insert disk in drive A: and press any key\n" );
getch();
status = _bios_disk( _DISK_VERIFY, &disk_info );
printf( "Return value: 0x%.4x\n", status );
if( status & 0xff00 ) /* Error if high byte is 0 */
printf( "Seek error\n" );
else
printf( "No seek error\n" );
printf( "Press any key\n" );
getch();
disk_info.head = 0; /* Valid head number */
status = _bios_disk( _DISK_VERIFY, &disk_info );
printf( "Return value: 0x%.4x\n", status );
if( status & 0xff00 ) /* Error if high byte is 0 */
printf( "Seek error\n" );
else
printf( "No seek error\n" );
}
Output
Insert disk in drive A: and press any key
Return value: 0x0400
Seek error
Press any key
Return value: 0x0008
No seek error
_bios_equiplist
────────────────────────────────────────────────────────────────────────────
Description
Calls BIOS equipment-list service, using system call INT 0x11.
#include <bios.h>
unsigned _bios_equiplist( void );
Remarks
The _bios_equiplist routine uses system call INT 0x11 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
────────────────────────────────────────────────────────────────────────────
0 Any disk drive installed if true
1 True (1) if math coprocessor installed
2 -3 System RAM in 16K blocks (16-64K)
4 -5 Initial video mode
6 -7 Number of floppy-disk drives installed
(00 = 1, 01 = 2, etc.)
8 False (0) if and only if a Direct Memory
Access (DMA) chip is installed
9 -11 Number of RS232 serial ports installed
12 True (1) if and only if a game adapter
is installed
13 True (1) if and only if an internal
modem is installed
14 -15 Number of printers installed
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
Example
/* BEQUIPLI.C: This program checks for the presence of diskettes. */
#include <bios.h>
#include <stdio.h>
void main()
{
unsigned equipment;
equipment = _bios_equiplist();
printf( "Equipment bits: 0x%.4x\n", equipment );
if( equipment & 0x1000 ) /* Check for game adapter bit */
printf( "Game adapter installed\n" );
else
printf( "No game adapter installed\n" );
}
Output
Equipment bits: 0x4061
No game adapter installed
_bios_keybrd
────────────────────────────────────────────────────────────────────────────
Description
Calls BIOS keyboard services, using INT 0x16.
#include <bios.h>
unsigned _bios_keybrd( unsigned service );
service Keyboard function desired
Remarks
The _bios_keybrd routine uses system call INT 0x16 to access the keyboard
services. The service argument can be any of the following manifest
constants:
Constant Meaning
────────────────────────────────────────────────────────────────────────────
_KEYBRD_READ, Reads the next character from the
_NKEYBRD_READ keyboard. 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 character typed. The
high-order byte contains the keyboard
scan code for the character. The
_NKEYBRD_READ constant is used with
enhanced keyboards to obtain the scan
codes for function keys F11 and F12 and
the cursor control keys.
_KEYBRD_READY, Checks whether a keystroke 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 constant is
used with enhanced keyboards to obtain
the scan codes for function keys F11 and
F12 and the cursor control keys.
_KEYBRD_SHIFTSTATUS, Returns the current SHIFT-key status.
_NKEYBRD_SHIFTSTATUS Only the low-order byte of the return
value is affected. The
_NKEYBRD_SHIFTSTATUS constant is used to
get a full 16-bit status value. Any
combination of the following bits may be
set:
Bit Meaning if True
────────────────────────────────────────────────────────────────────────────
00H Rightmost SHIFT key pressed
01H Leftmost SHIFT key pressed
02H Either CTRL key pressed
3H Either ALT key pressed
04H SCROLL LOCK on
05H NUM LOCK on
06H CAPS LOCK on
07H In insert mode (INS)
08H Left CTRL key pressed
09H Left ALT key pressed
0AH Right CTRL key pressed
0BH Right ALT key pressed
0CH SCROLL LOCK key pressed
0DH NUM LOCK key pressed
0EH CAPS LOCK key pressed
0FH SYS REQ key pressed
Return Value
With the ...READ and ...SHIFTSTATUS arguments, the _bios_keybrd function
returns the contents of the AX register after the BIOS call.
With the ...READY argument, _bios_keybrd returns 0 if there is no key. If
there is a key, _bios_keybrd returns the key waiting to be read (i.e. the
same value as _KEYBRD_READ).
With the ...READ and the ...READY arguments, the _bios_keybrd function
returns -1 if CTRL+BREAK has been pressed and is the next keystroke to be
read.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
Example
/* BKEYBRD.C: This program prints a message on the screen until the
* right SHIFT key is pressed.
*/
#include <bios.h>
#include <stdio.h>
void main()
{
while( !(_bios_keybrd( _KEYBRD_SHIFTSTATUS ) & 0001) )
printf( "Use the right SHIFT key to stop this message\n" );
printf( "Right SHIFT key pressed\n" );
}
Output
Use the right SHIFT key to stop this message
Use the right SHIFT key to stop this message
Use the right SHIFT key to stop this message
Use the right SHIFT key to stop this message
Right SHIFT key pressed
_bios_memsize
────────────────────────────────────────────────────────────────────────────
Description
Calls the BIOS memory-size service, using system call INT 0x12.
#include <bios.h>
unsigned _bios_memsize( void );
Remarks
The _bios_memsize routine uses system call INT 0x12 to determine the total
amount of main memory installed.
Return Value
The routine returns the total amount of installed memory in 1K blocks. The
maximum return value is 640, representing 640K of main memory.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
Example
/* BMEMSIZE.C: This program displays the amount of memory installed. */
#include <bios.h>
#include <stdio.h>
void main()
{
unsigned memory;
memory = _bios_memsize();
printf ( "The amount of memory installed is: %dK\n", memory );
}
Output
The amount of memory installed is: 639K
_bios_printer
────────────────────────────────────────────────────────────────────────────
Description
Calls BIOS printer services using system call INT 0x17.
#include <bios.h>
unsigned _bios_printer( unsigned service, unsigned printer, unsigned data
);
service Printer function desired
printer Target printer port
data Output data
Remarks
The _bios_printer routine uses system call INT 0x17 to perform printer
output services for parallel printers. The printer argument specifies the
affected printer, where 0 is LPT1, 1 is LPT2, and so forth.
Some printers do not support the full set of signals. As a result, the "Out
of Paper" condition, 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:
Bit Meaning if True
────────────────────────────────────────────────────────────────────────────
0 Printer timed out
1 Not used
2 Not used
3 I/O error
4 Printer selected
5 Out of paper
6 Acknowledge
7 Printer not busy
Return Value
The _bios_printer function returns the value in the AX register after the
BIOS interrupt.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
Example
/* BPRINTER.C: This program checks the status of the printer attached to
* LPT1 when it is off line, then initializes the printer.
*/
#include <bios.h>
#include <conio.h>
#include <stdio.h>
#define LPT1 0
void main()
{
unsigned status;
printf ( "Place printer off line and press any key\n" );
getch();
status = _bios_printer( _PRINTER_STATUS, LPT1, 0 );
printf( "Status with printer off line: 0x%.4x\n\n", status );
printf( "Put the printer on line and then\n" );
printf( "Press any key to initialize printer\n" );
getch();
status = _bios_printer( _PRINTER_INIT, LPT1, 0 );
printf( "Status after printer initialized: 0x%.4x\n", status );
}
Output
Place printer off line and press any key
Status with printer off line: 0x0018
Put the printer on line and then
Press any key to initialize printer
Status after printer initialized: 0x0090
_bios_serialcom
────────────────────────────────────────────────────────────────────────────
Description
Calls BIOS communications services, using system call INT 0x14.
#include <bios.h>
unsigned _bios_serialcom( unsigned service, unsigned serial_port, unsigned
data );
service Communications service
serial_port Serial port to use
data Port configuration bits
Remarks
The _bios_serialcom routine uses system call INT 0x14 to provide serial
communications services. The serial_port argument is set to 0 for COM1, 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 programming 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
The data argument is ignored if service is set to _COM_RECEIVE or
_COM_STATUS. The data argument for _COM_INIT is created by combining (with
the OR operator) one or more of the following constants:
Constant Meaning
────────────────────────────────────────────────────────────────────────────
_COM_CHR7 7 data bits
_COM_CHR8 8 data bits
_COM_STOP1 1 stop bit
_COM_STOP2 2 stop bits
_COM_NOPARITY No parity
_COM_EVENPARITY Even parity
_COM_ODDPARITY Odd parity
_COM_110 110 baud
_COM_150 150 baud
_COM_300 300 baud
_COM_600 600 baud
_COM_1200 1,200 baud
_COM_2400 2,400 baud
_COM_4800 4,800 baud
_COM_9600 9,600 baud
The default value of data is 1 stop bit, no parity, and 110 baud.
Return Value
The function returns a 16-bit integer whose high-order byte contains status
bits. The meaning of the low-order byte varies, depending on the service
value. The high-order bits have the following meanings:
Bit Meaning if Set
────────────────────────────────────────────────────────────────────────────
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, 11, or 15 will be set.
When service is _COM_INIT or _COM_STATUS, the low-order bits are defined as
follows:
Bit Meaning if Set
────────────────────────────────────────────────────────────────────────────
7 Receive-line signal detected
6 Ring indicator
5 Data set ready
4 Clear to send
3 Change in receive-line signal detected
2 Trailing-edge ring indicator
1 Change in data-set-ready status
0 Change in clear-to-send status
Note that this function works only with IBM personal computers and true
compatibles.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
Example
/* BSERIALC.C: This program checks the status of serial port COM1. */
#include <bios.h>
#include <stdio.h>
void main()
{
unsigned com1_status;
com1_status = _bios_serialcom( _COM_STATUS, 0, 0 );
printf ( "COM1 status: 0x%.4x\n", com1_status );
}
Output
COM1 status: 0x6000
_bios_timeofday
────────────────────────────────────────────────────────────────────────────
Description
Calls BIOS time and date services, using system call INT 0x1A.
#include <bios.h>
unsigned _bios_timeofday( unsigned service, long *timeval );
service Time function desired
timeval Clock count
Remarks
The _bios_timeofday routine uses system call INT 0x1A 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 0;
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.
Return Value
The _bios_timeofday function returns the value in the AX register after the
BIOS interrupt.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
Example
/* BTIMEOFD.C: This program gets the current system clock count before and
after
* a "do-nothing" loop and displays the difference.
*/
#include <bios.h>
#include <stdio.h>
void main()
{
long i, begin_tick, end_tick;
_bios_timeofday( _TIME_GETCLOCK, &begin_tick );
printf( "Beginning tick count: %lu\n", begin_tick );
for( i = 1; i <= 900000; i++ )
;
_bios_timeofday( _TIME_GETCLOCK, &end_tick );
printf( "Ending tick count: %lu\n", end_tick );
printf( "Elapsed ticks: %lu\n", end_tick - begin_tick );
}
Output
Beginning tick count: 1114255
Ending tick count: 1114287
Elapsed ticks: 32
bsearch
────────────────────────────────────────────────────────────────────────────
Description
Performs binary search of a sorted array.
#include <stdlib.h> Required for ANSI compatibility
#include <search.h> Required only for function declarations
void *bsearch( const void *key, const void *base, size_t num, size_t
width,
int ( *compare )( const void *elem1, const void *elem2 ) );
key Object to search for
base Pointer to base of search data
num Number of elements
width Width of elements
compare Function that compares two elements:
elem1 and elem2
elem1 Pointer to the key for the search
elem2 Pointer to the array element to be
compared with the key
Remarks
The bsearch function performs 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 elements and returns a value specifying their relationship. The
bsearch function calls the compare routine one or more times during the
search, passing pointers to two array elements on each call. The routine
compares the elements, then returns one of the following values:
Value Meaning
────────────────────────────────────────────────────────────────────────────
< 0 elem1 less than elem2
= 0 elem1 identical to elem2
> 0 elem1 greater than elem2
If the array you are searching is not in ascending sort order, bsearch does
not work properly. 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 Value
The bsearch function returns a pointer to the first occurrence of key in the
array pointed to by base. If key is not found, the function returns NULL.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
lfind, lsearch, qsort
Example
/* BSEARCH.C: This program reads the command-line arguments, sorting them
* with qsort, and then uses bsearch to find the word "cat."
*/
#include <search.h>
#include <string.h>
#include <stdio.h>
int compare( char **arg1, char **arg2 ); /* Declare a function for
compare */
void main( int argc, char **argv )
{
char **result;
char *key = "cat";
int i;
/* Sort using Quicksort algorithm: */
qsort( (char *)argv, argc, sizeof( char * ), compare );
for( i = 0; i < argc; ++i ) /* Output sorted list */
printf( "%s ", argv[i] );
/* Find the word "cat" using a binary search algorithm: */
result = (char **)bsearch( (char *) &key, (char *)argv, argc,
sizeof( char * ), compare );
if( result )
printf( "\n%s found at %Fp\n", *result, result );
else
printf( "\nCat not found!\n" );
}
int compare( char **arg1, char **arg2 )
{
/* Compare all of both strings: */
return strcmpi( *arg1, *arg2 );
}
Output
[C:\LIBREF] bsearch dog pig horse cat human rat cow goat
bsearch cat cow dog goat horse human pig rat
cat found at 0292:0FD0
cabs, cabsl
────────────────────────────────────────────────────────────────────────────
Description
Calculate absolute value of a complex number.
#include <math.h>
double cabs( struct complex z );
long double cabsl( struct _complexl z );
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 equivalent to the following:
sqrt( z.x*z.x + z.y*z.y )
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 errno to ERANGE.
Compatibility
cabs
▼ ANSI DOS OS/2 UNIX XENIX
cabsl
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
abs, fabs, labs
Example
/* CABS.C: Using cabs, this program calculates the absolute value of
* a complex number.
*/
#include <math.h>
#include <stdio.h>
void main()
{
struct complex number = { 3.0, 4.0 };
double d;
d = cabs( number );
printf( "The absolute value of %f + %fi is %f\n",
number.x, number.y, d );
}
Output
The absolute value of 3.000000 + 4.000000i is 5.000000
calloc Functions
────────────────────────────────────────────────────────────────────────────
Description
Allocate an array in memory with elements initialized to 0.
#include <stdlib.h> For ANSI compatibility (calloc only)
#include <malloc.h> Required only for function declarations
void *calloc( size_t num, size_t size );
void _based( void ) *_bcalloc( _segment seg, size_t num, size_t size );
void _far *_fcalloc( size_t num, size_t size );
void _near *_ncalloc( size_t num, size_t size );
num Number of elements
size Length in bytes of each element
seg Segment selector
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.
Compatibility
calloc
ANSI DOS OS/2 UNIX XENIX
_bcalloc, _fcalloc, _ncalloc
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
free functions, halloc, hfree, malloc functions, realloc functions
Example
/* CALLOC.C: This program uses calloc to allocate space for 40 long
integers.
* It initializes each element to zero.
*/
#include <stdio.h>
#include <malloc.h>
void main()
{
long *buffer;
buffer = (long *)calloc( 40, sizeof( long ) );
if( buffer != NULL )
printf( "Allocated 40 long integers\n" );
else
printf( "Can't allocate memory\n" );
free( buffer );
}
Output
Allocated 40 long integers
ceil, ceill
────────────────────────────────────────────────────────────────────────────
Description
Calculate the ceiling of a value.
#include <math.h>
double ceil( double x );
long double ceill( long double x );
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, 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 the double or long double result. There is no error
return.
Compatibility
ceil
ANSI DOS OS/2 UNIX XENIX
ceill
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
floor, fmod
Example
/* FLOOR.C: This example displays the largest integers less than or equal
* to the floating-point values 2.8 and -2.8. It then shows the smallest
* integers greater than or equal to 2.8 and -2.8.
*/
#include <math.h>
#include <stdio.h>
void main()
{
double y;
y = floor( 2.8 );
printf( "The floor of 2.8 is %f\n", y );
y = floor( -2.8 );
printf( "The floor of -2.8 is %f\n", y );
y = ceil( 2.8 );
printf( "The ceil of 2.8 is %f\n", y );
y = ceil( -2.8 );
printf( "The ceil of -2.8 is %f\n", y );
}
Output
The floor of 2.8 is 2.000000
The floor of -2.8 is -3.000000
The ceil of 2.8 is 3.000000
The ceil of -2.8 is -2.000000
_cexit, _c_exit
────────────────────────────────────────────────────────────────────────────
Description
Perform clean-up operations and return without terminating the process.
#include <process.h>
void _cexit( void );
void _c_exit( void );
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 I/O 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, terminates 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 returns to caller, but
does not terminate the process
_c_exit Performs "quick" C library termination
procedures and returns to caller, but
does not terminate the process
Return Value
None.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
abort, atexit, exec functions, exit, onexit, spawn functions, system
cgets
────────────────────────────────────────────────────────────────────────────
Description
Gets a character string from the console.
#include <conio.h> Required only for function declarations
char *cgets( char *buffer );
buffer Storage location for data
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[0], must contain the maximum length (in
characters) of the string to be read. The array must contain enough elements
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 second array element, buffer[1].
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.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
getch, getche
Example
/* CGETS.C: This program creates a buffer and initializes the first byte
* to the size of the buffer - 2. Next, the program accepts an input
string
* using cgets and displays the size and text of that string.
*/
#include <conio.h>
#include <stdio.h>
void main()
{
char buffer[82] = { 80 }; /* Maximum characters in first byte */
char *result;
printf( "Input line of text, followed by carriage return:\n");
result = cgets( buffer ); /* Input a line of text */
printf( "\nLine length = %d\nText = %s\n", buffer[1], result );
}
Output
Input line of text, followed by carriage return:
This is some text
Line length = 17
Text = This is some text
_chain_intr
────────────────────────────────────────────────────────────────────────────
Description
Chains an interrupt from one handler to another.
#include <dos.h>
void _chain_intr( void( _interrupt _far *target )());
target Target interrupt routine
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 processing.
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 finished and you want the second interrupt routine to
terminate the interrupt call.
void _interrupt new_int( unsigned _es, unsigned _ds,
unsigned _di, unsigned _si,... )
{
++_di; /* Initial processing here */
_chain_intr( old_int ); /* New DI passed to old_int */
--_di; /* This is never executed */
}
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.
void _interrupt new_int( unsigned _es, unsigned _ds,
unsigned _di, unsigned _si,... )
{
++_di; /* Initial processing here */
(*old_int)(); /* New DI passed to old_int */
_asm mov _di, di /* Put real DI from old_int */
/* into _di for return */
}
Note that the real registers set by the old interrupt function are not
automatically set to the pseudoregisters of the new routine.
Use the _chain_intr function when you do not want to replace the default
interrupt handler, 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.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_getvect, _dos_keep, _dos_setvect
chdir
────────────────────────────────────────────────────────────────────────────
Description
Changes the current working directory.
#include <direct.h> Required only for function declarations
#include <errno.h> Required for errno constants
int chdir( char *dirname );
dirname Path name of new working directory
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:
chdir("c:\\temp");
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.
Compatibility
▼ ANSI DOS OS/2 UNIX XENIX
See Also
_dos_setdrive, mkdir, rmdir, system
Example
/* CHGDIR.C: This program uses the chdir function to verify that a
* given directory exists. Under real mode that directory also becomes
* the current directory. Under protected mode, it is only the default
* directory for the current process.
*/
#include <direct.h>
#include <stdio.h>
#include <stdlib.h>
void main( int argc, char *argv[] )
{
if( chdir( argv[1] ) )
printf( "Unable to locate the directory: %s\n", argv[1] );
else
system( "dir *.c" );
}
Output
[C:\LIBREF] chgdir \tmp
The volume label in drive C is OS2.
Directory of C:\TMP
DUP C 232 4-18-89 11:18a
TEST C 713 4-07-88 2:49p
2 File(s) 14155776 bytes free
_chdrive
────────────────────────────────────────────────────────────────────────────
Description
Changes the current working drive.
#include <direct.h> Required only for function declarations
int _chdrive( int drive );
drive Number of new working drive
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 (1=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.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
chdir, _dos_setdrive, _fullpath, _getcwd, _getdrive, mkdir, rmdir,
system
Example
/* GETDRIVE.C illustrates drive functions including:
* _getdrive _chdrive _getdcwd
*/
#include <stdio.h>
#include <conio.h>
#include <direct.h>
#include <stdlib.h>
void main()
{
int ch, drive, curdrive;
static char path[_MAX_PATH];
/* Save current drive. */
curdrive = _getdrive();
printf( "Available drives are: \n" );
/* If we can switch to the drive, it exists. */
for( drive = 1; drive <= 26; drive++ )
if( !_chdrive( drive ) )
printf( "%c: ", drive + 'A' - 1 );
while( 1 )
{
printf( "\nType drive letter to check or ESC to quit: " );
ch = getch();
if( ch == 27 )
break;
if( isalpha( ch ) )
putch( ch );
if( _getdcwd( toupper( ch ) - 'A' + 1, path, _MAX_PATH ) != NULL )
printf( "\nCurrent directory on that drive is %s\n", path );
}
/* Restore original drive. This is only necessary for DOS. Under OS/2
* the current drive of the calling process is always restored.
*/
_chdrive( curdrive );
printf( "\n" );
}
Output
Available drives are:
A: B: C:
Type drive letter to check or ESC to quit: q
Type drive letter to check or ESC to quit: a
Current directory on that drive is A:\
Type drive letter to check or ESC to quit: c
Current directory on that drive is C:\LIBREF
Type drive letter to check or ESC to quit:
chmod
────────────────────────────────────────────────────────────────────────────
Description
Changes the file-permission settings.
#include <sys\types.h>
#include <sys\stat.h>
#include <errno.h>
#include <io.h> Required only for function declarations
int chmod( char *filename, int pmode );
filename Path name of existing file
pmode Permission setting for file
Remarks
The chmod function changes the permission setting of the file specified by
filename. The permission 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 ( | ). The meaning of the pmode argument is as follows:
Value Meaning
────────────────────────────────────────────────────────────────────────────
S_IWRITE Writing permitted
S_IREAD Reading permitted
S_IREAD | S_IWRITE Reading and writing permitted
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 | S_IWRITE are equivalent.
Return Value
The chmod function returns the value 0 if the permission setting is
successfully changed. A return value of -1 indicates an error; in this case,
errno is set to ENOENT, indicating that the specified file could not be
found.
Compatibility
▼ ANSI DOS OS/2 UNIX XENIX
See Also
access, creat, fstat, open, stat
Example
/* CHMOD.C: This program uses chmod to change the mode of a file to
* read-only. It then attempts to modify the file.
*/
#include <sys\types.h>
#include <sys\stat.h>
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
void main()
{
/* Make file read-only: */
if( chmod( "CHMOD.C", S_IREAD ) == -1 )
perror( "File not found\n" );
else
printf( "Mode changed to read-only\n" );
system( "echo /* End of file */ >> CHMOD.C" );
/* Change back to read/write: */
if( chmod( "CHMOD.C", S_IWRITE ) == -1 )
perror( "File not found\n" );
else
printf( "Mode changed to read/write\n" );
}
Output
Mode changed to read-only
Access denied
Mode changed to read/write
chsize
────────────────────────────────────────────────────────────────────────────
Description
Changes the file size.
#include <io.h> Required only for function declarations
#include <errno.h>
int chsize( int handle, long size );
handle Handle referring to open file
size New length of file in bytes
Remarks
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 permits
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 determine the amount of free disk
space may receive inaccurate results.
Return Value
The chsize function returns the value 0 if the file size is successfully
changed. A return value of -1 indicates an error, and errno 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).
EBADF Specified file is read-only or an
invalid file handle.
ENOSPC No space is left on device.
Compatibility
▼ ANSI DOS OS/2 UNIX XENIX
See Also
close, creat, open
Example
/* CHSIZE.C: This program uses filelength to report the size of a
* file before and after modifying it with chsize.
*/
#include <io.h>
#include <fcntl.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <stdio.h>
void main()
{
int fh, result;
unsigned int nbytes = BUFSIZ;
/* Open a file */
if( (fh = open( "data", O_RDWR | O_CREAT, S_IREAD | S_IWRITE )) != -1 )
{
printf( "File length before: %ld\n", filelength( fh ) );
if( chsize( fh, 329678 ) == 0 )
printf( "Size successfully changed\n" );
else
printf( "Problem in changing the size\n" );
printf( "File length after: %ld\n", filelength( fh ) );
close( fh );
}
}
Output
File length before: 0
Size successfully changed
File length after: 329678
_clear87
────────────────────────────────────────────────────────────────────────────
Description
Gets and clears the floating-point status word.
#include <float.h>
unsigned int _clear87( void );
Remarks
The _clear87 function gets and clears the floating-point status word. The
floating-point status 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.
Return Value
The bits in the value returned indicate the floating-point status. See the
FLOAT.H 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
unpredictable 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.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
_control87, _status87
Example
/* CLEAR87.C: This program creates various floating-point problems,
* then uses _clear87 to report on these problems.
*/
#include <stdio.h>
#include <float.h>
void main()
{
double a = 1e-40, b;
float x, y;
printf( "Status: %.4x - clear\n", _clear87() );
/* Store into y is inexact and underflows: */
y = a;
printf( "Status: %.4x - inexact, underflow\n", _clear87() );
/* y is denormal: */
b = y;
printf( "Status: %.4x - denormal\n", _clear87() );
}
Output
Status: 0000 - clear
Status: 0030 - inexact, underflow
Status: 0002 - denormal
clearerr
────────────────────────────────────────────────────────────────────────────
Description
Resets the error indicator for a stream.
#include <stdio.h>
void clearerr( FILE *stream );
stream Pointer to FILE structure
Remarks
The clearerr function resets the error indicator and end-of-file indicator
for stream. Error indicators are not automatically cleared; once the error
indicator for a specified stream is set, operations on that stream continue
to return an error value until clearerr, fseek, fsetpos, or rewind is
called.
Return Value
None.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
eof, feof, ferror, perror
Example
/* CLEARERR.C: This program creates an error on the standard input
* stream, then clears it so that future reads won't fail.
*/
#include <stdio.h>
void main()
{
int c;
/* Create an error by writing to standard input. */
putc( 'c', stdin );
if( ferror( stdin ) )
{
perror( "Write error" );
clearerr( stdin );
}
/* See if read causes an error. */
printf( "Will input cause an error? " );
c = getc( stdin );
if( ferror( stdin ) )
{
perror( "Read error" );
clearerr( stdin );
}
}
Output
Write error: Error 0
Will input cause an error? n
_clearscreen
────────────────────────────────────────────────────────────────────────────
Description
Clears the specified area of the screen.
#include <graph.h>
void _far _clearscreen( short area );
area Target area
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 Clears and fills the entire screen
_GVIEWPORT Clears and fills only within the current
view port
_GWINDOW Clears and fills only within the current
text window
Return Value
None.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
_getbkcolor, _setbkcolor
Example
/* CLRSCRN.C */
#include <conio.h>
#include <graph.h>
#include <stdlib.h>
void main()
{
short xhalf, yhalf, xquar, yquar;
struct videoconfig vc;
/* Find a valid graphics mode. */
if( !_setvideomode( _MAXRESMODE ) )
exit( 1 );
_getvideoconfig( &vc );
xhalf = vc.numxpixels / 2;
yhalf = vc.numypixels / 2;
xquar = xhalf / 2;
yquar = yhalf / 2;
_setviewport( 0, 0, xhalf - 1, yhalf - 1 );
_rectangle( _GBORDER, 0, 0, xhalf - 1, yhalf - 1 );
_ellipse( _GFILLINTERIOR, xquar / 4, yquar / 4,
xhalf - (xquar / 4), yhalf - (yquar / 4) );
getch();
_clearscreen( _GVIEWPORT );
getch();
_setvideomode( _DEFAULTMODE );
}
clock
────────────────────────────────────────────────────────────────────────────
Description
Calculates the time used by the calling process.
#include <time.h>
clock_t clock( void );
Remarks
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 -1, cast as clock_t.
Compatibility
ANSI DOS OS/2 ▼ UNIX ▼ XENIX
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.
In previous versions of Microsoft C, the CLOCKS_PER_SEC constant was called
CLK_TCK.
See Also
difftime, time
Example
/* CLOCK.C: This example prompts for how long the program is to run and
* then continuously displays the elapsed time for that period.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void sleep( clock_t wait );
void main()
{
long i = 600000L;
clock_t start, finish;
double duration;
/* Delay for a specified time. */
printf( "Delay for three seconds\n" );
sleep( (clock_t)3 * CLOCKS_PER_SEC );
printf( "Done!\n" );
/* Measure the duration of an event. */
printf( "Time to do %ld empty loops is ", i );
start = clock();
while( i-- )
;
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%2.1f seconds\n", duration );
}
/* Pauses for a specified number of microseconds. */
void sleep( clock_t wait )
{
clock_t goal;
goal = wait + clock();
while( goal > clock() )
;
}
Output
Delay for five seconds
Done!
Time to do 900000 empty loops is 2.0 seconds
close
────────────────────────────────────────────────────────────────────────────
Description
Closes a file.
#include <io.h> Required only for function declarations
#include <errno.h>
int close( int handle );
handle Handle referring to open file
Remarks
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 indicates an error, and errno is set to EBADF, indicating an
invalid file-handle argument.
Compatibility
▼ ANSI DOS OS/2 UNIX XENIX
See Also
chsize, creat, dup, dup2, open, unlink
Example
/* OPEN.C: This program uses open to open a file named OPEN.C for input
* and a file named OPEN.OUT for output. The files are then closed.
*/
#include <fcntl.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <io.h>
#include <stdio.h>
void main()
{
int fh1, fh2;
fh1 = open( "OPEN.C", O_RDONLY );
if( fh1 == -1 )
perror( "open failed on input file" );
else
{
printf( "open succeeded on input file\n" );
close( fh1 );
}
fh2 = open( "OPEN.OUT", O_WRONLY | O_CREAT, S_IREAD | S_IWRITE );
if( fh2 == -1 )
perror( "open failed on output file" );
else
{
printf( "open succeeded on output file\n" );
close( fh2 );
}
}
Output
open succeeded on input file
open succeeded on output file
_control87
────────────────────────────────────────────────────────────────────────────
Description
Gets and sets the floating-point control word.
#include <float.h>
unsigned int _control87( unsigned int new, unsigned int mask );
new New control-word bit values
mask Mask for new control-word bits to set
Remarks
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 unmasked 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 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,
fpcntrl = ((fpcntrl & ~mask) | (new & mask))
where fpcntrl is the floating-point control word.
The possible values for the mask constant (mask) and new control values
(new) are shown in Table R.1.
Table R.1 Hex Values
╓┌────────────┌──────────┌────────────────┌──────────────────────────────────╖
Mask Hex Value Constant Hex Value
────────────────────────────────────────────────────────────────────────────
MCW_EM 0x003F
(Interrupt
exception)
EM_INVALID 0x0001
EM_DENORMAL 0x0002
EM_ZERODIVIDE 0x0004
EM_OVERFLOW 0x0008
EM_UNDERFLOW 0x0010
EM_INEXACT 0x0020
MCW_IC 0x1000
Mask Hex Value Constant Hex Value
────────────────────────────────────────────────────────────────────────────
MCW_IC 0x1000
(Infinity
control)
IC_AFFINE 0x1000
IC_PROJECTIVE 0x0000
MCW_RC 0x0C00
(Rounding
control)
RC_CHOP 0x0C00
RC_UP 0x0800
RC_DOWN 0x0400
Mask Hex Value Constant Hex Value
────────────────────────────────────────────────────────────────────────────
RC_DOWN 0x0400
RC_NEAR 0x0000
MCW_PC 0x0300
(Precision
control)
PC_24 (24 bits) 0x0000
PC_53 (53 bits) 0x0200
PC_64 (64 bits) 0x0300
────────────────────────────────────────────────────────────────────────────
Return Value
The bits in the value returned indicate the floating-point control state.
See the FLOAT.H include file for a complete definition of the bits returned
by _control87.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
_clear87, _status87
Example
/* CNTRL87.C: This program uses _control87 to output the control word,
* set the precision to 24 bits, and reset the status to the default.
*/
#include <stdio.h>
#include <float.h>
void main()
{
double a = 0.1;
/* Show original control word and do calculation. */
printf( "Original: 0x%.4x\n", _control87( 0, 0 ) );
printf( "%1.1f * %1.1f = %.15e\n", a, a, a * a );
/* Set precision to 24 bits and recalculate. */
printf( "24-bit: 0x%.4x\n", _control87( PC_24, MCW_PC ) );
printf( "%1.1f * %1.1f = %.15e\n", a, a, a * a );
/* Restore to default and recalculate. */
printf( "Default: 0x%.4x\n", _control87( CW_DEFAULT, 0xffff ) );
printf( "%1.1f * %1.1f = %.15e\n", a, a, a * a );
}
Output
Original: 0x1332
0.1 * 0.1 = 1.000000000000000e-002
24-bit: 0x1332
0.1 * 0.1 = 9.999999776482582e-003
Default: 0x1032
0.1 * 0.1 = 1.000000000000000e-002
cos Functions
────────────────────────────────────────────────────────────────────────────
Description
Calculate the cosine (cos and cosl) or hyperbolic cosine (cosh and coshl).
#include <math.h>
double cos( double x );
double cosh( double x );
long double cosl( long double x );
long double coshl( long double x );
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 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
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.
Compatibility
cos, cosh
ANSI DOS OS/2 UNIX XENIX
cosl, coshl
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
acos functions, asin functions, atan functions, matherr, sin functions, tan
functions
Example
/* SINCOS.C: This program displays the sine, hyperbolic sine, cosine,
* and hyperbolic cosine of pi / 2.
*/
#include <math.h>
#include <stdio.h>
void main()
{
double pi = 3.1415926535;
double x, y;
x = pi / 2;
y = sin( x );
printf( "sin( %f ) = %f\n", x, y );
y = sinh( x );
printf( "sinh( %f ) = %f\n",x, y );
y = cos( x );
printf( "cos( %f ) = %f\n", x, y );
y = cosh( x );
printf( "cosh( %f ) = %f\n",x, y );
}
Output
sin( 1.570796 ) = 1.000000
sinh( 1.570796 ) = 2.301299
cos( 1.570796 ) = 0.000000
cosh( 1.570796 ) = 2.509178
cprintf
────────────────────────────────────────────────────────────────────────────
Description
Formats and prints to the console.
#include <conio.h> Required only for function declarations
int cprintf( char *format [[, argument]] ... );
format Format control string
argument Optional arguments
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 converted and output according to the corresponding
format specification in format. The format has the same form and function as
the format 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.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
cscanf, fprintf, printf, sprintf, vprintf
Example
/* CPRINTF.C: This program displays some variables to the console. */
#include <conio.h>
void main()
{
int i = -16, h = 29;
unsigned u = 62511;
char c = 'A';
char s[] = "Test";
/* Note that console output does not translate \n as
* standard output does. Use \r\n instead.
*/
cprintf( "%d %.4x %u %c %s\r\n", i, h, u, c, s );
}
Output
-16 001d 62511 A Test
cputs
────────────────────────────────────────────────────────────────────────────
Description
Puts a string to the console.
#include <conio.h> Required only for function declarations
int cputs( char *string );
string Output string
Remarks
The cputs function writes the null-terminated string pointed to by string
directly to the console. Note that a carriage-return-line-feed (CR-LF)
combination is not automatically appended to the string.
Return Value
If successful, cputs returns a 0. If the function fails, it returns a
nonzero value.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
putch
Example
/* CPUTS.C: This program first displays a string to the console. */
#include <conio.h>
void main()
{
/* String to print at console. Note the \r (return) character. */
char *buffer = "Hello world (courtesy of cputs)!\r\n";
cputs( buffer );
}
Output
Hello world (courtesy of cputs)!
creat
────────────────────────────────────────────────────────────────────────────
Description
Creates a new file.
#include <sys\types.h>
#include <sys\stat.h>
#include <errno.h>
#include <io.h> Required only for function declarations
int creat( char *filename, int pmode );
filename Path name of new file
pmode Permission setting
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 setting 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 SYS\STAT.H. When both of
the constants are given, they are joined with the bitwise-OR operator ( | ).
The pmode argument is set to one of the following values:
Value Meaning
────────────────────────────────────────────────────────────────────────────
S_IWRITE Writing permitted
S_IREAD Reading permitted
S_IREAD | 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 | S_IWRITE modes are equivalent. Under DOS versions 3.0 and later,
files opened using creat are always 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 O_CREAT and O_TRUNC in the oflag
argument is equivalent to creat and is preferable for new code.
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
Compatibility
▼ ANSI DOS OS/2 UNIX XENIX
See Also
chmod, chsize, close, dup, dup2, open, sopen, umask
Example
/* CREAT.C: This program uses creat to create the file (or truncate the
* existing file) named data and open it for writing.
*/
#include <sys\types.h>
#include <sys\stat.h>
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
void main()
{
int fh;
fh = creat( "data", S_IREAD | S_IWRITE );
if( fh == -1 )
perror( "Couldn't create data file" );
else
{
printf( "Created data file.\n" );
close( fh );
}
}
Output
Created data file.
cscanf
────────────────────────────────────────────────────────────────────────────
Description
Reads formatted data from the console.
#include <conio.h> Required only for function declarations
int cscanf( char *format [[, argument]] ... );
format Format-control string
argument Optional arguments
Remarks
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 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 description of
format.
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 assigned. 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 keyboard input is redirected at the operating system command-line
level. A return value of 0 means that no fields were assigned.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
cprintf, fscanf, scanf, sscanf
Example
/* CSCANF.C: This program prompts for a string and uses cscanf to read
* in the response. Then cscanf returns the number of items matched,
* and the program displays that number.
*/
#include <stdio.h>
#include <conio.h>
void main()
{
int result, i[3];
cprintf( "Enter three integers: ");
result = cscanf( "%i %i %i", &i[0], &i[1], &i[2] );
cprintf( "\r\nYou entered " );
while( result-- )
cprintf( "%i ", i[result] );
cprintf( "\r\n" );
}
Output
Enter three integers: 34 43 987k
You entered 987 43 34
ctime
────────────────────────────────────────────────────────────────────────────
Description
Converts a time stored as a time_t value to a character string.
#include <time.h> Required only for function declarations
char *ctime( const time_t *timer );
timer Pointer to stored time
Remarks
The ctime function converts a time stored as a time_t value to a character
string. The timer value is usually obtained from a call to time, which
returns the number of seconds elapsed since 00:00:00 Greenwich mean time,
January 1, 1970.
The string result produced by ctime contains exactly 26 characters and has
the form of the following example:
Wed Jan 02 02:03:55 1980\n\0
A 24-hour clock is 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 function. Thus, a call to ctime
destroys the results of any previous call to asctime, localtime, or gmtime.
Return Value
The ctime function returns a pointer to the character string result. If time
represents a date before 1980, ctime returns NULL.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
asctime, ftime, gmtime, localtime, time
Example
/* ASCTIME.C: This program places the system time in the long integer
aclock,
* translates it into the structure newtime and then converts it to
* string form for output, using the asctime function.
*/
#include <time.h>
#include <stdio.h>
struct tm *newtime;
time_t aclock;
void main()
{
time( &aclock ); /* Get time in seconds. */
newtime = localtime( &aclock ); /* Convert time to struct tm form.
*/
/* Print local time as a string. */
printf( "The current date and time are: %s\n", asctime( newtime ) );
}
Output
The current date and time are: Thu Jun 15 06:57:59 1989
cwait
────────────────────────────────────────────────────────────────────────────
Description
Waits until the child process terminates.
#include <process.h>
int cwait( int *termstat, int procid, int action );
termstat Address for termination status code
procid Process ID of child
action Action code
Remarks
The cwait function suspends the calling process until the specified child
process terminates.
If not NULL, termstat points to a buffer where cwait will place the
termination-status word and the return code of the terminated child process.
The termination-status word indicates whether or not the child process
terminated normally 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 normally, the low-order and
high-order bytes of the termination-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 termination).
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
────────────────────────────────────────────────────────────────────────────
1 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 returned 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.
The WAIT_CHILD and WAIT_GRANDCHILD action codes are defined in PROCESS.H.
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 following error codes:
Value Meaning
────────────────────────────────────────────────────────────────────────────
ECHILD No child process exists, or invalid
process ID
EINVAL Invalid action code
Compatibility
▼ ANSI ▼ DOS OS/2 ▼ UNIX ▼ XENIX
Note that the OS/2 DosExit function allows programs to return a 16-bit
result code. However, the wait and cwait functions return only the low-order
byte of that result code.
See Also
exit, _exit, spawn functions, wait
Example
/* CWAIT.C: This program launches several child processes and waits
* for a specified process to finish.
*/
#define INCL_NOPM
#define INCL_NOCOMMON
#define INCL_DOSPROCESS
#include <os2.h> /* DosSleep */
#include <process.h> /* cwait */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
/* Macro to get a random integer within a specified range */
#define getrandom( min, max ) ((rand() % (int)(((max) + 1) - (min))) +
(min))
struct CHILD
{
int pid;
char name[10];
} child[4] = { { 0, "Ann" }, { 0, "Beth" }, { 0, "Carl" }, { 0, "Dave" }
};
void main( int argc, char *argv[] )
{
int termstat, pid, c, tmp;
srand( (unsigned)time( NULL ) ); /* Seed randomizer */
/* If no arguments, this is the parent. */
if( argc == 1 )
{
/* Spawn children in numeric order. */
for( c = 0; c < 4; c++ )
child[c].pid = spawnl( P_NOWAIT, argv[0], argv[0],
child[c].name, NULL );
/* Wait for randomly specified child, and respond when done. */
c = getrandom( 0, 3 );
printf( "Come here, %s\n", child[c].name );
cwait( &termstat, child[c].pid, WAIT_CHILD );
printf( "Thank you, %s\n", child[c].name );
}
/* If there are arguments, this must be a child. */
else
{
/* Delay for a period determined by process number. */
DosSleep( (argv[1][0] - 'A' + 1) * 1000L );
printf( "Hi, dad. It's %s.\n", argv[1] );
}
}
Output
Come here, Carl
Hi, dad. It's Ann.
Hi, dad. It's Beth.
Hi, dad. It's Carl.
Thank you, Carl
Hi, dad. It's Dave.
dieeetomsbin, dmsbintoieee
────────────────────────────────────────────────────────────────────────────
Description
Convert between IEEE double value and Microsoft (MS) binary double value.
#include <math.h>
int dieeetomsbin( double *src8, double *dst8 );
int dmsbintoieee( double *src8, double *dst8 );
src8 Buffer containing value to convert
dst8 Buffer to store converted value
Remarks
The dieeetomsbin routine converts a double-precision number in IEEE
(Institute of Electrical and Electronic Engineers) format to Microsoft (MS)
binary format. The routine dmsbintoieee converts a double-precision number
in MS binary format to IEEE format.
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 src8 is a pointer to the double value to be converted. The
result is stored at the location given by dst8.
These routines do not handle IEEE NANs ("not a number") and infinities. IEEE
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.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
fieeetomsbin, fmsbintoieee
difftime
────────────────────────────────────────────────────────────────────────────
Description
Finds the difference between two times.
#include <time.h> Required only for function declarations
double difftime( time_t timer1, time_t timer0 );
timer0 Beginning time
timer1 Ending time
Remarks
The difftime function computes the difference between the supplied time
values, timer0 and timer1.
Return Value
The difftime function returns, in seconds, the elapsed time from timer0 to
timer1. The value returned is a double-precision number.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
time
Example
/* DIFFTIME.C: This program calculates the amount of time needed to
* do a floating-point multiply 50000 times.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main()
{
time_t start, finish;
unsigned loop;
double result, elapsed_time;
printf( "This program will do a floating point multiply 50000 times\n"
);
printf( "Working...\n" );
time( &start );
for( loop = 0; loop < 50000L; loop++ )
result = 3.63 * 5.27;
time( &finish );
elapsed_time = difftime( finish, start );
printf( "\nProgram takes %6.2f seconds.\n", elapsed_time );
}
Output
This program will do a floating point multiply 50000 times
Working...
Program takes 4.00 seconds.
_displaycursor
────────────────────────────────────────────────────────────────────────────
Description
Sets the cursor toggle for graphics functions.
#include <graph.h>
short _far _displaycursor( short toggle );
toggle Cursor state
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.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
_gettextcursor, _settextcursor
Example
/* DISCURS.C: This program changes the cursor shape using _gettextcursor
* and _settextcursor, and hides the cursor using _displaycursor.
*/
#include <conio.h>
#include <graph.h>
void main()
{
short oldcursor;
short newcursor = 0x007; /* Full block cursor */
/* Save old cursor shape and make sure cursor is on */
oldcursor = _gettextcursor();
_clearscreen( _GCLEARSCREEN );
_displaycursor( _GCURSORON );
_outtext( "\nOld cursor shape: " );
getch();
/* Change cursor shape */
_outtext( "\nNew cursor shape: " );
_settextcursor( newcursor );
getch();
/* Restore original cursor shape */
_outtext( "\n" );
_settextcursor( oldcursor );
}
div
────────────────────────────────────────────────────────────────────────────
Description
Computes the quotient and the remainder of two integer values.
#include <stdlib.h>
div_t div( int numer, int denom );
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
────────────────────────────────────────────────────────────────────────────
int quot Quotient
int rem 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.
Return Value
The div function returns a structure of type div_t, comprising both the
quotient and the remainder. The structure is defined in STDLIB.H.
Compatibility
ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
ldiv
Example
/* DIV.C: This example takes two integers as command-line arguments and
* displays the results of the integer division. This program accepts
* two arguments on the command line following the program name, then
* calls div to divide the first argument by the second. Finally,
* it prints the structure members quot and rem.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void main( int argc, char *argv[] )
{
int x,y;
div_t div_result;
x = atoi( argv[1] );
y = atoi( argv[2] );
printf( "x is %d, y is %d\n", x, y );
div_result = div( x, y );
printf( "The quotient is %d, and the remainder is %d\n",
div_result.quot, div_result.rem );
}
Output
[C:\LIBREF] div 876 13
x is 876, y is 13
The quotient is 67, and the remainder is 5
_dos_allocmem
────────────────────────────────────────────────────────────────────────────
Description
Allocates a block of memory, using DOS service 0x48.
#include <dos.h>
#include <errno.h>
unsigned _dos_allocmem( unsigned size, unsigned *seg );
size Block size to allocate
seg Return buffer for segment descriptor
Remarks
The _dos_allocmem function uses DOS service 0x48 to allocate a block of
memory size paragraphs long. (A paragraph is 16 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.
Return 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.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
alloca, calloc functions, _dos_freemem, _dos_setblock, halloc, malloc
functions
Example
/* DALOCMEM.C: This program allocates 20 paragraphs of memory, increases
* the allocation to 40 paragraphs, and then frees the memory space.
*/
#include <dos.h>
#include <stdio.h>
void main()
{
unsigned segment;
unsigned maxsize;
/* Allocate 20 paragraphs */
if( _dos_allocmem( 20, &segment ) != 0 )
printf( "allocation failed\n" );
else
printf( "allocation successful\n" );
/* Increase allocation to 40 paragraphs */
if( _dos_setblock( 40, segment, &maxsize ) != 0 )
printf( "allocation increase failed\n" );
else
printf( "allocation increase successful\n" );
/* free memory */
if( _dos_freemem( segment ) != 0 )
printf( "free memory failed\n" );
else
printf( "free memory successful\n" );
}
Output
allocation successful
allocation increase successful
free memory successful
_dos_close
────────────────────────────────────────────────────────────────────────────
Description
Closes a file using system call INT 0x3E.
#include <dos.h>
#include <errno.h>
unsigned _dos_close( int handle );
handle Target file handle
Remarks
The _dos_close function uses system call 0x3E 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 I/O routines with the console, low-level, or
stream I/O routines.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
close, creat, _dos_creat functions, _dos_open, _dos_read, _dos_write,
dup, open
Example
/* DOPEN.C: This program uses DOS I/O functions to open and close a file.
*/
#include <fcntl.h>
#include <stdio.h>
#include <dos.h>
void main()
{
int fh;
/* Open file with _dos_open function */
if( _dos_open( "data1", O_RDONLY, &fh ) != 0 )
perror( "Open failed on input file\n" );
else
printf( "Open succeeded on input file\n" );
/* Close file with _dos_close function */
if( _dos_close( fh ) != 0 )
perror( "Close failed\n" );
else
printf( "File successfully closed\n" );
}
Output
Open succeeded on input file
File successfully closed
_dos_creat Functions
────────────────────────────────────────────────────────────────────────────
Description
Create a new file.
#include <dos.h>
#include <errno.h>
unsigned _dos_creat( char *filename, unsigned attrib, int *handle );
unsigned _dos_creatnew( char *filename, unsigned attrib, int *handle );
filename File path name
attrib File attributes
handle Handle return buffer
Remarks
The _dos_creat and _dos_creatnew routines create and open a new file named
filename; 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 0x3C, and the _dos_creatnew
routine uses system call INT 0x5B. 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
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
Example
/* DCREAT.C: This program creates a file using the _dos_creat function.
The
* program cannot create a new file using the _dos_creatnew function
* because it already exists.
*/
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
void main()
{
int fh1, fh2;
int result;
if( _dos_creat( "data", _A_NORMAL, &fh1 ) != 0 )
printf( "Couldn't create data file\n" );
else
{
printf( "Created data file.\n" );
/* If _dos_creat is successful, the _dos_creatnew call
* will fail since the file exists
*/
if( _dos_creatnew( "data", _A_RDONLY, &fh2 ) != 0 )
printf( "Couldn't create data file\n" );
else
{
printf( "Created data file.\n" );
_dos_close( fh2 );
}
_dos_close( fh1 );
}
}
Output
Created data file.
Couldn't create data file
_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>
unsigned _dos_findfirst( char *filename, unsigned attrib, struct find_t
*fileinfo );
unsigned _dos_findnext( struct find_t *fileinfo );
filename Target file name
attrib Target attributes
fileinfo File-information buffer
Remarks
The _dos_findfirst routine uses system call INT 0x4E to return information
about the first instance of a file whose name and attributes match filename
and attrib.
The filename 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.
Multiple constants can be combined (with the OR operator), using the
vertical-bar ( | ) character.
If the attributes argument to either of these functions is _A_RDONLY,
_A_HIDDEN, _A_SYSTEM, or _A_SUBDIR, the function also returns any normal
attribute files that match the filename argument. That is, a normal file
does not have a read-only, hidden, system, or directory attribute.
Information is returned in a find_t structure, defined in DOS.H. The find_t
structure contains the following elements:
Element Description
────────────────────────────────────────────────────────────────────────────
char reserved[21] Reserved for use by DOS
char attrib Attribute byte for matched path
unsigned wr_time Time of last write to file
unsigned wr_date Date of last write to file
long size Length of file in bytes
char name[13] Null-terminated name of matched
file/directory, without
the path
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
────────────────────────────────────────────────────────────────────────────
0 - 4 Number of 2-second increments (0 - 29)
5 -10 Minutes (0 - 59)
11-15 Hours (0 - 23)
The date format is shown below:
Bits Contents
────────────────────────────────────────────────────────────────────────────
0 - 4 Day of month (1-31)
5 - 8 Month (1-12)
9 -15 Year (relative to 1980)
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 should not
be altered between calls to _dos_findnext.
The _dos_findnext routine uses system call 0x4F 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.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
Example
/* DFIND.C: This program finds and prints all files in the current
directory with
* the .c extension.
*/
#include <stdio.h>
#include <dos.h>
main()
{
struct find_t c_file;
/* find first .c file in current directory */
_dos_findfirst( "*.c", _A_NORMAL, &c_file );
printf( "Listing of .c files\n\n" );
printf( "File: %s is %ld bytes\n", c_file.name, c_file.size );
/* find the rest of the .c files */
while( _dos_findnext( &c_file ) == 0 )
printf( "File: %s is %ld bytes\n", c_file.name, c_file.size );
}
Output
Listing of .c files
File: CHDIR.C is 524 bytes
File: SIGFP.C is 2674 bytes
File: MAX.C is 258 bytes
File: CGETS.C is 577 bytes
File: FWRITE.C is 1123 bytes
_dos_freemem
────────────────────────────────────────────────────────────────────────────
Description
Releases a block of memory (INT 0x49).
#include <dos.h>
#include <errno.h>
unsigned _dos_freemem( unsigned seg );
seg Block to be released
Remarks
The _dos_freemem function uses system call 0x49 to release a block of memory
previously 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 segment returned by a previous _dos_allocmem call) or
invalid arena headers.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_allocmem, _dos_setblock, free functions
Example
/* DALOCMEM.C: This program allocates 20 paragraphs of memory, increases
* the allocation to 40 paragraphs, and then frees the memory space.
*/
#include <dos.h>
#include <stdio.h>
void main()
{
unsigned segment;
unsigned maxsize;
/* Allocate 20 paragraphs */
if( _dos_allocmem( 20, &segment ) != 0 )
printf( "allocation failed\n" );
else
printf( "allocation successful\n" );
/* Increase allocation to 40 paragraphs */
if( _dos_setblock( 40, segment, &maxsize ) != 0 )
printf( "allocation increase failed\n" );
else
printf( "allocation increase successful\n" );
/* Free memory */
if( _dos_freemem( segment ) != 0 )
printf( "free memory failed\n" );
else
printf( "free memory successful\n" );
}
Output
allocation successful
allocation increase successful
free memory successful
_dos_getdate
────────────────────────────────────────────────────────────────────────────
Description
Gets current system date using system call INT 0x2A.
#include <dos.h>
void _dos_getdate( struct dosdate_t *date );
date Current system date
Remarks
The _dos_getdate routine uses system call 0x2A to obtain the current system
date. The date is returned in a dosdate_t structure, defined in DOS.H.
The dosdate_t structure contains the following elements:
Element Description
────────────────────────────────────────────────────────────────────────────
unsigned char day 1-31
unsigned char month 1-12
unsigned int year 1980 - 2099
unsigned char dayofweek 0 - 6 (0 = Sunday)
Return Value
None.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_gettime, _dos_setdate, _dos_settime, gmtime, localtime, mktime,
_strdate, _strtime, time
Example
/* DGTIME.C: This program gets and displays current date and time values.
*/
#include <stdio.h>
#include <dos.h>
void main()
{
struct dosdate_t date;
struct dostime_t time;
/* Get current date and time values */
_dos_getdate( &date );
_dos_gettime( &time );
printf( "Today's date is %d-%d-%d\n", date.month, date.day, date.year
);
printf( "The time is %02d:%02d\n", time.hour, time.minute );
}
Output
Today's date is 6-15-1989
The time is 18:07
_dos_getdiskfree
────────────────────────────────────────────────────────────────────────────
Description
Gets disk information using system call INT 0x36.
#include <dos.h>
#include <errno.h>
unsigned _dos_getdiskfree( unsigned drive, struct diskfree_t *diskspace );
drive Drive number (default is 0)
diskspace Buffer to hold disk information
Remarks
The _dos_getdiskfree routine uses system call 0x36 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
────────────────────────────────────────────────────────────────────────────
unsigned total_clusters Total clusters on disk
unsigned avail_clusters Available clusters on disk
unsigned sectors_per_cluster Sectors per cluster
unsigned bytes_per_sector Bytes per sector
Return Value
If successful, the function returns 0. Otherwise, it returns a nonzero value
and sets errno to EINVAL, indicating that an invalid drive was specified.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_getdrive, _dos_setdrive
Example
/* DGDISKFR.C: This program displays information about the default disk
drive. */
#include <stdio.h>
#include <dos.h>
main()
{
struct diskfree_t drive;
/* Get information on default disk drive 0 */
_dos_getdiskfree( 0, &drive );
printf( "total clusters: %d\n", drive.total_clusters );
printf( "available clusters: %d\n", drive.avail_clusters );
printf( "sectors per cluster: %d\n", drive.sectors_per_cluster );
printf( "bytes per sector: %d\n", drive.bytes_per_sector );
}
Output
total clusters: 9013
available clusters: 6030
sectors per cluster: 4
bytes per sector: 512
_dos_getdrive
────────────────────────────────────────────────────────────────────────────
Description
Gets the current disk drive using system call INT 0x19.
#include <dos.h>
void _dos_getdrive( unsigned *drive );
drive Current-drive return buffer
Remarks
The _dos_getdrive routine uses system call 0x19 to obtain the current disk
drive. The current drive is returned in the word that drive points to: 1 =
drive A, 2 = drive B, and so on.
Return Value
None.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_getdiskfree, _dos_setdrive, _getdrive
Example
/* DGDRIVE.C: This program prints the letter of the current drive,
* changes the default drive to A, then returns the number of disk drives.
*/
#include <stdio.h>
#include <dos.h>
void main()
{
unsigned olddrive, newdrive;
unsigned number_of_drives;
/* Print current default drive information */
_dos_getdrive( &olddrive );
printf( "The current drive is: %c\n", 'A' + olddrive1 );
/* Set default drive to be drive A */
printf( "Changing default drive to A\n");
_dos_setdrive( 1, &number_of_drives );
/* Get new default drive information and total number of drives */
_dos_getdrive( &newdrive );
printf( "The current drive is: %c\n", 'A' + newdrive1 );
printf( "Number of logical drives: %d\n", number_of_drives );
/* Restore default drive */
_dos_setdrive( olddrive, &number_of_drives );
}
Output
The current drive is: C
Changing default drive to A
The current drive is: A
Number of logical drives: 26
_dos_getfileattr
────────────────────────────────────────────────────────────────────────────
Description
Gets the current attributes of a file or directory, using system call INT
0x43.
#include <dos.h>
#include <errno.h>
unsigned _dos_getfileattr( char *pathname, unsigned *attrib );
pathname Full path of target file/directory
attrib Word to store attributes in
Remarks
The _dos_getfileattr routine uses system call 0x43 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
────────────────────────────────────────────────────────────────────────────
_A_ARCH 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
without restriction.
_A_RDONLY Read-only. File cannot be opened for a
write, and a file with the same name
cannot be created.
_A_SUBDIR 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
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.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
access, chmod, _dos_setfileattr, umask
Example
/* DGFILEAT.C: This program creates a file with the specified attributes,
* then prints this information before changing the file attributes back
* to normal.
*/
#include <stdio.h>
#include <dos.h>
void main()
{
unsigned oldattrib, newattrib;
int fh;
/* Get and display file attribute */
_dos_getfileattr( "DGFILEAT.C", &oldattrib );
printf( "Attribute: 0x%.4x\n", oldattrib );
if( ( oldattrib & _A_RDONLY ) != 0 )
printf( "Read only file\n" );
else
printf( "Not a read only file.\n" );
/* Reset file attribute to normal file */
_dos_setfileattr( "DGFILEAT.C", _A_RDONLY );
_dos_getfileattr( "DGFILEAT.C", &newattrib );
printf( "Attribute: 0x%.4x\n", newattrib );
/* Restore file attribute */
_dos_setfileattr( "DGFILEAT.C", oldattrib );
_dos_getfileattr( "DGFILEAT.C", &newattrib );
printf( "Attribute: 0x%.4x\n", newattrib );
}
Output
Attribute: 0x0020
Not a read only file.
Attribute: 0x0001
Attribute: 0x0020
_dos_getftime
────────────────────────────────────────────────────────────────────────────
Description
Gets the date and time a file was last written, using system call INT 0x57.
#include <dos.h>
#include <errno.h>
unsigned _dos_getftime( int handle, unsigned *date, unsigned *time );
handle Target file
date Date-return buffer
time Time-return buffer
Remarks
The _dos_getftime routine uses system call 0x57 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:
Time Bits Meaning
────────────────────────────────────────────────────────────────────────────
0 - 4 Number of 2-second increments (0 -29)
5 -10 Minutes (0 -59)
11-15 Hours (0 -23)
Date Bits Meaning
────────────────────────────────────────────────────────────────────────────
0 - 4 Day (1-31)
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.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_setftime, fstat, stat
Example
/* DGFTIME.C: This program displays and modifies the date and time
* fields of a file.
*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
void main()
{
/* FEDC BA98 7654 3210 */
unsigned new_date = 0x184f; /* 0001 1000 0100 1111 2/15/92 */
unsigned new_time = 0x48e0; /* 0100 1000 1110 0000 9:07 AM */
unsigned old_date, old_time;
int fh;
/* Open file with _dos_open function */
if( _dos_open( "dgftime.obj", O_RDONLY, &fh ) != 0 )
exit( 1 );
/* Get file date and time */
_dos_getftime( fh, &old_date, &old_time );
printf( "Old date field: 0x%.4x\n", old_date );
printf( "Old time field: 0x%.4x\n", old_time );
system( "dir dgftime.obj" );
/* Modify file date and time */
if( !_dos_setftime( fh, new_date, new_time ) )
{
_dos_getftime( fh, &new_date, &new_time );
printf( "New date field: 0x%.4x\n", new_date );
printf( "New time field: 0x%.4x\n", new_time );
system( "dir dgftime.obj" );
/* Restore date and time */
_dos_setftime( fh, old_date, old_time );
}
_dos_close( fh );
}
Output
Old date field: 0x12cf
Old time field: 0x94bb
Volume in drive C is OS2
Directory of C:\LIBREF
DGFTIME OBJ 3923 6-15-89 6:37p
1 File(s) 13676544 bytes free
New date field: 0x184f
New time field: 0x48e0
Volume in drive C is OS2
Directory of C:\LIBREF
DGFTIME OBJ 3923 2-15-92 9:07a
1 File(s) 13676544 bytes free
_dos_gettime
────────────────────────────────────────────────────────────────────────────
Description
Gets the current system time, using system call INT 0x2C.
#include <dos.h>
void _dos_gettime( struct dostime_t *time );
time Current system time
Remarks
The _dos_gettime routine uses system call 0x2C 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
────────────────────────────────────────────────────────────────────────────
unsigned char hour 0 -23
unsigned char minute 0 -59
unsigned char second 0 -59
unsigned char hsecond 1/100 second; 0 -99
Return Value
None.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_getdate, _dos_setdate, _dos_settime, gmtime, localtime, _strtime
Example
/* DGTIME.C: This program gets and displays current date and time values.
*/
#include <stdio.h>
#include <dos.h>
void main()
{
struct dosdate_t date;
struct dostime_t time;
/* Get current date and time values */
_dos_getdate( &date );
_dos_gettime( &time );
printf( "Today's date is %d-%d-%d\n", date.month, date.day, date.year
);
printf( "The time is %02d:%02d\n", time.hour, time.minute );
}
Output
Today's date is 6-15-1989
The time is 18:07
_dos_getvect
────────────────────────────────────────────────────────────────────────────
Description
Gets the current value of the interrupt vector, using system call INT 0x35.
#include <dos.h>
void ( _interrupt _far *_dos_getvect( unsigned intnum))();
intnum Target interrupt vector
Remarks
The _dos_getvect routine uses system call INT 0x35 to get the current value
of the interrupt 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
original vector in order to call that vector or chain to it with
_chain_intr.
Return Value
The function returns a far pointer for the intnum interrupt to the current
handler, if there is one.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_chain_intr, _dos_keep, _dos_setvect
_dos_keep
────────────────────────────────────────────────────────────────────────────
Description
Installs TSR (terminate-and-stay-resident) programs in memory, using system
call INT 0x31.
#include <dos.h>
void _dos_keep( unsigned retcode, unsigned memsize );
retcode Exit status code
memsize Allocated resident memory (in 16-byte
paragraphs)
Remarks
The _dos_keep routine installs TSRs (terminate-and-stay-resident programs)
in memory, using system call INT 0x31.
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 16-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:
■ Calls atexit and onexit if defined.
■ Flushes all file buffers.
■ 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 0x34 through
0x3D 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.
Return Value
None.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_cexit, _chain_intr, _dos_getvect, _dos_setvect, _exit
_dos_open
────────────────────────────────────────────────────────────────────────────
Description
Opens a file, using system call INT 0x3D.
#include <dos.h>
#include <errno.h>
#include <fcntl.h> Access mode constants
#include <share.h> Sharing mode constants
unsigned _dos_open( char *filename, unsigned mode, int *handle );
filename Path to an existing file
mode Permissions
handle Pointer to integer
Remarks
The _dos_open routine uses system call INT 0x3D 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 combining (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.
╓┌─────────────┌────────────────────────────────┌────────────────────────────►
Constant Mode Meaning
─────────────────────────────────────────────────────────────────────────────
O_RDONLY Access Read-only
Constant Mode Meaning
─────────────────────────────────────────────────────────────────────────────
O_RDONLY Access Read-only
O_WRONLY Access Write-only
O_RDWR Access Both read and write
SH_COMPAT Sharing Compatibility
SH_DENYRW Sharing Deny reading and writing
SH_DENYWR Sharing Deny writing
SH_DENYRD Sharing Deny reading
SH_DENYNO Sharing Deny neither
O_NOINHERIT Inheritance by the child File is not inherited
process
Constant Mode Meaning
─────────────────────────────────────────────────────────────────────────────
Do not use the DOS interface I/O routines in conjunction with the console,
low-level, or stream I/O routines.
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
────────────────────────────────────────────────────────────────────────────
EACCES Access denied (possible reasons include
specifying a directory or volume ID for
filename, or opening a read-only file
for write access)
EINVAL Sharing mode specified when file sharing
not installed, or
access-mode value is invalid
EMFILE Too many open file handles
ENOENT Path or file not found
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_close, _dos_read, _dos_write
Example
/* DOPEN.C: This program uses DOS I/O functions to open and close a file.
*/
#include <fcntl.h>
#include <stdio.h>
#include <dos.h>
void main()
{
int fh;
/* Open file with _dos_open function */
if( _dos_open( "data1", O_RDONLY, &fh ) != 0 )
perror( "Open failed on input file\n" );
else
printf( "Open succeeded on input file\n" );
/* Close file with _dos_close function */
if( _dos_close( fh ) != 0 )
perror( "Close failed\n" );
else
printf( "File successfully closed\n" );
}
Output
Open succeeded on input file
File successfully closed
_dos_read
────────────────────────────────────────────────────────────────────────────
Description
Reads data from a file, using system call INT 0x3F.
#include <dos.h>
unsigned _dos_read( int handle, void _far *buffer, unsigned count,
unsigned *numread );
handle File to read
buffer Buffer to write to
count Number of bytes to read
numread Number of bytes actually read
Remarks
The _dos_read routine uses system call INT 0x3F 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 I/O routines in conjunction with the console,
low-level, or stream I/O 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
────────────────────────────────────────────────────────────────────────────
EACCES Access denied (handle is not open for
read access)
EBADF File handle is invalid
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_close, _dos_open, _dos_write, read
Example
/* DREAD.C: This program uses the DOS I/O operations to read the contents
* of a file.
*/
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <dos.h>
void main()
{
int fh;
char buffer[50];
unsigned number_read;
/* Open file with _dos_open function */
if( _dos_open( "dread.c", O_RDONLY, &fh ) != 0 )
perror( "Open failed on input file\n" );
else
printf( "Open succeeded on input file\n" );
/* Read data with _dos_read function */
_dos_read( fh, buffer, 50, &number_read );
printf( "First 40 characters are: %.40s\n\n", buffer );
/* Close file with _dos_close function */
_dos_close( fh );
}
Output
Open succeeded on input file
First 40 characters are: /* DREAD.C: This program uses the DOS I/
_dos_setblock
────────────────────────────────────────────────────────────────────────────
Description
Changes the size of a memory segment, using system call INT 0x4A.
#include <dos.h>
unsigned _dos_setblock( unsigned size, unsigned seg, unsigned *maxsize );
size New segment size
seg Target segment
maxsize Maximum-size buffer
Remarks
The _dos_setblock routine uses system call INT 0x4A to change the size of
seg, previously 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 errno 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.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_allocmem, _dos_freemem, realloc functions
Example
/* DALOCMEM.C: This program allocates 20 paragraphs of memory, increases
* the allocation to 40 paragraphs, and then frees the memory space.
*/
#include <dos.h>
#include <stdio.h>
void main()
{
unsigned segment;
unsigned maxsize;
/* Allocate 20 paragraphs */
if( _dos_allocmem( 20, &segment ) != 0 )
printf( "allocation failed\n" );
else
printf( "allocation successful\n" );
/* Increase allocation to 40 paragraphs */
if( _dos_setblock( 40, segment, &maxsize ) != 0 )
printf( "allocation increase failed\n" );
else
printf( "allocation increase successful\n" );
/* Free memory */
if( _dos_freemem( segment ) != 0 )
printf( "free memory failed\n" );
else
printf( "free memory successful\n" );
}
Output
allocation successful
allocation increase successful
free memory successful
_dos_setdate
────────────────────────────────────────────────────────────────────────────
Description
Sets the current system date, using system call INT 0x2B.
#include <dos.h>
unsigned _dos_setdate( struct dosdate_t *date );
date New system date
Remarks
The _dos_setdate routine uses system call INT 0x2B to set the current system
date. The date is stored in the dosdate_t structure pointed to by date,
defined in DOS.H. The dosdate_t structure contains the following elements:
Element Description
────────────────────────────────────────────────────────────────────────────
unsigned char day 1 -31
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.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_gettime, _dos_setdate, _dos_settime, gmtime, localtime, mktime,
_strdate, _strtime, time
Example
/* DSTIME.C: This program changes the time and date values and displays
the
* new date and time values.
*/
#include <dos.h>
#include <conio.h>
#include <stdio.h>
#include <time.h>
void main()
{
struct dosdate_t olddate, newdate = { { 4 }, { 7 }, { 1984 } };
struct dostime_t oldtime, newtime = { { 3 }, { 45 }, { 30 }, { 0 } };
char datebuf[40], timebuf[40];
/* Get current date and time values */
_dos_getdate( &olddate );
_dos_gettime( &oldtime );
printf( "%s %s\n" , _strdate( datebuf ), _strtime( timebuf ) );
/* Modify date and time structures */
_dos_setdate( &newdate );
_dos_settime( &newtime );
printf( "%s %s\n" , _strdate( datebuf ), _strtime( timebuf ) );
/* Restore old date and time */
_dos_setdate( &olddate );
_dos_settime( &oldtime );
}
Output
06/15/89 18:26:09
07/04/84 03:45:30
_dos_setdrive
────────────────────────────────────────────────────────────────────────────
Description
Sets the default drive, using system call INT 0x0E.
#include <dos.h>
void _dos_setdrive( unsigned drive, unsigned *numdrives );
drive New default drive
numdrives Total drives available
Remarks
The _dos_setdrive routine uses system call INT 0x0E 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 indication. Use the _dos_getdrive routine to verify whether
the desired drive has been set.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_getdiskfree, _dos_getdrive
Example
/* DGDRIVE.C: This program prints the letter of the current drive,
* changes the default drive to A, then returns the number of disk drives.
*/
#include <stdio.h>
#include <dos.h>
void main()
{
unsigned olddrive, newdrive;
unsigned number_of_drives;
/* Print current default drive information */
_dos_getdrive( &olddrive );
printf( "The current drive is: %c\n", 'A' + olddrive1 );
/* Set default drive to be drive A */
printf( "Changing default drive to A\n");
_dos_setdrive( 1, &number_of_drives );
/* Get new default drive information and total number of drives */
_dos_getdrive( &newdrive );
printf( "The current drive is: %c\n", 'A' + newdrive1 );
printf( "Number of logical drives: %d\n", number_of_drives );
/* Restore default drive */
_dos_setdrive( olddrive, &number_of_drives );
}
Output
The current drive is: C
Changing default drive to A
The current drive is: A
Number of logical drives: 26
_dos_setfileattr
────────────────────────────────────────────────────────────────────────────
Description
Sets the attributes of the file or directory, using system call INT 0x43.
#include <dos.h>
unsigned _dos_setfileattr( char *pathname, unsigned attrib );
pathname Full path of target file/directory
attrib New attributes
Remarks
The _dos_setfileattr routine uses system call INT 0x43 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_ARCH 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_RDONLY Read-only. File cannot be opened for
writing, and a file with the same name
cannot be created.
_A_SUBDIR 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.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_getfileattr
Example
/* DGFILEAT.C: This program creates a file with the specified attributes,
* then prints this information before changing the file attributes back
* to normal.
*/
#include <stdio.h>
#include <dos.h>
void main()
{
unsigned oldattrib, newattrib;
int fh;
/* Get and display file attribute */
_dos_getfileattr( "DGFILEAT.C", &oldattrib );
printf( "Attribute: 0x%.4x\n", oldattrib );
if( ( oldattrib & _A_RDONLY ) != 0 )
printf( "Read only file\n" );
else
printf( "Not a read only file.\n" );
/* Reset file attribute to normal file */
_dos_setfileattr( "DGFILEAT.C", _A_RDONLY );
_dos_getfileattr( "DGFILEAT.C", &newattrib );
printf( "Attribute: 0x%.4x\n", newattrib );
/* Restore file attribute */
_dos_setfileattr( "DGFILEAT.C", oldattrib );
_dos_getfileattr( "DGFILEAT.C", &newattrib );
printf( "Attribute: 0x%.4x\n", newattrib );
}
Output
Attribute: 0x0020
Not a read only file.
Attribute: 0x0001
Attribute: 0x0020
_dos_setftime
────────────────────────────────────────────────────────────────────────────
Description
Sets the date and time for a file, using system call INT 0x57.
#include <dos.h>
unsigned _dos_setftime( int handle, unsigned date, unsigned time );
handle Target file
date Date of last write
time Time of last write
Remarks
The _dos_setftime routine uses system call INT 0x57 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 format, described in the following lists:
Time Bits Meaning
────────────────────────────────────────────────────────────────────────────
0 - 4 Number of two-second increments (0 -29)
5 - 10 Minutes (0 -59)
11-15 Hours (0 -23)
Date Bits Meaning
────────────────────────────────────────────────────────────────────────────
0 - 4 Day (1-31)
5 -8 Month (1-12)
9 -15 Year since 1980 (for example, 1989 is
stored as 9)
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.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_getftime, fstat, stat
Example
/* DGFTIME.C: This program displays and modifies the date and time
* fields of a file.
*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
void main()
{
/* FEDC BA98 7654 3210 */
unsigned new_date = 0x184f; /* 0001 1000 0100 1111 2/15/92 */
unsigned new_time = 0x48e0; /* 0100 1000 1110 0000 9:07 AM */
unsigned old_date, old_time;
int fh;
/* Open file with _dos_open function */
if( _dos_open( "dgftime.obj", O_RDONLY, &fh ) != 0 )
exit( 1 );
/* Get file date and time */
_dos_getftime( fh, &old_date, &old_time );
printf( "Old date field: 0x%.4x\n", old_date );
printf( "Old time field: 0x%.4x\n", old_time );
system( "dir dgftime.obj" );
/* Modify file date and time */
if( !_dos_setftime( fh, new_date, new_time ) )
{
_dos_getftime( fh, &new_date, &new_time );
printf( "New date field: 0x%.4x\n", new_date );
printf( "New time field: 0x%.4x\n", new_time );
system( "dir dgftime.obj" );
/* Restore date and time */
_dos_setftime( fh, old_date, old_time );
}
_dos_close( fh );
}
Output
Old date field: 0x12cf
Old time field: 0x94bb
Volume in drive C is OS2
Directory of C:\LIBREF
DGFTIME OBJ 3923 6-15-89 6:37p
1 File(s) 13676544 bytes free
New date field: 0x184f
New time field: 0x48e0
Volume in drive C is OS2
Directory of C:\LIBREF
DGFTIME OBJ 3923 2-15-92 9:07a
1 File(s) 13676544 bytes free
_dos_settime
────────────────────────────────────────────────────────────────────────────
Description
Sets the current system time, using system call INT 0x2D.
#include <dos.h>
unsigned _dos_settime( struct dostime_t *time );
time New system time
Remarks
The _dos_settime routine uses system call INT 0x2D 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
Return Value
If successful, the function returns 0. Otherwise, it returns a nonzero value
and sets errno to EINVAL, indicating an invalid time was specified.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_getdate, _dos_gettime, _dos_setdate, gmtime, localtime, mktime,
_strdate, _strtime
Example
/* DSTIME.C: This program changes the time and date values and displays
the
* new date and time values.
*/
#include <dos.h>
#include <conio.h>
#include <stdio.h>
#include <time.h>
void main()
{
struct dosdate_t olddate, newdate = { { 4 }, { 7 }, { 1984 } };
struct dostime_t oldtime, newtime = { { 3 }, { 45 }, { 30 }, { 0 } };
char datebuf[40], timebuf[40];
/* Get current date and time values */
_dos_getdate( &olddate );
_dos_gettime( &oldtime );
printf( "%s %s\n" , _strdate( datebuf ), _strtime( timebuf ) );
/* Modify date and time structures */
_dos_setdate( &newdate );
_dos_settime( &newtime );
printf( "%s %s\n" , _strdate( datebuf ), _strtime( timebuf ) );
/* Restore old date and time */
_dos_setdate( &olddate );
_dos_settime( &oldtime );
}
Output
06/15/89 18:26:09
07/04/84 03:45:30
_dos_setvect
────────────────────────────────────────────────────────────────────────────
Description
Sets the current value of the interrupt vector, using system call INT 0x25.
#include <dos.h>
void _dos_setvect( unsigned intnum, void( _interrupt _far *handler)( ));
intnum Target-interrupt vector
handler Interrupt handler for which to assign
intnum
Remarks
The _dos_setvect routine uses system call INT 0x25 to set the current value
of the interrupt vector intnum to the function pointed to by handler.
Subsequently, whenever the 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, including 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
original vector in order to call it or to chain to it with _chain_intr.
Registers and Interrupt Functions
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:
void _interrupt _far int_handler( unsigned _es, unsigned _ds,
unsigned _di, unsigned _si,
unsigned _bp, unsigned _sp,
unsigned _bx, unsigned _dx,
unsigned _cx, unsigned _ax,
unsigned _ip, unsigned _cs,
unsigned _flags )
{
.
.
.
}
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 DS, 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 returns. For example:
void _interrupt _far int_handler( unsigned _es, unsigned _ds,
unsigned _di, unsigned _si )
{
_di = -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 interrupt functions. If you must
modify a particular flag (such as the carry flag for certain DOS and BIOS
interrupt routines), use the OR operator ( | ) so that other bits in the
flag register are not changed.
When an interrupt function is called by an INT instruction, the
interrupt-enable flag is cleared. If your interrupt function needs to do
significant processing, you should use the _enable function to set the
interrupt flag so that interrupts can be handled.
Precautions for Interrupt Functions
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 21H. Similar
precautions apply to many BIOS functions. Functions that rely on INT 21H
calls include I/O functions and the _dos family of functions. Functions 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
21H 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.
Return Value
None.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_chain_intr, _dos_getvect, _dos_keep
_dos_write
────────────────────────────────────────────────────────────────────────────
Description
Writes a buffer to a file, using system call INT 0x40.
#include <dos.h>
unsigned _dos_write( int handle, void _far *buffer, unsigned count,
unsigned *numwrt );
handle File to write to
buffer Buffer to write from
count Number of bytes to write
numwrt Number of bytes actually written
Remarks
The _dos_write routine uses system call INT 0x40 to write data to the file
that handle references; 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
I/O routines.
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
────────────────────────────────────────────────────────────────────────────
EACCES Access denied (handle references a file
not open for write
access)
EBADF Invalid file handle
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_dos_close, _dos_open, _dos_read, write
Example
/* DWRITE.C: This program uses DOS I/O functions to write to a file. */
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
void main()
{
char out_buffer[] = "Hello";
int fh;
unsigned n_written;
/* Open file with _dos_creat function */
if( _dos_creat( "data", _A_NORMAL, &fh ) == 0 )
{
/* Write data with _dos_write function */
_dos_write( fh, out_buffer, 5, &n_written );
printf( "Number of characters written: %d\n", n_written );
_dos_close( fh );
printf( "Contents of file are:\n" );
system( "type data" );
}
}
Output
Number of characters written: 5
Contents of file are:
Hello
dosexterr
────────────────────────────────────────────────────────────────────────────
Description
Gets register values returned by INT 0x59.
#include <dos.h>
int dosexterr( struct DOSERROR *errorinfo );
errorinfo Extended DOS error information
Remarks
The dosexterr function obtains the extended error information returned by
the DOS system call INT 0x59 and stores the values in the structure pointed
to by errorinfo. This function 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.H. The DOSERROR structure
contains the following elements:
Element Description
────────────────────────────────────────────────────────────────────────────
int exterror AX register contents
char class BH register contents
char action BL register contents
char locus CH register contents
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, 1988) 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).
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
The dosexterr function should be used only under DOS versions 3.0 or later.
See Also
perror
Example
/* DOSEXERR.C: This program tries to open the file test.dat. If the
* attempted open operation fails, the program uses dosexterr to display
* extended error information.
*/
#include <dos.h>
#include <io.h>
#include <fcntl.h>
#include <stdio.h>
void main()
{
struct DOSERROR doserror;
int fd;
/* Attempt to open a non-existent file */
if( (fd = open( "NOSUCHF.ILE", O_RDONLY )) == -1 )
{
dosexterr( &doserror );
printf( "Error: %d Class: %d Action: %d Locus: %d\n",
doserror.exterror, doserror.class,
doserror.action, doserror.locus );
}
else
{
printf( "Open succeeded so no extended information printed\n" );
close( fd );
}
}
Output
Error: 2 Class: 8 Action: 3 Locus: 2
dup, dup2
────────────────────────────────────────────────────────────────────────────
Description
Create a second handle for an open file (dup), or reassign a file handle
(dup2).
#include <io.h Required only for function declarations
int dup( int handle );
int dup2( int handle1, int handle2 );
handle, handle1 Handle referring to open file
handle2 Any handle value
Remarks
The dup and dup2 functions cause a second file handle to be associated with
a currently open file. 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 function forces handle2 to refer to the same file as handle1. If
handle2 is associated with an open file at the time of the call, that file
is closed.
Return 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 errno
to one of the following values:
Value Meaning
────────────────────────────────────────────────────────────────────────────
EBADF Invalid file handle
EMFILE No more file handles available (too many
open files)
Compatibility
▼ ANSI DOS OS/2 UNIX XENIX
See Also
close, creat, open
Example
/* DUP.C: This program uses the variable old to save the original stdout.
* It then opens a new file named new and forces stdout to refer
* to it. Finally, it restores stdout to its original state.
*/
#include <io.h>
#include <stdlib.h>
#include <stdio.h>
void main()
{
int old;
FILE *new;
old = dup( 1 ); /* "old" now refers to "stdout" */
/* Note: file handle 1 == "stdout" */
if( old == -1 )
{
perror( "dup( 1 ) failure" );
exit( 1 );
}
write( old, "This goes to stdout first\r\n", 27 );
if( ( new = fopen( "data", "w" ) ) == NULL )
{
puts( "Can't open file 'data'\n" );
exit( 1 );
}
/* stdout now refers to file "data" */
if( -1 == dup2( fileno( new ), 1 ) )
{
perror( "Can't dup2 stdout" );
exit( 1 );
}
puts( "This goes to file 'data'\r\n" );
/* Flush stdout stream buffer so it goes to correct file */
fflush( stdout );
fclose( new );
/* Restore original stdout */
dup2( old, 1 );
puts( "This goes to stdout\n" );
puts( "The file 'data' contains:" );
system( "type data" );
}
Output
This goes to stdout first
This goes to stdout
The file 'data' contains:
This goes to file 'data'
ecvt
────────────────────────────────────────────────────────────────────────────
Description
Converts a double number to a string.
#include <stdlib.h> Required only for function declarations
char *ecvt( double value, int count, int *dec, int *sign );
value Number to be converted
count Number of digits stored
dec Stored decimal-point position
sign Sign of converted number
Remarks
The ecvt function converts a floating-point number to a character string.
The value argument 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 in the string. The position of the decimal point and
the sign of value can be obtained from dec and sign after the call. The dec
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.
Compatibility
▼ ANSI DOS OS/2 UNIX XENIX
See Also
atof, atoi, atol, fcvt, gcvt
Example
/* ECVT.C: This program uses ecvt to convert a floating-point
* number to a character string.
*/
#include <stdlib.h>
#include <stdio.h>
void main()
{
int decimal, sign;
char *buffer;
int precision = 10;
double source = 3.1415926535;
buffer = ecvt( source, precision, &decimal, &sign );
printf( "source: %2.10f buffer: '%s' decimal: %d sign: %d\n",
source, buffer, decimal, sign );
}
Output
source: 3.1415926535 buffer: '3141592654' decimal: 1 sign: 0
_ellipse Functions
────────────────────────────────────────────────────────────────────────────
Description
Draw ellipses.
#include <graph.h>
short _far _ellipse( short control, short x1, short y1, short x2, short y2
);
short _far _ellipse_w( short control, double wx1, double wy1, double wx2,
double wy2 );
short _far _ellipse_wxy( short control, struct _wxycoord _far *pwxy1,
struct _wxycoord _far *pwxy2 );
control Fill flag
x1, y1 Upper-left corner of bounding rectangle
x2, y2 Lower-right corner of bounding rectangle
wx1, wy1 Upper-left corner of bounding rectangle
wx2, wy2 Lower-right corner of bounding rectangle
pwxy1 Upper-left corner of bounding rectangle
pwxy2 Lower-right corner of bounding rectangle
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 defined by the view-coordinate points
(x1, y1) 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 (wx1, wy1) and
(wx2, wy2).
In the _ellipse_wxy function, the center of the ellipse is the center of the
bounding rectangle defined by the window-coordinate pairs (pwxy1) and
(pwxy2).
If the bounding-rectangle arguments define a point or a vertical or
horizontal line, no figure is drawn.
The control argument can be one of the following manifest constants:
Constant Action
────────────────────────────────────────────────────────────────────────────
_GFILLINTERIOR Fills the ellipse using the current fill
mask
_GBORDER Does not fill the ellipse
The control option given by _GFILLINTERIOR is equivalent to a subsequent
call to the _floodfill function, using the center of the ellipse as the
starting point and the current color (set by _setcolor) as the boundary
color.
Return Value
The _ellipse functions return a nonzero value if the ellipse is drawn
successfully; otherwise, they return 0.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_arc functions, _floodfill, _grstatus, _lineto functions, _pie
functions, _polygon functions, _rectangle functions, _setcolor,
_setfillmask
Example
/* ELLIPSE.C: This program draws a simple ellipse. */
#include <conio.h>
#include <stdlib.h>
#include <graph.h>
void main()
{
/* Find a valid graphics mode. */
if( !_setvideomode( _MAXRESMODE ) )
exit( 1 );
_ellipse( _GFILLINTERIOR, 80, 50, 240, 150 );
/* Strike any key to clear screen. */
getch();
_setvideomode( _DEFAULTMODE );
}
_enable
────────────────────────────────────────────────────────────────────────────
Description
Enables interrupts.
#include <dos.h>
void _enable( void );
Remarks
The _enable routine enables interrupts by executing an 8086 STI machine
instruction.
Return Value
None.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_disable
_endthread
────────────────────────────────────────────────────────────────────────────
Description
Terminates an OS/2 thread.
#include <process.h> Multithread version of PROCESS.H
void _far _endthread( void );
Description
The _endthread function terminates a thread created by _beginthread.
Because threads terminate automatically, the _endthread function is normally
not required. It is used to terminate a thread conditionally.
The OS/2 function DosExit should not be used to terminate threads created by
the _beginthread function. If DosExit is used, the results are
unpredictable.
Return Value
None.
Compatibility
▼ ANSI ▼ DOS OS/2 ▼ UNIX ▼ XENIX
See Also
_beginthread
Example
See the example for _beginthread.
eof
────────────────────────────────────────────────────────────────────────────
Description
Tests for end-of-file.
#include <io.h> Required only for function declarations
int eof( int handle );
handle Handle referring to open file
Remarks
The eof function determines whether the end of the file associated with
handle has been reached.
Return Value
The eof function returns the value 1 if the current position is end-of-file,
or 0 if it is not. A return value of -1 indicates an error; in this case,
errno is set to EBADF, indicating an invalid file handle.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
clearerr, feof, ferror, perror
Example
/* EOF.C: This program reads data from a file ten bytes at a time
* until the end of the file is reached or an error is encountered.
*/
#include <io.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
void main()
{
int fh, count, total = 0;
char buf[10];
if( (fh = open( "eof.c", O_RDONLY )) == - 1 )
exit( 1 );
/* Cycle until end of file reached: */
while( !eof( fh ) )
{
/* Attempt to read in 10 bytes: */
if( (count = read( fh, buf, 10 )) == -1 )
{
perror( "Read error" );
break;
}
/* Total up actual bytes read */
total += count;
}
printf( "Number of bytes read = %d\n", total );
close( fh );
}
Output
Number of bytes read = 715
exec Functions
────────────────────────────────────────────────────────────────────────────
Description
Load and execute new child processes.
#include <process.h> Required only for function declarations
int execl( char *cmdname, char *arg0, ... char *argn, NULL );
int execle( char *cmdname, char *arg0, ... char *argn, NULL,
char **envp );
int execlp( char *cmdname, char *arg0, ... char *argn, NULL );
int execlpe( char *cmdname, char *arg0, ... char *argn, NULL,
char **envp );
int execv( char *cmdname, char **argv );
int execve( char *cmdname, char **argv, char **envp );
int execvp( char *cmdname, char **argv );
int execvpe( char *cmdname, char **argv, char **envp );
cmdname Path name of file to be executed
arg0, ... argn List of pointers to arguments
argv Array of pointers to arguments
envp Array of pointers to environment
settings
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.
l 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.
The cmdname argument specifies the file to be executed as the child process.
It 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 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 128
bytes (in real mode only). The terminating null character ('\0') for each
string is not included in the count, but space characters (inserted
automatically 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 argument, arg0, must be passed to the child process;
this argument is argv[0] of the child process. Usually, this argument 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 arg0 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 arg0.
The execl, execle, execlp, and execlpe calls are typically used when the
number of arguments is known in advance. The argument arg0 is usually a
pointer to cmdname. The arguments arg1 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 argument argv[0] is usually a pointer to
cmdname. The arguments argv[1] 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
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 inherits 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 0FFFFH. 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 functions 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 fflush 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 returns, 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 exceeds 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 determine 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 allocated
properly.
Compatibility
▼ ANSI DOS OS/2 UNIX XENIX
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 argument) 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
Example
/* EXEC.C: This program accepts a number in the range 1 through 8 from the
* command line. Based on the number it receives, it executes one of the
* eight different procedures that spawn the process named child. For
* some of these procedures, the child.exe file must be in the same
* directory; for others, it need only be in the same path.
*/
#include <stdio.h>
#include <process.h>
char *my_env[] = {
"THIS=environment will be",
"PASSED=to child.exe by the",
"EXECLE=and",
"EXECLPE=and",
"EXECVE=and",
"EXECVPE=functions",
NULL
};
void main( int argc, char *argv[] )
{
char *args[4];
int result;
args[0] = "child"; /* Set up parameters to send */
args[1] = "execv??";
args[2] = "two";
args[3] = NULL;
switch( argv[1][0] ) /* Based on first letter of argument */
{
case '1':
execl( argv[2], argv[2], "execl", "two", NULL );
break;
case '2':
execle( argv[2], argv[2], "execle", "two", NULL, my_env );
break;
case '3':
execlp( argv[2], argv[2], "execlp", "two", NULL );
break;
case '4':
execlpe( argv[2], argv[2], "execlpe", "two", NULL, my_env );
break;
case '5':
execv( argv[2], args );
break;
case '6':
execve( argv[2], args, my_env );
break;
case '7':
execvp( argv[2], args );
break;
case '8':
execvpe( argv[2], args, my_env );
break;
default:
printf( "SYNTAX: EXEC <1-8> <childprogram>\n" );
exit( 1 );
}
printf( "Process was not spawned.\n" );
printf( "Program 'child' was not found." );
}
exit, _exit
────────────────────────────────────────────────────────────────────────────
Description
Terminate the calling process after cleanup (exit) or immediately ( _exit).
#include <process.h> Required only for function declarations
#include <stdlib.h> Use either PROCESS.H or STDLIB.H
void exit( int status );
void _exit( int status );
status Exit status
Remarks
The exit and _exit functions terminate 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
terminating the process. The _exit function terminates the process without
processing atexit or onexit functions or flushing stream buffers. The status
value is typically set to 0 to indicate a normal 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
────────────────────────────────────────────────────────────────────────────
exit Performs complete C library termination
procedures, terminates 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 returns to caller, but
does not terminate the process.
_c_exit Performs "quick" C library termination
procedures and returns to caller, but
does not terminate the process.
Return Value
None.
Compatibility
exit
ANSI DOS OS/2 UNIX XENIX
_exit
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
abort, atexit, _cexit, exec functions, onexit, spawn functions, system
Example
/* EXITER.C: This program prompts the user for a yes or no and returns
* a DOS error code of 1 if the user answers Y or y; otherwise it
* returns 0. The error code could be tested in a batch file.
*/
#include <conio.h>
#include <stdlib.h>
void main()
{
char ch;
cputs( "Yes or no? " );
ch = getch();
cputs( "\r\n" );
if( toupper( ch ) == 'Y' )
exit( 1 );
else
exit( 0 );
}
exp, expl
────────────────────────────────────────────────────────────────────────────
Description
Calculate the exponential.
#include <math.h>
double exp( double x );
long double expl( long double x );
x Floating-point value
Remarks
The exp and expl functions return the exponential function of their
floating-point arguments (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
ANSI DOS OS/2 UNIX XENIX
expl
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
log functions
Example
/* EXP.C */
#include <math.h>
#include <stdio.h>
void main()
{
double x = 2.302585093, y;
y = exp( x );
printf( "exp( %f ) = %f\n", x, y );
}
Output
exp( 2.302585 ) = 10.000000
_expand Functions
────────────────────────────────────────────────────────────────────────────
Description
Changes the size of a memory block.
#include <malloc.h> Required only for function declarations
void *_expand( void *memblock, size_t size );
void _based( void ) *_bexpand( _segment seg, void _based( void )
*memblock,
size_t size );
void _far *_fexpand( void _far *memblock, size_t size );
void _near *_nexpand( void _near *memblock, size_t size );
memblock Pointer to previously allocated memory
block
size New size in bytes
seg Value of base segment
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 memblock 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
────────────────────────────────────────────────────────────────────────────
_expand Depends on data model of program
_bexpand Based heap specified by seg, or in all
based heaps if seg
is zero
_fexpand Far heap (outside default data segment)
_nexpand Near heap (inside default 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 insufficient 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.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
calloc functions, free functions, malloc functions, _msize functions,
realloc functions
Example
/* EXPAND.C */
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
void main()
{
char *bufchar;
printf( "Allocate a 512 element buffer\n" );
if( (bufchar = (char *)calloc( 512, sizeof( char ) )) == NULL )
exit( 1 );
printf( "Allocated %d bytes at %Fp\n",
_msize( bufchar ), (void _far *)bufchar );
if( (bufchar = (char *)_expand( bufchar, 1024 )) == NULL )
printf( "Can't expand" );
else
printf( "Expanded block to %d bytes at %Fp\n",
_msize( bufchar ), (void _far *)bufchar );
/* Free memory */
free( bufchar );
exit( 0 );
}
Output
Allocate a 512 element buffer
Allocated 512 bytes at 0067:142A
Expanded block to 1024 bytes at 0067:142A
fabs, fabsl
────────────────────────────────────────────────────────────────────────────
Description
Calculate the absolute value of their floating-point arguments.
#include <math.h>
double fabs( double x );
long double fabsl( long double x );
x Floating-point value
Remarks
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, 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 the absolute value of their arguments. There is no
error return.
Compatibility
fabs
ANSI DOS OS/2 UNIX XENIX
fabsl
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
abs, cabs, labs
Example
/* ABS.C: This program computes and displays the absolute values of
* several numbers.
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
int ix = -4, iy;
long lx = -41567L, ly;
double dx = -3.141593, dy;
iy = abs( ix );
printf( "The absolute value of %d is %d\n", ix, iy);
ly = labs( lx );
printf( "The absolute value of %ld is %ld\n", lx, ly);
dy = fabs( dx );
printf( "The absolute value of %f is %f\n", dx, dy );
}
Output
The absolute value of -4 is 4
The absolute value of -41567 is 41567
The absolute value of -3.141593 is 3.141593
fclose, fcloseall
────────────────────────────────────────────────────────────────────────────
Description
Closes a stream (fclose) or closes all open streams (fcloseall).
#include <stdio.h>
int fclose( FILE *stream );
int fcloseall( void );
stream Pointer to FILE structure
Remarks
The fclose function closes stream. The fcloseall function closes all open
streams except stdin, stdout, stderr (and in DOS, stdaux and stdprn). It
also closes and deletes any temporary 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 returns the total number of streams closed. Both
functions return EOF to indicate an error.
Compatibility
fclose
ANSI DOS OS/2 UNIX XENIX
fcloseall
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
close, fdopen, fflush, fopen, freopen
Example
/* FOPEN.C: This program opens files named "data" and "data2". It uses
* fclose to close "data" and fcloseall to close all remaining files.
*/
#include <stdio.h>
FILE *stream, *stream2;
void main()
{
int numclosed;
/* Open for read (will fail if 'data does not exist) */
if( (stream = fopen( "data", "r" )) == NULL )
printf( "The file 'data' was not opened\n" );
else
printf( "The file 'data' was opened\n" );
/* Open for write */
if( (stream2 = fopen( "data2", "w+" )) == NULL )
printf( "The file 'data2' was not opened\n" );
else
printf( "The file 'data2' was opened\n" );
/* Close stream */
if( fclose( stream ) )
printf( "The file 'data' was not closed\n" );
/* All other files are closed: */
numclosed = fcloseall( );
printf( "Number of files closed by fcloseall: %u\n", numclosed );
}
Output
The file 'data' was opened
The file 'data2' was opened
Number of files closed by fcloseall: 1
fcvt
────────────────────────────────────────────────────────────────────────────
Description
Converts a floating-point number to a string.
#include <stdlib.h> Required only for function declarations
char *fcvt( double value, int count, int *dec, int *sign );
value Number to be converted
count Number of digits after decimal point
dec Pointer to stored decimal-point position
sign Pointer to stored sign indicator
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 specifies 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 dec and sign after the call. The dec
argument points to an integer value; this integer value gives the position
of the decimal point with respect to the beginning 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.
Compatibility
▼ ANSI DOS OS/2 UNIX XENIX
See Also
atof, atoi, atol, ecvt, gcvt
Example
/* FCVT.C: This program converts the constant 3.1415926535 to a string and
* sets the pointer *buffer to point to that string.
*/
#include <stdlib.h>
#include <stdio.h>
void main()
{
int decimal, sign;
char *buffer;
double source = 3.1415926535;
buffer = fcvt( source, 7, &decimal, &sign );
printf( "source: %2.10f buffer: '%s' decimal: %d sign: %d\n",
source, buffer, decimal, sign );
}
Output
source: 3.1415926535 buffer: '31415927' decimal: 1 sign: 0
fdopen
────────────────────────────────────────────────────────────────────────────
Description
Opens a stream using a handle.
#include <stdio.h>
FILE *fdopen( int handle, char *mode );
handle Handle referring to open file
mode Type of access permitted
Remarks
The fdopen function associates an input/output stream with the file
identified by handle, thus allowing a file opened for "low-level" I/O to be
buffered and formatted. (See Section 2.7, "Input and Output," for an
explanation of stream I/O and low-level I/O.) The mode character string
specifies the type of access requested for the file, as shown below. The
following list gives the mode string used in the fopen and fdopen functions
and the corresponding 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.
Type String Equivalent Value for open/sopen
────────────────────────────────────────────────────────────────────────────
"r" O_RDONLY
"w" O_WRONLY (usually O_WRONLY | O_CREAT |
O_TRUNC)
"a" O_WRONLY | O_APPEND (usually O_WRONLY |
O_CREAT | O_APPEND)
"r+" O_RDWR
"w+" O_RDWR (usually O_RDWR | O_CREAT |
O_TRUNC)
"a+" O_RDWR | O_APPEND (usually O_RDWR |
O_APPEND | O_CREAT )
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:
Mode Equivalent Value for open/sopen
────────────────────────────────────────────────────────────────────────────
t O_TEXT
b O_BINARY
If t or b is not given in the mode string, the translation mode is defined
by the default-mode variable _fmode.
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.
Compatibility
▼ ANSI DOS OS/2 UNIX XENIX
See Also
dup, dup2, fclose, fcloseall, fopen, freopen, open
Example
/* FDOPEN.C: This program opens a file using low-level I/O, then uses
* fdopen to switch to stream access. It counts the lines in the file.
*/
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
void main()
{
FILE *stream;
int fh, count = 0;
char inbuf[128];
/* Open a file handle. */
if( (fh = open( "fdopen.c", O_RDONLY )) == -1 )
exit( 1 );
/* Change handle access to stream access. */
if( (stream = fdopen( fh, "r" )) == NULL )
exit( 1 );
while( fgets( inbuf, 128, stream ) != NULL )
count++;
/* After fdopen, close with fclose, not close. */
fclose( stream );
printf( "Lines in file: %d\n", count );
}
Output
Lines in file: 31
feof
────────────────────────────────────────────────────────────────────────────
Description
Tests for end-of-file on a stream.
#include <stdio.h>
int feof( FILE *stream );
stream Pointer to FILE structure
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 against it.
Return Value
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 error return.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
clearerr, eof, ferror, perror
Example
/* FEOF.C: This program uses feof to indicate when it reaches the end
* of the file FEOF.C. It also checks for errors with ferror.
*/
#include <stdio.h>
#include <stdlib.h>
void main()
{
int count, total = 0;
char buffer[100];
FILE *stream;
if( (stream = fopen( "feof.c", "r" )) == NULL )
exit( 1 );
/* Cycle until end of file reached: */
while( !feof( stream ) )
{
/* Attempt to read in 10 bytes: */
count = fread( buffer, sizeof( char ), 100, stream );
if( ferror( stream ) )
{
perror( "Read error" );
break;
}
/* Total up actual bytes read */
total += count;
}
printf( "Number of bytes read = %d\n", total );
fclose( stream );
}
Output
Number of bytes read = 697
ferror
────────────────────────────────────────────────────────────────────────────
Description
Tests for an error on a stream.
#include <stdio.h>
int ferror( FILE *stream );
stream Pointer to FILE structure
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.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
clearerr, eof, feof, fopen, perror
Example
/* FEOF.C: This program uses feof to indicate when it reaches the end
* of the file FEOF.C. It also checks for errors with ferror.
*/
#include <stdio.h>
#include <stdlib.h>
void main()
{
int count, total = 0;
char buffer[100];
FILE *stream;
if( (stream = fopen( "feof.c", "r" )) == NULL )
exit( 1 );
/* Cycle until end of file reached: */
while( !feof( stream ) )
{
/* Attempt to read in 10 bytes: */
count = fread( buffer, sizeof( char ), 100, stream );
if( ferror( stream ) )
{
perror( "Read error" );
break;
}
/* Total up actual bytes read */
total += count;
}
printf( "Number of bytes read = %d\n", total );
fclose( stream );
}
Output
Number of bytes read = 697
fflush
────────────────────────────────────────────────────────────────────────────
Description
Flushes a stream.
#include <stdio.h>
int fflush( FILE *stream );
stream Pointer to FILE structure
Remarks
If the file associated with stream is open for output, fflush writes to that
file the contents of the buffer associated with the stream. If the stream is
open for input, fflush clears the contents of the buffer. The fflush
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 fflush function has no effect on
an unbuffered stream.
Return Value
The fflush 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.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
fclose, flushall, setbuf
Example
/* FFLUSH.C */
#include <stdio.h>
#include <conio.h>
void main()
{
int integer;
char string[81];
/* Read each word as a string. */
printf( "Enter a sentence of four words with scanf: " );
for( integer = 0; integer < 4; integer++ )
{
scanf( "%s", string );
printf( "%s\n", string );
}
/* You must flush the input buffer before using gets. */
fflush( stdin );
printf( "Enter the same sentence with gets: " );
gets( string );
printf( "%s\n", string );
}
Output
Enter a sentence of four words with scanf: This is a test
This
is
a
test
Enter the same sentence with gets: This is a test
This is a test
fgetc, fgetchar
────────────────────────────────────────────────────────────────────────────
Description
Read a character from a stream (fgetc) or stdin (fgetchar).
#include <stdio.h>
int fgetc( FILE *stream );
int fgetchar( void );
stream Pointer to FILE structure
Remarks
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 increments the associated file pointer (if any) to
point to the next character. The fgetchar function is equivalent to
fgetc(stdin).
The fgetc and fgetchar routines are identical to getc and getchar, but they
are functions rather than macros.
Return 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.
Compatibility
fgetc
ANSI DOS OS/2 UNIX XENIX
fgetchar
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
fputc, fputchar, getc, getchar
Example
/* FGETC.C: This program uses getc to read the first 80 input characters
* (or until the end of input) and place them into a string named buffer.
*/
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *stream;
char buffer[81];
int i, ch;
/* Open file to read line from: */
if( (stream = fopen( "fgetc.c", "r" )) == NULL )
exit( 0 );
/* Read in first 80 characters and place them in "buffer": */
ch = fgetc( stream );
for( i=0; (i < 80 ) && ( feof( stream ) == 0 ); i++ )
{
buffer[i] = ch;
ch = fgetc( stream );
}
/* Add null to end string */
buffer[i] = '\0';
printf( "%s\n", buffer );
fclose( stream );
}
Output
/* FGETC.C: This program uses getc to read the first 80 input characters
/* (or
fgetpos
────────────────────────────────────────────────────────────────────────────
Description
Gets a stream's file-position indicator.
#include <stdio.h>
int fgetpos( FILE *stream, fpos_t *pos );
stream Target stream
pos Position-indicator storage
Remarks
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 information stored in pos to reset the stream
argument's pointer to its position at the time fgetpos was called.
The pos value is stored in an internal format 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
────────────────────────────────────────────────────────────────────────────
EBADF The specified stream is not a valid file
handle or is not
accessible.
EINVAL The stream value is invalid.
Compatibility
ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
fsetpos
Example
/* FGETPOS.C: This program opens a file and reads bytes at several
* different locations.
*/
#include <stdio.h>
void main()
{
FILE *stream;
fpos_t pos;
int val;
char buffer[20];
if( (stream = fopen( "fgetpos.c", "rb" )) == NULL )
printf( "Trouble opening file\n" );
else
{
/* Read some data and then check the position. */
fread( buffer, sizeof( char ), 10, stream );
if( fgetpos( stream, &pos ) != 0 )
perror( "fgetpos error" );
else
{
fread( buffer, sizeof( char ), 10, stream );
printf( "10 bytes at byte %ld: %.10s\n", pos, buffer );
}
/* Set a new position and read more data */
pos = 140;
if( fsetpos( stream, &pos ) != 0 )
perror( "fsetpos error" );
fread( buffer, sizeof( char ), 10, stream );
printf( "10 bytes at byte %ld: %.10s\n", pos, buffer );
fclose( stream );
}
}
Output
10 bytes at byte 10: .C: This p
10 bytes at byte 140: FILE *
fgets
────────────────────────────────────────────────────────────────────────────
Description
Gets a string from a stream.
#include <stdio.h>
char *fgets( char *string, int n, FILE *stream );
string Storage location for data
n Number of characters stored
stream Pointer to FILE structure
Remarks
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 1, string is empty (""). The fgets function is similar to the gets
function; however, gets replaces the newline character with NULL.
Return 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.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
fputs, gets, puts
Example
/* FGETS.C: This program uses fgets to display a line from a file on the
* screen.
*/
#include <stdio.h>
FILE *stream;
void main()
{
char line[100], *result;
if( (stream = fopen( "fgets.c", "r" )) != NULL )
{
if( fgets( line, 100, stream ) == NULL)
printf( "fgets error\n" );
else
printf( "%s", line);
fclose( stream );
}
}
Output
/* FGETS.C: This program uses fgets to display a line from a file on the
fieeetomsbin, fmsbintoieee
────────────────────────────────────────────────────────────────────────────
Description
Convert floating-point numbers between IEEE and Microsoft binary formats.
#include <math.h>
int fieeetomsbin( float *src4, float *dst4 );
int fmsbintoieee( float *src4, float *dst4 );
scr4 Value to be converted
dst4 Converted value
Remarks
The fieeetomsbin routine converts a single-precision floating-point number
in IEEE (Institute of Electrical and Electronic Engineers) format to
Microsoft (MS) binary format.
The fmsbintoieee routine converts a floating-point number in Microsoft
binary format to IEEE format.
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
Microsoft BASIC (which stores floating-point numbers in the Microsoft binary
format), and vice versa.
The argument src4 points to the float value to be converted. The result is
stored at the location given by dst4.
These routines do not handle IEEE NANs ("not a number") and infinities. IEEE
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.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
dieeetomsbin, dmsbintoieee
filelength
────────────────────────────────────────────────────────────────────────────
Description
Gets the length of a file.
#include <io.h> Required only for function declarations
long filelength( int handle );
handle Target file handle
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
-1L indicates an error, and an invalid handle sets errno to EBADF.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
chsize, fileno, fstat, stat
Example
/* CHSIZE.C: This program uses filelength to report the size of a
* file before and after modifying it with chsize.
*/
#include <io.h>
#include <fcntl.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <stdio.h>
void main()
{
int fh, result;
unsigned int nbytes = BUFSIZ;
/* Open a file */
if( (fh = open( "data", O_RDWR | O_CREAT, S_IREAD | S_IWRITE )) != -1 )
{
printf( "File length before: %ld\n", filelength( fh ) );
if( chsize( fh, 329678 ) == 0 )
printf( "Size successfully changed\n" );
else
printf( "Problem in changing the size\n" );
printf( "File length after: %ld\n", filelength( fh ) );
close( fh );
}
}
Output
File length before: 0
Size successfully changed
File length after: 329678
fileno
────────────────────────────────────────────────────────────────────────────
Description
Gets the file handle associated with a stream.
#include <stdio.h>
int fileno( FILE *stream );
stream Pointer to FILE structure
Remarks
The fileno routine returns the file handle currently associated with stream.
This routine is implemented as a macro.
Return 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.
Compatibility
▼ ANSI DOS OS/2 UNIX XENIX
See Also
fdopen, filelength, fopen, freopen
Example
/* FILENO.C: This program uses fileno to obtain the file handle for
* some standard C streams.
*/
#include <stdio.h>
void main()
{
printf( "The file handle for stdin is %d\n", fileno( stdin ) );
printf( "The file handle for stdout is %d\n", fileno( stdout ) );
printf( "The file handle for stderr is %d\n", fileno( stderr ) );
}
Output
The file handle for stdin is 0
The file handle for stdout is 1
The file handle for stderr is 2
_floodfill, _floodfill_w
────────────────────────────────────────────────────────────────────────────
Description
Fill an area of a display using the current color and fill mask
#include <graph.h>
short _far _floodfill( short x, short y, short boundary );
short _far _floodfill_w( double wx, double wy, short boundary );
x, y Start point
wx, wy Start point
boundary Boundary color of area to be filled
Remarks
The functions in the _floodfill family fill an area of the display, using
the current color and fill mask. The _floodfill 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 background is filled. The point must be inside or
outside the figure to be filled, not on the figure boundary itself. Filling
occurs in all directions, stopping at the color of boundary.
Return 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.
Compatibility
▼ ANSI DOS ▼ OS/2 ▼ UNIX ▼ XENIX
See Also
_ellipse functions, _getcolor, _getfillmask, _grstatus, _pie functions,
_setfillmask, _setcliprgn, _setcolor
Example
/* FLOODFIL.C: This program draws a series of nested rectangles in
* different colors, constantly changing the background color.
*/
#include <conio.h>
#include <stdlib.h>
#include <graph.h>
void main()
{
int loop;
int xvar, yvar;
/* find a valid graphics mode */
if( !_setvideomode( _MAXCOLORMODE ) )
exit( 1 );
for( xvar = 163, loop = 0; xvar < 320; loop++, xvar += 3 )
{
_setcolor( loop % 16 );
yvar = xvar * 5 / 8;
_rectangle( _GBORDER, 320-xvar, 200-yvar, xvar, yvar );
_setcolor( rand() % 16 );
_floodfill( 0, 0, loop % 16 );
}
getch();
_setvideomode( _DEFAULTMODE );
}
floor, floorl
────────────────────────────────────────────────────────────────────────────
Description
Calculate the floor of a value.
#include <math.h>
double floor( double x );
long double floorl( long double x );
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,
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 the floating-point result. There is no error return.
Compatibility
floor
ANSI DOS OS/2 UNIX XENIX
floorl
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
ceil, fmod
Example
/* FLOOR.C: This example displays the largest integers less than or equal
* to the floating-point values 2.8 and -2.8. It then shows the smallest
* integers greater than or equal to 2.8 and -2.8.
*/
#include <math.h>
#include <stdio.h>
void main()
{
double y;
y = floor( 2.8 );
printf( "The floor of 2.8 is %f\n", y );
y = floor( -2.8 );
printf( "The floor of -2.8 is %f\n", y );
y = ceil( 2.8 );
printf( "The ceil of 2.8 is %f\n", y );
y = ceil( -2.8 );
printf( "The ceil of -2.8 is %f\n", y );
}
Output
The floor of 2.8 is 2.000000
The floor of -2.8 is -3.000000
The ceil of 2.8 is 3.000000
The ceil of -2.8 is -2.000000
flushall
────────────────────────────────────────────────────────────────────────────
Description
Flushes all streams; clears all buffers.
#include <stdio.h>
int flushall( void );
Remarks
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.
Return Value
The flushall function returns the number of open streams (input and output).
There is no error return.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
fflush
Example
/* FLUSHALL.C: This program uses flushall to flush all open buffers. */
#include <stdio.h>
void main()
{
int numflushed;
numflushed = flushall();
printf( "There were %d streams flushed\n", numflushed );
}
Output
There were 3 streams flushed
fmod, fmodl
────────────────────────────────────────────────────────────────────────────
Description
Calculates the floating-point remainder.
#include <math.h>
double fmod( double x, double y );
long double fmodl( long double x, long double y );
x, y Floating-point values
Remarks
The fmod and fmodl functions calculate the floating-point remainder f of x /
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 less than the absolute value of y.
The fmodl function is the 80-bit counterpart; it uses the 80-bit, 10-byte
coprocessor form of arguments and return values. See the discussion of the
long double functions for more details on this data type.
Return Value
These functions return the floating-point remainder. If y is 0, the function
returns 0.
Compatibility
fmod
ANSI DOS OS/2 UNIX XENIX
fmodl
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
ceil, fabs, floor
Example
/* FMOD.C: This program displays a floating-point remainder. */
#include <math.h>
#include <stdio.h>
void main()
{
double x = -10.0, y = 3.0, z;
z = fmod( x, y );
printf( "The remainder of %.2f / %.2f is %f\n", x, y, z );
}
Output
The remainder of -10.00 / 3.00 is -1.000000
fopen
────────────────────────────────────────────────────────────────────────────
Description
Opens a file.
#include <stdio.h>
FILE *fopen( const char *filename, const char *mode );
filename Path name of file
mode Type of access permitted
Remarks
The fopen function opens the file specified by filename. The character
string mode specifies the type of access requested for the file, as follows:
Type 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 allowed (the file is said to be open for "update"). However,
when you switch between reading 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 can
be included in mode to specify the translation mode for newline characters:
Mode Meaning
────────────────────────────────────────────────────────────────────────────
t Open in text (translated) mode. In this
mode, carriage-return-line-feed (CR-LF)
combinations are translated into single
line feeds (LF) on input and LF
characters are translated to CR-LF
combinations on output. Also, CTRL+Z is
interpreted as an end-of-file character
on input. In files opened for reading or
for reading/writing, fopen checks for a
CTRL+Z at the end of the file and
removes it, if possible. This is done
because using the fseek and ftell
functions to move within a file that
ends with a CTRL+Z may cause fseek to
behave improperly near the end of 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 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.
Compatibility
ANSI DOS OS/2 UNIX XENIX
Note that the t option is not part of the ANSI standard for fopen; it is a
Microsoft extension and should not be used where ANSI portability is
desired.
See Also
fclose, fcloseall, fdopen, ferror, fileno, freopen, open, setmode
Example
/* FOPEN.C: This program opens files named "data" and "data2". It uses
* fclose to close "data" and fcloseall to close all remaining files.
*/
#include <stdio.h>
FILE *stream, *stream2;
void main()
{
int numclosed;
/* Open for read (will fail if 'data' does not exist) */
if( (stream = fopen( "data", "r" )) == NULL )
printf( "The file 'data' was not opened\n" );
else
printf( "The file 'data' was opened\n" );
/* Open for write */
if( (stream2 = fopen( "data2", "w+" )) == NULL )
printf( "The file 'data2' was not opened\n" );
else
printf( "The file 'data2' was opened\n" );
/* Close stream */
if( fclose( stream ) )
printf( "The file 'data' was not closed\n" );
/* All other files are closed: */
numclosed = fcloseall( );
printf( "Number of files closed by fcloseall: %u\n", numclosed );
}
Output
The file 'data' was opened
The file 'data2' was opened
Number of files closed by fcloseall: 1
FP_OFF, FP_SEG
────────────────────────────────────────────────────────────────────────────
Description
Get or set a far-pointer offset (FP_OFF) or a far-pointer segment (FP_SEG).
#include <dos.h>
unsigned FP_OFF( void _far *address );
unsigned FP_SEG( void _far *address );
address Far pointer to memory address
Remarks
The FP_OFF and FP_SEG macros can be used to set or get the offset and
segment, respectively, of the far pointer at address.
Return Value
The FP_OFF macro returns an offset. The FP_SEG macro returns a segment
address.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
Example
/* FP_SEG.C: This program uses FP_SEG and FP_OFF to obtain
* the segment and offset of the long pointer p.
*/
#include <dos.h>
#include <malloc.h>
#include <stdio.h>
void main()
{
void _far *p;
unsigned int seg_val;
unsigned int off_val;
p = _fmalloc( 100 ); /* Points pointer at something */
seg_val = FP_SEG( p ); /* Gets address pointed to */
off_val = FP_OFF( p );
printf( "Segment is %.4X; Offset is %.4X\n", seg_val, off_val );
}
Output
Segment is 00C7; Offset is 0016
_fpreset
────────────────────────────────────────────────────────────────────────────
Description
Resets the floating-point package.
#include <float.h>
void _fpreset( void );
Remarks
The _fpreset function reinitializes the floating-point-math package. This
function is usually 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.
Return Value
None.
Compatibility
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
exec functions, signal, spawn functions
Example
/* FPRESET.C: This program uses signal to set up a routine for handling
* floating-point errors.
*/
#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include <string.h>
jmp_buf mark; /* Address for long jump to jump to */
int fperr; /* Global error number */
void fphandler( int sig, int num ); /* Prototypes */
void fpcheck( void );
void main()
{
double n1, n2, r;
int jmpret;
/* Set up floating point error handler. */
if( signal( SIGFPE, fphandler ) == SIG_ERR )
{
fprintf( stderr, "Couldn't set SIGFPE\n" );
abort();
}
/* Save stack environment for return in case of error. First time
* through, jmpret is 0, so true conditional is executed. If an
* error occurs, jmpret will be set to -1 and false conditional
* will be executed.
*/
jmpret = setjmp( mark );
if( jmpret == 0 )
{
printf( "Test for invalid operation - " );
printf( "enter two numbers: " );
scanf( "%lf %lf", &n1, &n2 );
r = n1 / n2;
/* This won't be reached if error occurs. */
printf( "\n\n%4.3g / %4.3g = %4.3g\n", n1, n2, r );
r = n1 * n2;
/* This won't be reached if error occurs. */
printf( "\n\n%4.3g * %4.3g = %4.3g\n", n1, n2, r );
}
else
fpcheck();
}
/* Handles SIGFPE (floating point error) interrupt. */
void fphandler( int sig, int num )
{
/* Set global for outside check since we don't want to do I/O in the
* handler.
*/
fperr = num;
/* Initialize floating-point package. */
_fpreset();
/* Restore calling environment and jump back to setjmp. Return -1
* so that setjmp will return false for conditional test.
*/
longjmp( mark, -1 );
}
void fpcheck()
{
char fpstr[30];
switch( fperr )
{
case FPE_INVALID:
strcpy( fpstr, "Invalid number" );
break;
case FPE_OVERFLOW:
strcpy( fpstr, "Overflow" );
break;
case FPE_UNDERFLOW:
strcpy( fpstr, "Underflow" );
break;
case FPE_ZERODIVIDE:
strcpy( fpstr, "Divide by zero" );
break;
default:
strcpy( fpstr, "Other floating point error" );
break;
}
printf( "Error %d: %s\n", fperr, fpstr );
}
Output
Test for invalid operation - enter two numbers: 5 0
Error 131: Divide by zero
fprintf
────────────────────────────────────────────────────────────────────────────
Description
Prints formatted data to a stream.
#include <stdio.h>
int fprintf( FILE *stream, const char *format [[, argument]]... );
stream Pointer to FILE structure
format Format-control string
argument Optional arguments
Remarks
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 in format.
The format 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 on format and argument.
Return Value
The fprintf function returns the number of characters printed, or a negative
value in the case of an output error.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
cprintf, fscanf, printf, sprintf
Example
/* FPRINTF.C: This program uses fprintf to format various data and
* print them to the file named FPRINTF.OUT. It then displays
* FPRINTF.OUT on the screen using the system function to invoke
* the DOS TYPE command.
*/
#include <stdio.h>
#include <process.h>
FILE *stream;
void main()
{
int i = 10;
double fp = 1.5;
char s[] = "this is a string";
char c = '\n';
stream = fopen( "fprintf.out", "w" );
fprintf( stream, "%s%c", s, c );
fprintf( stream, "%d\n", i );
fprintf( stream, "%f\n", fp );
fclose( stream );
system( "type fprintf.out" );
}
Output
this is a string
10
1.500000
fputc, fputchar
────────────────────────────────────────────────────────────────────────────
Description
Write a character to a stream (fputc) or to stdout (fputchar).
#include <stdio.h>
int fputc( int c, FILE *stream );
int fputchar( int c );
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 position. 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 indicates an error.
Compatibility
fputc
ANSI DOS OS/2 UNIX XENIX
fputchar
▼ ANSI DOS OS/2 ▼ UNIX ▼ XENIX
See Also
fgetc, fgetchar, putc, putchar
Example
/* FPUTC.C: This program uses fputc and fputchar to send a character
* array to stdout.
*/
#include <stdio.h>
void main()
{
char strptr1[] = "This is a test of fputc!!\n";
char strptr2[] = "This is a test of fputchar!!\n";
char *p;
/* Print line to stream using fputc. */
p = strptr1;
while( (*p != '\0') && fputc( *(p++), stdout ) != EOF )
;
/* Print line to stream using fputchar. */
p = strptr2;
while( (*p != '\0') && fputchar( *(p++) ) != EOF )
;
}
Output
This is a test of fputc!!
This is a test of fputchar!!
fputs
────────────────────────────────────────────────────────────────────────────
Description
Writes a string to a stream.
#include <stdio.h>
int fputs( const char *string, FILE *stream );
string String to be output
stream Pointer to FILE structure
Remarks
The fputs function copies string to the output stream at the current
position. The terminating null character ('\0') is not copied.
Return Value
The fputs function returns a nonnegative value if it is successful. If an
error occurs, it returns EOF.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
fgets, gets, puts
Example
/* FPUTS.C: This program uses fputs to write a single line to the
* stdout stream.
*/
#include <stdio.h>
void main()
{
fputs( "Hello world from fputs.\n", stdout );
}
Output
Hello world from fputs.
fread
────────────────────────────────────────────────────────────────────────────
Description
Reads data from a stream.
#include <stdio.h>
size_t fread( void *buffer, size_t size, size_t count, FILE *stream );
buffer Storage location for data
size Item size in bytes
count Maximum number of items to be read
stream Pointer to FILE structure
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 return 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 count.
The feof or ferror function should be used to distinguish a read error from
an end-of-file condition. If size or count is 0, fread returns 0 and the
buffer contents are unchanged.
Compatibility
ANSI DOS OS/2 UNIX XENIX
See Also
fwrite, read
Example
/* FREAD.C: This program opens a file named FREAD.OUT and writes 25
* characters to the file. It then tries to open FREAD.OUT and
* read in 25 characters. If the attempt succeeds, the program
* displays the number of actual items read.
*/
#include <stdio.h>
void main()
{
FILE *stream;
char list[30];
int i, numread, numwritten;
/* Open file in text mode: */
if( (stream = fopen( "fread.out", "w+t" )) != NULL )
{
for ( i = 0; i < 25; i++ )
list[i] = 'z' - i;
/* Write 25 characters to stream */
numwritten = fwrite( list, sizeof( char ), 25, stream );
printf( "Wrote %d items\n", numwritten );
fclose( stream );
}
else
printf( "Problem opening the file\n" );
if( (stream = fopen( "fread.out", "r+t" )) != NULL )
{
/* Attempt to read in 25 characters */
numread = fread( list, sizeof( char ), 25, stream );
printf( "Number of items read = %d\n", numread );
printf( "Contents of buffer = %.25s\n", list );
fclose( stream );
}
else
printf( "Was not able to open the file\n" );
}
Output
Wrote 25 items
Number of items read = 25
Contents of buffer = zyxwvutsrqponmlkjihgfedcb
free Functions
────────────────────────────────────────────────────────────────────────────
Description
Deallocate a memory block.
#include <stdlib.h> For ANSI compatibility (free only)
#include <malloc.h> Required only for function declarations
void free( void *memblock );
void _bfree( _segment seg, void _based( void ) *memblock );
void _ffree( void _far *memblock );
void _nfree( void _near *memblock );
memblock Allocated memory block
seg Based-heap segment selector
Remarks
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 functi