414
DeSMET DC88 C COMPILER MARK DeSMET Published and Distributed by C WARE CORPORATION PASO ROBLES , CALIFORNIA

Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

  • Upload
    lethuy

  • View
    220

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

DeSMET DC88C COMPILER

MARK DeSMET

Published and Distributed by

C WARE CORPORATIONPASO ROBLES , CALIFORNIA

Page 2: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

DeSmet C Development Package

Version 3. May, 1988

Version 3.03 February, 1988 (DC88)Version 3. - April, 1987Version 2. - October, 1985Version 2.4 - October, 1984Version 2. April, 1984

Published by: C Ware CorporationO. Box 428

Paso RobJes, CA 93447USA

. . ' ,

(805) 239 4620 (Tech 'SupportSales)

(805) 239-4834 (Tech BBS)

Copyright (Q 1982 - 1988 by DeSmet Software

All rights reserved. Printed in the United States of America. No part of thispublication may be reproduced , stored in a retrieval system, or transmitted in anyform or by any means electronic, mechanical, photocopying, recording orotherwise without prior written permission of the publisher.

DISCLAIMER OF WARRANTIES AND LIMITATION OF LIABILITIES

The author has taken due care in preparing this book and the programs and data onthe electronic media accompanying this book including research, development, andtesting to ascertain their effectiveness. The author and the publisher make noexpressed or implied warranty of any kind with regard to these programs nor thesupplemental documentation in this book. In no event shall the author or C WareCorporation be liable for incidental or consequential damages in connection with orarising out of the furnishing, performance or use of any of these programs.

DeSmet C Development Package and SEE are Trademarks of C Ware Corporation.

CP/M-86 is a Trademark of Digita,l Research, Inc. .IBM is a Registered Trademark ofInternationalBusiness Machines.MSDOS is a Trademark of Microsoft, Inc.UNIX is a Trademark of Bell Laboratories.

Page 3: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Table of Contents

IntroductionOverview 1.1

Large Case Option 1.3

Gettng StartedBacking Up

Installng The Software 2.1

Installng DC88Installng DC88 ona Hard DiskInstalling DC88 on a Floppy Disk

2.i2.4

Installng the Large Case Option 2:10Installing Large Case on a Hard Disk 2.Installing Large Case on a Floppy Disk 2.

A Short Example

Completion Codes

The SEETM Text EditorIntroduction

Getting StaredConceptsStaring the EditorInserting & Editing TextSaving the FileEditing Existing Files

3.4

The Invocation Line

The KeyboardCursor Movement KeysEditing KeysThe DOS Key

Commands

Configuration

Page 4: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Table of Contents

The C88 C CompilerIntroduction

InvocationExamples

The C LanguageEnvironment

Character Set

Trigraph SequencesLanguage

KeywordsIdentifiers, Floating constants

. Integer constantsCharacter constantsString constantsHardware data typesEnumerated type Function proto typing

Preprocessor Conditional compilationSource fie inclusion

Macro replacementLine controlErrorPragmaNullPredefined macros

ExtensionsAsmCase range

RestrictionsForward referencesExterns

Large Case Option

The ASM88 AssemblerIntroduction

Invocation

Examples

Large Case ASM88

4.3

4.44.4

4.5

4;10

Page 5: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Table of Contents

The BIND Object File LinkerIntroduction

Invocation

Examples

Small Case BINDSpace ConsiderationsOverlays 6.4

Large Case BIND

Libraries

The LIB88 Object File LibrarianIntroduction

Invocation

Examples 7.2

Libraries

The D88 C Language DebuggerIntroduction

D88 Usage

Command Input

Expressions 8.3

Commands

Utilty ProgramsCLIST: a listing & xref utilty

DUMP: a hex and ascii display utilty

FASTSCR: a screen output enhancer

FREE: a free space display

GREP: a fie search utilty

Page 6: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Table of Contents

LS: a directory listing util

MERGE: a C source and assemblylanguage merge utilty

MORE: a fie screen listing utilty.

PCmake: a program maintainanc utilty

PROFILE: a performance monitor utilty

RM: a fie removal utilty

SENSE87: an 8087/80287 sensing librar

TOOLBOX.S: a librar of useful tools

The CSTDIO LibraryIntroduction

Names

Program Initialization

Callng Conventions

Memory Management

Input/Output LibrarDirectory Level FunctionsFile Level FunctionsStream Level FunctionsHandle Level FunctionsScreen Level FunctionsConsole Level Functions

Math Library

System Interface

Environment

9.4

9.5

10.

10.

10.

10.4

10.

10.10.10.10.10.10.10.

10.

10.

10. 18-

Page 7: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Table of Contents

LibraryHeaders

assert.ctype.math.setjmp.stdarg.stdio.stdlib.string.

Functions & MacrosAlphabetical by name

Appendix A: Messages

ASM88 Messages Baner and Termination MessagesASM88 Fatal Error MessagesASM88 Error Messages

BIN MessagesBaner and Termination MessagesBIND Fatal Error MessagesBIN Warng Messages

C88 MessagesBanner and Termination MessagesC88 Fatal Error MessagesC88 Error MessagesC88 Warnng MessagesC88 ASM88 Messages

CLIST MessagesBanner and Termination MessagesCLIST Fatal Error Messages

D88 Messages

LIB88 MessagesBanner and Termination MessagesLIB 88 Fatal Error MessagesLIB88 Waring Messages

SEE MessagesBanner and Termination MessagesSEE Error and Status Messages

10. 18-

10.18-10. 18-10. 18-10. 18-10. 18-10.18-10. 18-10. 18-

A.2A.2

A.7A.7A.8

A.9

A.12

A.17

A.18

A.21A.21A.22

A.23

Page 8: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Table of Contents

. Appendix B: The ASM88 Assembly Language

Identifiers

Constants

Expressions

RegistersGeneral RegistersByte RegistersSegment Registers

Addressing Modes

8086 Flags

Address Expressions

Address Typing

Comments

Assembler Direectives

Reserving Storage

Differences between ASM86 and ASM88

8086 InstructionsElements of InstructionsInstrctions

8087Control WordStatus WordTag WordCondition Codes

8087 Instructions

B.3B.3

B.4

B.5

Page 9: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Preface

This manual describes the DeSmet C Development Package for the IBM-personal computer and the other MS-DOS based personal computers. If you areunfamilar with the C language or UNIX, the book The Programming Languageby Brian Kernighan and Denns Ritchie is a good place to star. If you plan oncoding in assembly language, it is advisable to get a manual on the Intel 8086microprocessor. Books such as Intel's ASM86 Language Reference Manual or The8086 Family User s Guide are good choices. These manuals fully describe thearchitecture and the instruction set of the 8086/8088 family of microprocessors.

We than both the Pacific Data Works, and Scott Lewis for proofreading the manyrevisions of this manual.

Page 10: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 11: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Chapter

Introduction

Overview 1.1

Large Case Option 1.3

Page 12: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 13: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Introduction

Overview

The DeSmet C Development Package is a set of programs and fies for developingapplications in the C programming language for the IBM-PC personal computerand its clones. The programs provided in this package require a minimum of l28Kof Random Access Memory (RAM) and at least one disk drive. D88 requires 192K.Most programs wil run under all versions of DOS, 1.xx, 2.xx, and 3.xx. Theprogram execution profier req ires the use of DOS 2.x or later versions.

legend: C=:) Programs

c= Files

The diagram above outlines the interrelationships between some of the programswhich are provided.

Page 14: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Introduction

SEE is a full-screen, command oriented text editor designed for program editingrather than word processing. While SEE can edit any standand ASCII text fie, itsmain purpose is to produce C (.C) and Assembler source fies A). The compilerC88 and the linker BIND can be invoked from SEE.

CLIST reads C source fies (.C) and produces a listing fie with a symbolcross-reference.

C88 is the C compiler. It reads C source fies (.C) ard produces either object fies0) or assembler fies A). It supports the complete Kernighan and Ritchie C

language plus the UNIX V7 extensions strcture assignment and parameter

passing, and enumerated types. C88 supports both the Small and Large Casememory models.

ASM88 is the 8086/8088 assembler. It reads assembler source fies A) andproduces linkable object fies (.0).

BIN is the object fie linker. Itreads object fies (.0) and libra fies S) andproduces an executable fie (.EXE). BIND optionally produces the debuggerinformation fie (.CHK) and overlay fies (.OV). The Large Case memory modellinker is BBIND.

LIB88 is the object fie libraan. It reads object fies (.0) and other library fiesS) and produces libra fies S).

D88 is the C source-level symbolic debugger. It provides access to programvariables by name, breakpoints by function name and line number, and specialsupport for debugging interactive progras. Source code display and stepping bysource lines are also supported.

PROFILE is the C program execution profier. It monitqrs the execution of theapplication progra and indicates where time is spent in the progra.

CSTDIO.S is the Standard Librar used by BIND to provide the Operating Systemand machine-level functions supported by the C language. Two libraes areprovided in the development package, one that support the 8087 math coprocessordirectly (CSTDI07.s) and one that provides numeric support in software(CSTDIO.S). The Large Case memory model libraries are BCSTDIO.S andBCSTDI07.

1.2

Page 15: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Introduction

Large Case Option

The Large Case Option addresses the needs of programs that fit neither the standard'Small Case restrictions (64K of code, 64K of data and stack), the paritioningrequirements of overlays, nor the communication limitations of the exec function.Its features include:

Full1-megabyte addressabilty via 32-bitpointers.

Static varables combined within a single data-segment to speed access.

Large Case differs from Small Case in two aspects: pointers are four bytes long(segment:offset) rather than two bytes (offset), and function calls are inter-segment(segment:offset) instead of intra-segment (offset).

There are stil some memory restrictions with Large Case. No derived data object- ary or strcture - may be larger than 64K. The total size of all static andglobal fundamental objects (char, int, ... ) must be less than 64K. Therestrction on static and global fundamental objects has to do with efficiency-they can be accessed with the same speed as Small Case.

Large Case programs are approximately 15 per-cent larger and slower than theirSmall Case equivalents.

WARNING: LOGIC ERRORS IN PROGRAMSUSING 32-BIT POINTERS MAY BEHAZARDOUS TO YOURCOMPUTER I

Programs using 32.bit pointers can change any byte of memory viapointers. Thus, improperly initialized pointers can change criticalportions of MSDOS, possibly causing corruption of, or damage to yourDISKS.

In addition, corruption of the return address or function address cantransfer control to an arbitrary location in memory, thereby activatingcode that may cause corruption of, or damage to your DISKS. .

1.1

Page 16: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 17: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Chapter 2

Getting Stared

Backing Up

Installng The Software

Installng DC88 Installng DC88 on a Hard DiskInstallng C88 on a Floppy Disk

2.4

Installing the Large Case OptionInstallng Large Case on a Hard DiskInstallng Large Case on a Floppy Disk

A Short Example

Completion Codes

Page 18: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 19: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Backing Up

Getting Started

First things first. Copy all of the fies from the distribution disks on,to a set ofworking floppy diskettes or hard disk. The disks are!1 copy-protected so the DOScopy command can be used to copy the fies. The package is distributed on threeDOS 2 double-sided (360KB) or one DOS 3 quad (1.2MB) diskette.The distributiondiskette(s) should never be used, they should be kept as the backup copy of thepackage.

Installing the Software

The following section assumes you have two drives: a floppy disk (drive A:) and

either a hard disk (drive C:) or another floppy disk (drive B:). The system drive isthe disk your machine "boots" from, either A: or C:. All of the relevant DeSmet Csoftware is in the \DC88 sub-directory on the hard disk, and in the Root Directoryon the floppy disk.

Installng DC88 There is one information and six data fies in the DC88 3.distribution. The fies, and their contents are:

BIN.EXE

ASM88.EXE:BIN.EXE:BUF128.EXE:BUGS!.EXE:C88.EXE:CLIST.EXECOMPAR.EXE:D88.EXE:DUMP.EXE:F ASTSCR.EXEFREE.EXEGEN.EXE:GREP.EXELIB88.EXE:LIF.EXE:LS.EXE11RGE.EXEMORE.EXEPCMAKE.EXEPROFEND.EXE:PROFILE.EXE:PROFSTAR.EXE:RAM.COM:RM.EXESEE.EXE:TOOBJ.EXE

An archive of executable files, containing

The 8088 assembler.The object me linker.128 byte type-ahead buffer program.Arcade game (use 'BUGS! c ' for color displays).The fIrst pass of the C compiler.The C listing and cross-reference utility.The source code comparson utility.The C source-level symbolic debugger.The hex me display utity.Screen output speed-up.

Disk free space displayThe second pass of the C compiler.A me seach utityThe object me libraran.Full screen game of Life.A diectory listig utity

A C source and assembly language merge utilty

A me listig utiityprogr maitenance utity

Used by PROFIE.EXE.The progran execution profiler.Used by PROFILE.EXE.RA Disk drver for DOS 2 and later systems.A me deletion utityThe full-screen edtor.0 to .OBJ converter.

2.1

Page 20: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

GRAPHICS.EXE

GRAPIDCS.NEWGRAPIDCS.DOCGRAPIDCS.CGAGRAPIDCS.HGA

INCLUDE.EXE

ASSERT,CTYPE.DOS.FLOA T.LIMITS,MA TH.HSETJM.StDARG.H 'STDIO.STDLIB.STRNG,

LIB.EXE

C88.LBC887.LIBCSTDIO.CSTDI07.LLINK.BA TSENSE87.TOOLBOXS

OBJ.EXE

c.omCOMP ARE.D88.D88REST.OEXEC.O:EXEC. OBIMSVER1.0SEE.

Getting Started

An archive of text and librar files, containing

New release informationGraphics documentationSmall-case graphics for the CGASmall-case graphics for the Hercules Adaptor

An archive of text files, containing

Diagnostic include fie.

Character handling indude fIe.

DOS function include fie. Floating-point constants include fie.Character and numerical lits include file.Mathematics include file.Non-local jump include file.Varable argument include file.InputJoutputinclude file.General utity include file.Strng handling include file.

An archive of librar fies" containing

Software FIP LINK librar.8087 LINK librar.Software FIP BIND librar.

8087 BIN librar.LINK typical batch fie.8087-sensing upgrades to CSTDIO.Utilty function librar.

An archive of object files, containing

LINK start-off code.Object Code form of comparson utility.Object version of D88 - par Object version of D88 -- part 2.The ExecO and ChaiO functions.Object code for exec () and chain () functions.Object code for DOS 1 I/O functions.Object code of the SEE editor

Page 21: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

SRC.EXE

BUF128.C.ASMCB.C:CLOCK.CCONFIG.DUM.FLIP.ISETU.LATER.C:LIF.PCIO.RUBRBAN.STUB.ASMTDRA W.TGETPUT.TXRAW.

VERSION.DOC

Getting Staed

An archive of source fies, containing

Source code for BUF128.EXE.Source code for runtime stat-up function.

Source code for a brace matchig program.Source code to display clock face.Source code for screen functionsSource code for DUM.EXE.D88 screen Flip source code.Source code for runtime stat-up function.

Source code for a file modification-date utility.Source code for LIF.EXE.INT lOH screen interface source code.Line drawing source code.LIN example source code.Med-res drwing test.Screen ara get/put test.High-res drawing test.

Contains the latest information about the release and itscontents.

If you have the 1.2MB disk format, all the fies wil be on the one disk. If you havethe 360KB disk format, the fies are on the following disks:

Disk #1Disk #2Disk #3

BIN.EXE, INCLUDE.EXE, and VERSION.DOCGRAPHICS.EXE, LIB.EXE, and OBJ.EXESRC.EXE

Each of the archive fies can extract some, or all, of its contents. For example, toextract all of the SRC.EXE archive fie enter

src

To extract, say, just the PCIO.A fie from the SRC.EXE archive, enter

src pcio. a

If the package is to be run on a system other than an IBM PC, XT, AT, PCjr orPC-clone, the screen interface for SEE must be configured before it can be used.See the notes in the fie CONFIG.C in the SRC.EXE archive for details.

Page 22: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Getting Stared

Instal1n DC88 on a Hard Disk.

l. For systems utilzing DOS 2 or later versions of the operating systems,make sure that the ASCII text file CONFIG.SYS exists in the RootDirectory of your system disk (C:). If it doesn t exist, you can create itwith SEE (If you don t know how to use SEE, look at the example in thischapter).

cd \see config. sys

The fie must contain the line:

FILES=20

since DC88 supports 20 open fies - stdin, stdout, stderr, stdaux, stdprtand 15 other fies. The default number of eight is insufficient for theBIND program. If there is enough memory available, add the line:

BUFFERS=20

t9 improve fie performance in the operating system. 512 bytes areallocated for each buffer specified.

If you have a system with more than 256KB of memory, then the Ram Diskdriver RAM.COM cal be used to create an extremely fast disk. To add theRam Disk, extract RAM. COM from the BIN.EXE archive

a :bin ram. com

and add the line

DEVICE=RAM. COM n

to CONFIG.SYS. The parameter is a decimal number between 32 and650, indicating the size of Ram Disk in KB (1024 bytes) increments.

The Ram Disk installs as the next available drve if the highest letterdrive on your system was C:, then the Ram Disk wil install as D:. Use theDOS chkdsk command to verify the drive assignment.

2.4

Page 23: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Getting Started

2. Create a sub-directory (i.e. , \DC88) in the root directory of the hard disk(e.g., C:).

mkdir de88cd de88

3. Unpack the BIN, INCLUDE, LIB and OBJ archives to DC88.

Disk #1 - 1.2MB & 360KB format.

a:bin e88. * gen. * asm88. * bind. * d88. * see.a: inel ude

If you wish to use LINK

a:bin toobj. exe

If you have the 360KB format, insert Disk #2 in drive A:

If you wish to create programs that use .Q hardware FIP

a: lib estdio? sren estdio? s estdio.

else, if you wish to create programs that use .Q software F/P

a: lib estdio. s

else, if you wish to create programs that use either FIP

a: lib estdio. s sense8? sren * . s *lib88 sense8? estdio -oestdiodel estdio. 0del sense8? 0

If you wish to use LINK

a:obj c. obj exec. obj

If you wish to create programs that use.Q hardware FIP

a: lib c88? . lib

else, if you wish to create programs that use only software FIP

a: lib e88. lib

2.5

Page 24: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Getting Stared

Be sure to change the Bind Flags in SEE (using the SET command) toinvoke LINK instead of BIND, or use the LLINK.BA T fileas model for linking.

If you want your library to use only DOS 1 functions

a: obj msverl. 0ren, cstdio. s cstdio. 0lib88 msverl cstdio ocstdiodel cstdio.del msverl. 0

3. If you wish to use the GraphiCs Package, print the manual and text

a: graphics graphics. doc graphics. newcopy graphics. * prndel graphics. *

If you have a Color Graphics Adaptor (CGA), extract its library

a: graphics graph cs. cgaren graphics. cga libg. s

If you have a Hercules Adaptor (HGA), extract its library

a: graphics graphics. hgaren graphics. hga libg. s

4. If you have a machine other than an IBM or c1osec1one copy.

a:obj see. o d88. o d88rest. o compare.

If you have the 360KB format, insert Disk #3.

If your machine emmulates the IBM ROM BIOS interrpt 10H, then

recreate SEE, D88, & COMPARE

a:src pcio.asm88 pciobind see pcio -osee bind d88 d88rest pcio -od88bind compare pcio -ocompare

Page 25: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Getting Started

otherwise modify CONFIG.C for your particular display, then recreateSEE, D88, & COMPAR

a: src config. cedit config.c88 configbind see config -oseebind da8 d88rest config -od88bind compare config -ocompare

Delete see . 0, d88 . 0, d88rest . 0, and. compare. o.

5. Modify AUTOEXEC.BAT to specify the location of DC88 componentsand include fies. see \autoexec. bat

The DC88 components are specified in the pATH environment varable.Add the c:\dc88 sub-directory to the existing PATH specification, orcreate a PATH specification. See your DOS manual for information onspecifying the PATH variable.

The DC88 include files are specified in either tbe DSINC or theINCLUDE environment variable. Add either the set DSINC=c:\dc88\or the set INCLUDE=c:\dc88\ line to the AUTOEXEC.BAT fie. See

Chapter 4 - The C88 C Compiler for more information on thespecifying the search path for DC88 include fies.

6. Re-boot the system.

Insta1ln!! DC88 on a FIopnv Dlsk

1. Create a System Disk on drive B:

format b:

copy format. com b:

2. Put the System Disk in drive A: and DC88 Disk #1 in drive B: For systems

utilzing DOS 2 or later versions of the operating systems, create the ASCIItext fie CONFIG.SYS in the Root Directory of your system disk ( A:).You can create it with SEE (If you don t know how to use SEE, look at the

example in this chapter).

b: see config. sys

Page 26: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

tting Stared

The fie 11 contain the line:

FILES=20

since DC88 supports 20 open fies stdin, stdout, stderr, stdaux, stdprtand 15 other fies. The default number of eight -is insufficient for theBIND program. If there is enough memory available, add the line:

BUFFERS=20

to improve fie performance in the operating system. 512 bytes areallocated for each buffer specified.

If you have a system with more than 256KB of memory, then the Ram Diskdriver RAM.COM can be used to create an extremely fast disk. To add theRam Disk, extract RAM.COM from the BIN.EXE archive

b:bin ram . com

and add the line

DEVICE=RAM. COM'

to CONFIG.SYS. The parameter is ad-ecimal number between 32 and650, indicating the size Of Ram Disk in KB (1024 bytes) increments.

The Ram Disk installs as the next available drive if the highest letterdrive on your system was B: , then the Ram Disk wil install as C:. Use theDOS chkdsk command to verify the drive assignment.

2. Unpack the BIN, INCLUDE, LIB and OBJ archives to the system disk.

Disk #1 - 1.2MB & 360KB format.

b:bin c88. * gen. * asm88. * bind. * d88. * see.

b: include

If you wishto use LINK

b:bin toobj . exe

If you have the 360KB format, insert Disk #2 in drive B:

Page 27: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Getting Started

If you wish to create programs that use hardware FIP

b: lib cstdio7. sren cstdio7. s cstdio. s

else, if you wish to create programs that use software FIP

b: lib cstdio. s

else, if you wish to create programs that use either PIP

b: lib cstdio. ssense87 . ren * . s *lib88 sense87 cstdio -ocstdiodel cstdio.del sense87. 0

If you wish to use LIN

b:obj c. obj exec. obj

If you wish to create programs that use only hardware FIP

b: lib c887. lib

else, if you wish to create programs that use only software FIP

b:lib c88. lib

Be sure to change the Bind Flags in SEE (using the SET command) toinvoke LINK instead of BIND, or use the LLINK.BA T fie as modelfor linking.

If you want your librar to use only DOS 1 functions

b:obj msverl.ren cstdio. s cstdio. 0lib88 msverl cstdio -ocstdiodel cstdio. 0del msverl.

3. If you wish to use the Graphics Package; print the manual and text

b: graphics graphics. doc graphics. newcopy graphics. * prndel graphics. *

Page 28: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Getting Started

If you have a Color Graphics Adaptor (CGA), extract its library

b: graphics graphics. cgaren graphics. cga libg. s

If you have a Hercules Adaptor (HGA), extract its library

b: graphics graphics. hgaren graphics. hga libg. s

4. If you have a machine other than an IBM or':Close clone copy.

b: obj see. 0 d88. od88rest. 0 compare.

If you have the 360KB format, insert Disk #3.

If your machine emmulates the IBM ROM BIOS interrpt 10H, thenrecreate SEE, D88, & COMPARE

b:src pcio.asm88 pciobind see pcio -oseebind d88 d88rest pcio -od88bind compare pcio -ocompare

otherwise modify CONFIG.C for your paricular display, then recreate

SEE, D88, & COMPARE

b: src config. cedi t config . c .c88 configbind see config -oseebind d88 d88rest config -od88bind compare config -ocompare

Delete see. 0 , d88 . 0, d88rest. 0, and compare. o.

5. Re-boot the system.

Installng the Large Case Option

The Large Case Option is distributed on a single 5 1/4 inch floppy diskettes,containing:

B88.LB:B887.LIB:BBIN.EXE:

Large Case DOS LINK C Librar (non-8087)Large Case DOS LINK C Librar (80Large Case Binder.

2.10

Page 29: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

BC.ASMBC.OBIBCSTDIO.BCSTDI07.BEXEC.BEXEC.OBJBGRAPHIC.CGABGRAPHIC.HGABLLINK.BATBSTUB.ASM

Getting Started

Large Case DOS LINK star-up source codeLage Case DOS LINK start-up object codeLarge Case C Librar (non-8087)Large Case C Librar (8087)

Large Case exec () and chain () functions.Large Case DOS LINK exec () and chain () functions.Lage-case graphics for the CGALage-case graphics for the Hercules AdaptorLarge Case OOS LINLage Case OOS LIK MASM example

InstaHinQ' LarQ'e Case on a Hard Disk

Place the Large Case Option disk in drive A:

copy a: exe c:\dc88

If you have a SOS7 coprocessor

otherwise

copy a :bcstdio7. s c: \dc88\bcstdio. s

If you are using LINK

copy a:bcstdio. s c:\dc88

copy a: * . obj c: \dc88

If you have a SOS7 coprocessor

otherwise

copy a :bc887 . lib c: \dc88\bc88 . lib

copy a :bc88 . lib c: \dc88

Be sure to change the Bind Flags in SEE (using the SET command) to invokeBBIND or LINK instead of BIND, or use the BLLINK.BA T file as model forlinking.

If you are using the Graphics Package with a Color Graphics Adaptor

otherwise

copy a:bgraphic. cga c: \dc88\blibg. s

copy a:bgraphic. hga c:\dc88\blibg.

Page 30: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Getting Started

Installn Lar e Case on a F10ppv Disk

Place the Large Case Option disk in drive B: and the DCS8 System Disk in drive A:and copy the following files:

copy b: * . exe

If you have a SOS7 coprocessor

:'

copy b :bcstdio7. s bcstdio. s

otherwisecopy b: bcstdio. s

If you are using LINK

copy b: * . ob j a:

If you have a 80S7 coprocessor

copy b :bc887 . lib bc88. lib

otherwise

copy b :bc88 . lib

Be sure to change the Bind Flags in SEE (using the SET command) to invokeBBIND or LINK instead of BIND, or use the BLLINK.BAT fie as model for

linking.

If you are using the Graphics Package with a Color Graphics Adaptor

copy b: bgraphic . cga blibg. s

otherwise

copy b: bgraphic . hga blibg. s

2.12

Page 31: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Getting Started

A Short Example

This example shows the general method for creating executable programs with thispackage. It assumes that the disk in the default drive, in this case drive containsthe compiler (C88.EXE and GEN.EXE), the assembler (ASM88.EXE), the binder(BlND.EXE), the standard librar (CSTDIO.S) and the text editor (SEE.EXE).The source code wil reside on drive B:.

Enter the example program with the SEE text-editor. To star the SEE text editor

type:

see b : example.

The screen wil look as follows:

Again Buffer Copy Delete Find -find Get Insert Jump -space-_m reading file: b:example.c...--new fie 0 characters

Figure 2-

SeeTM Initial Screen

2.13

Page 32: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Getting Started

Other than the header, footer, and this sentence this page is intentionally blank.

2.14

Page 33: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Getting Stared

Type the letter T, or press the ' Ins' key, to put the editor into Insert mode. Now

type in the following progra:

main ( ) et.::Tab::print.f("%d plus %d is %d\n , 2, 2, 2+2);.aet.::Tab::l Ret.::Esc::

Note that the items ",Tab:;, ",ReD, and ",Esc:; indicate the Tab, Return, and Esckeys, respectively. The ",Esc:; wil termitiate insert mode and return the editor tocommand mode. The screen should now appear as follows:

Again Buffer Copy Delete Find -find Get Insert Jump -space-

mainOIprlntf(%d plus %d is %(1\", 2, 2, 2+2);

Figure 2-

Progra Display

To compile the program just entered, type the sequence of charcters, 'Q' for Quitand 'C' for Compile. This wil sta C88 using the fie in memory. The computerwil display:

Page 34: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Gettig Staed

Compiling;..

mainO!prinjf(%d plus %d Is %d\n , 2, 2, 2+2);

,'"

Figure 2-

Compilig from SEE

The message "Compilng ..." replaces the firt line of the display. If there errors durig the compilation, the error message wil appear on the second line ofthe display, and the cursor wil be on the error line. You can correct the error andrecompile. If there are no errors BIN wil be invoked. The screen appears asfollows:

Binding ...

malnO!printf(%d plus o/od Is %cI\n , 2, 2, 2-1);

Figure 2-

Binding from SEE

Page 35: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Getting Stared

If there are any eITors, they wil be displayed on the message line. To run theprogram, press esc to escape from the Quit menu and press the F9 key toinvoke a new DOS shell. At the prompt, enter

b:example

to invoke the progra. The screen wil look somethg like:

Again Buffer Copy Delete Find -find Get Insert Jump -space-

maln()(prlntf(%d plus %d Is %d\n , 2, 2, 2+2);

DOS Ver 3.0 Copyright ......A:ob:example2 plus 2 Is 4

Figue 2-Executig example Progra

To return to SEE type

exit

at the DOS propmpt. You wil be returned to the SEE display.

If you wish to save the fie to disk, tye 'Q' (Quit) followed by an S' (Save-exit).The fie wil be saved, and control wil be returned to DOS.

2.17

Page 36: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Getting Staed

Completion Codes

The C88, ASM88, BIN and LIB88 progras set the completion code to:

if no wargs or eITors occulTed,if warngs were issued, andif errors occulTed.

Batch fies can tae advantage of these values, to. stop execution or otherwise handlethese exceptiona cases.

The batch fie CC.BAT listed below wil stop ifC88 or BIN reports an error:

eBB %lif errorlevelbind %lif errorlevel

: stop

1 goto stop

1 goto stop

More complicated development situations can be handled with the program LA TEPwhich is supplied in source form in the fie LATER.C. LATER taes a list offienames as arguments. It sets the eITorlevel to one if the last fie does not exist orif the last fie has an earlier modification date than any other fie in the list. It canonly be used on systems with a batery backup clock or where users are carefulabout settig the date and tie when the system is brought up. Assume a progra iscomposed of the fies moda.c, modb.c, modc.c and the include fie mod.h. Thefollowing .BA T fie can be used to regenerate the progra whenever a modulechanges:

later moda. e mod. h moda.if errorlevel 1 eBB modaif errorlevel 19oto stoplater modb. e mod. h modb.if errorlevel 1 eB8 modbif error level 1 goto stoplater mode. e mod. h mode.if errorlevel 1 e8B modeif errorlevel 19o'to stoplater moda. o modb. o mode. o mod. exeif errorlevel 1 bind moda modb mode:stop

-omod

Ths provides a service simlar to the UN MAK program. Only those fies thatneed to be compiled wil be compiled.

Page 37: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Chapter 3

The SEE Text Editor

Introduction

Getting StaredConc ptsStaring the EditorInserting and Editing Text 3.4Saving the FileEditing Existing Files

The Invocation Line

The KeyboardCursor Movement KeysEditing KeysThe DOS Key

CommandsAgainBufferCopyDeleteFindFind

GetInsertJumpListMacroOtherPutQuitReplaceSetTag 3.30Version/ViewWrapXchange

Page 38: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Commands (cont.)

non 3.31

Configuration 3.31

Page 39: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

Introduction

SEE is a general purpose full-screen text editor designed for program entry ratherthan word processing. It features:

invoking the compiler (C88) and the binder (BIND) from the editor errors return control to the editor at the error lineinvoking a copy of the shell (COMMAND.COM) to provide access toDOS functions,handling fies hu"ger than available memory,editing two fies simultaeously,viewing the two fies either on separate screens, or in two windows onthe :)ame screen,

. a macro facilty which allows you to capture a series of keystrokes andreplay them to ease repetitive tasks,automatic indentationbracelbracket/parenthesis matching to ease program entry,

SEE is shipped confgured for the IBM-PC and its clones. SEE may bereconfigured to run on other machines which support DOS but have differentkeyboard and/or screen interfaces than the IBM-PC (see Section 3.6).

:1.

Page 40: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

Getting Stared

Concepts

SEE does not directly manipulate a fie on the disk. It brings a copy of the fie intomemory and performs all work on this internal copy. The fie on the disk is notmodified until the copy in memory is stored on the disk. If the fie is larger than theinternal buffer area, SEE wil open "spil" fies to swap the edited text in and out ofmemory. For this reason, you should not have anyliles named SEETMP.

###

where ### is a series of three digits (currently restricted to 000, 001 , 002, 003, and004).

Commands are executed by typing the first letter of the command displayed on themenu line (the first line on the screen). For example, to execute the Deletecommand, simply type the letter ' ; the case of the letter does not matter.

Whenever a of text is deletep with the Delete command, the text is placed in aspecial area known as the copy buffer. Blocks seiected with the Buffer commandare also placed in this buffer. When the Copy command is used, the contents of thisbuffer is inserted into the text at the cursor location. The copy buffer is maintainedas long as the editor is running and is shared by both fies (if two fies are beingedited). This is the mechanism used to move text from one location to another orfrom one fie to another.

The cursor indicates the location where all action wil occur. It wil be in one ofthee states: a double-bar cursor indicating command mode, a single-bar cursorindicating Insert mode or a block cursor indicating Exchange mode. The cursor isalways visible on the screen. As the cursor is moved to an edge of the screen, the screen wil scroll the text to keep the cursor in view, both vertically andhorizontaly. For example, if the cursor is moved down when it is on the last line ofthe screen, the screen wil be scrolled up one line to show. the line the cursor is on.

. Similarly, when the cursor is in the rightmost column of the screen and the cursor ismoved to the right (assuming the line has more charcters not currently displayedon the screen), the screen wil be scrolled to the left by 15 columns to show the newlocation.

3.2

Page 41: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

Starting the Editor

To start the editor to edit a new fie named ' ergo , simply type:

see ergo

and the computer should respond with the screen:

Again Buffer Copy Delete Find -find Gel Insert Jump --space------- reeding me: ergo ... -- new me 0 characters

The top line on the display is the menu line . This line displays the current mode ofthe editor and the commands available at any given time. In this first screen, themenu line contains the fIrst set of commands available at the command level:

Again Buffer Copy Delete Find -find Get Insert Jump space--

Hitting the space bar displays the second set of commands:

List Macro Other Put Quit Replace Set Tag Wrap Xchange --space--

Hitting the space bar again wil redisplay the fIrst set of commands. The commandsare fully described in Section 3.5 of ths manual. Each command may be executedby typing the first letter of its menu item; for example, A for Again, B for Bufferetc. The case of the command letter is ll importt.

The second line of the screen is used to display messages and status from the varouscommands and is naturally called the message line . The message "ergo... -- new

3.3

Page 42: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

fie 0 characters" indicates that the fie ergo has not been found and that the internalfie buffer is empty.

Inserting and Editing Text

To ,insert text into the fie, we must enter Insert mode. Do this by either typing theletter 'I to execute the insert command, or by pressj g the Ins key. The screenshould now look as follows:

Insert: (cursor keys) , Esc to eXil , Ins for Exchange----- reading f1e: ergo.. -- new f1e 0 characters

Note that the menu line has changed to indicate the types of actions, other thaninserting text, that may be performed. Any charcter now tYped, except for one ofthe special keys described in Section 4, wil now be inseI1ed into the text at thecursor location, just prior to the character that the cursor is on.

Now type in the lines:

These are a few lines -:Returnof example text to shoe-:Backspace w-:Returnthe editing capabilties of the SEE editor. -:Return-:Ese:

3.4

Page 43: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

The screen should now look as follows:

AgaIn Buffer Copy Delete FInd -find Get Insert Jump --space--

These are a few lInesof example text to showthe edIting capabilitIes of the SEE editor.

Note that the symbols .:Retu1l, .:Backspace;:, and .:Esc;: represent the use of thereturn, backspace, tab, and Esc keys, respectively. The .:Return;: inserts acarage-return, line-feed (CRLF) s quence into the fie to begin a new line and thecursor moves down one line and to the left side of the screen. The .:Backspace;: keydeletes the charcter preceding the cursor. The .:Tab;: key inserts a tab characterinto the fie which is expanded to the next tab stop. Tab stops, by default, are locatedevery four charcters, however this value may be changed in the Set command. The.:Esc;: key breaks the editor out of Insert mode and places it back in commandmode. The cursor keys are used to move the cursor around the screen in small increments.Press the up-arow key twice to move the cursor up to the beginning of the' second,line. Press the right-arow key thee times to move the cursor to the beginning ofthe word 'example . Type the letter 'I to put the editor into Insert mode and typethe word 'some ' without the quotes and add a blank. Note that as each character istyped, the rest of the line is "pushed" to the right. The screen should now look asfollows:

3.5

Page 44: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

Insert: (cursor keys) , Esc to exIt , Ins for Exchange

These are a few linesof some xample text to showthe edit I ng capab111 t1 es of the SEE editor,

. '

Now hold down the control key (Ctrl) and press the right-arow key thee times.Note that the cursor jumps from one word to the next when using this combinationof keys. See Section 4 for full detals on all of the special keys. Also note that theeditor does not have to be in command mode to use the cursor movement keys. Nowhit the Ins key to change from Insert mode to Exchange mode; the menu line wil'display Exchange instead of Insert. In Exchange mode, the charcter at the cursor isoverwritten by the new charcter rather than having the charcter inserted into thefie. The only exception to this rule is when the cursor -is positioned at the end of aline, characters are inserted rather than overwriting the CRLF end-of-linesequence. Exchange mode can also be entered from command mode by typing theletter 'X' for Xchange. Type the word 'display' and notice how the word 'show ' isoverwritten with the new word 'display . Press the Esc key to go back to commandmode. The screen should now look as follows:

- .

Page 45: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

Agoln Buffer Copy Delete Find -fjnd Get Insert Jump --spoce--

These ore 0 few .l1nesof some exomple text to dlsploy-the ed1l1ng copob1l11es of the SEE edllor.

Press the Home key and note the location of th cursor. To delete this line, invokethe Delete command by typing the letter ' , move the cursor down one line withthe down-arow key, and type the letter ' D' again to complete the deletion (the Esckey wil also work). The second line has been deleted and placed in the copy buffer.Now type the letter 'C' to invoke the Copy command to retrieve the text that wasdeleted. Type the letter 'C' agai and a second copy of the line is inserted. The copybuffer always contains the last Deleted or Buffered block of text. The screen shouldnow look as follows:

Agoln Buffer Copy Delete Find -find Get Insert Jump --spoce--

These ore 0 few I1nes

Cf some exomple text to dlsployof some exomple text to dlsploythe editing copob11111esof the SEE edllor.

Page 46: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

To find the first occurrence of the word ' display ; press the letter 'F' to invoke theFind command. Type in the word 'display ' (without the quotes) and press either Escor Return to begin the searh. The cursor should now be positioned after the worddisplay' on the second line. To replace the next occurrence of the word ' displaywith the word 'show , press the letter 'R' to invoke the Replace command. Noticethat the previous search string 'display ' now appears on the message line. Since thisis the string to be replaced, simply press the Esc or Return key to select the string(rather than retyping the string). Type in the strng ' show and hit the Esc or Returney to execute the command. Press the Home key twice to move the cursor to the

top of the screen. The screen should now appear as follows:

Again Buffer Copy Delete Find -find Get Insert Jump --space-

lhese are 8 few lfnesof some example text to displayof some example text to showthe editing capabfltles of the SEE editor.

Another useful feature in SEE is its abilty to record a ser es of keystrokes,command, cursor keys, etc., and replay them on command. These recordings are'called macros. To create a macro, type 'M' to invoke the Macro command, typeR' to indicate that a recording is to be made, and select the function key (F1 throughF8) that is to be used to invoke the macro. In ths example, press the F1 key. Themessage line now displays the line:

recording, Macro FI, use Macro key to complete recording

This, message wil be displayed after every command to indicate that a macrorecording is in progress. Now, any commands or special keys typed wil be

Page 47: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

, ,

The SEETM Text Editor

recorded into the macro until the Macro command is executed once again: For thisexample, execute the following commands:

Esc control right-arrow

Macro F1 is now defined to insert the '(g' charcter in front of each word. , Toexecute the macro, press the F1 key. To execute the macro a fixed number of times,say five times, type the number 5 and then the function key Fl. The macro isexecuted five times. To execute the macro for the rest of the words in the fie, typein a large number or use the more convenient I' character to indicate the number32767, the largest number. Type 'I' and press the F1 key. The screen should nowappear as follows:

Again Buffer Copy Delete Find -fjnd Get Insert Jump --space--

(!These (!are (!a '(! few l1nesof (!some example text (!to' (!'display

(!of (!some (!examp1e text (!to (!showthe editing capabi1iies (!of (!the (!SEE (!edi tor.

Saving the File

Recall that all of the editing was performed on the fie in memory. This copy of thefie must be written out to the disk. Type the letter 'Q' to enter the Quit menu. Thechoices under the Quit menu are:

BAKup Compile Exit Initialize Save-exit Update Write

Each menu item is explained in detail in Section 5 under the Quit command. Pressthe letter S' to save the memory copy of the fie to the disk fie named 'ergo whichwas entered at the beginning of this example. This selection wil also terminate theeditor.

Page 48: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEE-r Text Editor

Editing Existing Files

Now to edit the fie ergo again, simply type the line:

see ergo

The editor wil be loaded and wil attempt to load dje fie ergo. If the fie wasloaded correctly, the screen should appear as follows:

Ag61n BUffer Copy Delele Find -find Gellnserl Jump----- re6d1 ng f1 e: ergo ... 156 ch6r6clers

These 6re few l1nesof some ex6mple lexl lo dlspl6Yof some ex6mple lexl lo showlhe ed1l1ng c6pob11l1es of lhe SEE edllor.

sp6ce--

Type 'Q' to select the Quit command and then type 'E' to 'exit from the editorwithout writing the fie out, since nothing 'has changed.

You now have a basic understanding of how to edit fies with the ' SEE editor.Practice editing other fies using the skils developed in this example. Don t beafraid to experiment. Remember that as long as you don t write the fie back out tothe disk, the old copy is safe. When you are comfortable with these editing features,look though the rest of the manual to see what else can be done and experiment withsome new features.

Page 49: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

The Invocation Line

There are a few different options available when starting the SEE editor. InvokingSEE with the command line:

see

wil bring up the editor with an empty buffer and no fiename specified. To save thefie to disk, use the Write option under the Quit command 'described in Section 5.

Invoking SEE with the command line:

see fi1ena.e

wil have the editor load the fie dilename:: if it exists. -cfiename:: wil be used bythe Update and BAKup options in the Quit command. If the fie doesn t exist, SEEwil act as if it existed but was a zero length file. Note that the fie is not createduntil it is written out to disk.

Invoking the editor with the command line:

see fi1ena.e1 fi1ename2

wil have the editor load the text from -cfienameb but wil write out the text todilename2::. -cfienameb wil not be altered by the edit session.

Adding the -1 option to the command line:

see fi1ena.e -lnnnn

wil have the editor load the text from -cfiename b and start editing at line nnnn .

The -1 option works with either fiename configuration.

Page 50: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

The Keyboard

This , section describes the special keys used, by the SEE editor as defined for theIBM-PC keyboard. If the editor has been reconfigured for a differe t keyboard,you wil have to map the reconfigured keys to the IBM-PC keys to understand thefollowing documentation.

Cursor Movement Keys

..-

In the following descriptions, the caret (") preceding the name of the key indicatesthat the control (Ctrl) key must be held down while the key is pressed.

Home:

"Home:

End:

"End:

PgUp:

"PgUp:

PgDn:

"PgDn:

UpArrow:

When the Home key is pressed once, the cursor wil move to thebeginning of the current line (the line that the cursor is currently on).If the Home key is pressed twice in succession, the cursor wil moveto the beginning of the first line on the screen.

When the control key is held down as the Home key is pressed, thecursor wil be moved to the peginning of the first line of the fie.

When the End key is pressed once, the cursor wil move to the end ofthe current line (positioned just before the CRLF end of linesequence). If the End key is pressed twice in succession, the cursorwil move to the begi ing of the last line on the screen.

With the control key helddown, the End key wil move the cursor the end of the fie.

Moves up twenty lines of text and redisplays the screen.

Scrolls the screen up one line without moving the cursor.

Moves down twenty lines of text and redisplays the screen.

Scrolls the screen down one line without moving the cursor.

The up-arow key moves the cursor up one line. The column that thecursor is in remains the same. If the cursor is positioned beyond theend of a line because of ths action, the visible cursor is shown beyondthe end of the line but is logically located just before the CRLF

3.12

Page 51: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

sequence (The cursor is moved tp this location when some other, operation is performed.) If the cursor is already on the top line of the

screen, the screen is scrolled down one line to show the new line.

DownArrow: The down-arow key moves the cursor down one line. Again, thevisible cursor remains in the same column as described above. If thecursor is already on the last line of the screen, the screen is scrolledup one line to show the new line.

The left-arow key moves the cursor one character to the left. ' If thecursor is at the left edge of the screen, and the screen has beenscrolled to the right, the screen wil scroll back to the left by 15character locations to show the new cursor position. If the screen hadnot been scrolled implying that the cursor was on the first characterof the line, the cursor moves to the end of the previous line.

LeftArrow:

"LeftArrow:

RightArrow:

With the control key held down, the cursor wil move to the left inword increments rather an character ihcrements. Each time thiscombination is pressed, the cursor wil move to the first character ofthe previous word where word is defined as a sequence of letters ordigits. Any other character separates the words.

The right-arrow key moves the cursor one character to the right. If

the cursor is at the right edge of the screen and more text exists in thecurrent line, the screen is scrolled to the right by 15 characters toshow the new location. If the cursor was positioned at the end of theline, then the cursor is moved to the beginnng of the next line.

"RightArrow:This combination moves the cursor to the beginning of the next word.

Return:

Editing Keys

Backspace:

The return key is normally used to insert a CRLF end of line sequence, into the text, thereby positioning the cursor at the beginnng of thenextline If the return key is pressed while in command mode, the

cursor wil simply move to the beginning of the next line.

The backspace key deletes the character to the left of the cursor. the cursor is positioned at the beginning of a line, the CRLF sequenceis removed and the two lines are joined to form a single line.

3.13

Page 52: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Del:

Ins:

FI-FS:

FlO:

The SEETM Text Editor

The delete key deletes the character atthe cursor. If the cursor ispositioned on the CRLF end of line sequence, then the next line isjoined with the current line.

The Ins key is used to toggle between Insert and Ex.change modes. the command level, it wil place the editor into Insert mode.

The function keys F1 thoughFS are ay_ailable for user-definedmacros. Macros may be saved with the Macro-Save command.

If you are using a split-screen to display two fies concurrently, theFIO key wil temporarily expand, the current fie display to fil theentire screen. Switching to the other fie wil reset to the split-screen.

IIC or IIBreak:Holding down the control (Ctrl) key and hitting the letter 'e' or theBreak key (Scroll Lock) wil normally stop the execution of acommand (where reasonable). Ths is useful when you decide not toexecute the Find command and are in the middle of typing in thesearch string. Typing control-C wil abort the Find commandwithout modifying the old search string. This key combination wilalso stop an executing macro.

liRe turn: Delet s from the cursor to the end of the line. This command may beused to edit the command line (e.g., Find, Replace, Initialize).

The :qOS Key

Under MS-DOS 2.0 and later versions of the operating system, the F9 function keyallows another command shell to be executed while the editor and text remain inmemory. When the F9 key is pressed, the screen Wil display the DOS copyrightmessage and wil prompt for a command. You can execute any command, evenanother copy of the editor (although this is 11 recommended because of conflctswith the spil fies). When you want to return to the editor, type the DQS command

exit

and the text wil be redisplayed as if the F9 key never had been pressed. DOS, SEEand your text occupy about 12SK. You must have at least an additional 64K unused memory in your machine to use the DOS feature.

Page 53: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Edjtor

Commands

In command mode, the menu line displays the commands available for editing andmanipulating the text. Since the names of the commands are too long for a singlemenu line, the menu is broken into two parts. To toggle between each part of thecommand menu, press the space bar.

Aglin Buff.r' Cop." D.l.t. Find -find G.t Insert Jump -- c.--

cr'o Oth.r' Put Quit R.pl c. S.t T g Xchang. -- c.--

Command Menus

To invoke a command, type the first letter of the command. To terminate acommand, press the escape c:Esc key. A command may be aborted by holdingdown the control key, Ctrl, and typing the letter C (control-C).

Many commands wil tae a repetition count to execute the command multiple timesbefore completing. The repetition count takes the form of a decimal number or aslash (indicating a very large number). It is entered prior to typing the first letter ofthe command. Some commands - Find

, -

fmd, and Replace - may be given aquestion mark (7) repetition count indicating that the editor should prompt aftereach strng is found. Note that at the command level, the cursor movement keysmay also be repeated by using a repetition count. This also means that if a mistake ismade in the repetition count, the Backspace key canot be used to correct themistake. The command must be aborted.

In the following descriptions of the commands, c:rep indicates that the commandtaes a repetition count and c:rep I 7 indicates that it wil take a repetition count orquestion mark repetition count.

Commands that need furter information (Le. , Find) interact with the user on thesecond line of the display the message line. . Each command that interacts on the 'message line displays the current value of the information sought. You can use thecurrent value by pressing c:RETURN , or you can use all the editing facilities ofSEE to edit the current value before pressing "RETURN

Page 54: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

oerep Again

The Again command repeats the action of the last Find

, -

find, or replace commandwithout any prompting. For example, if a Find command is executed to locate thestring "hello , then executing the Again command wil find the next occurrence ofthe string "hello

Buffer

The Buffer command is used to copy a block of text into the copy buffer. The copybuffer is an internal buffer used to hold the last buffered or deleted (with the Deletecommand) item. To use the Buffer command, move the cursor to the beginning ofthe block to be buffered and type 'B' for Buffer. The charcter at the cursor wil betemporarily overwritten with a block to indicate the beginning of the block. Themenu line wil be replaced with the new menu line:

Buffer: cursor keys esc I B Again Find - find Jump

Now move the cursor to the end of the block, either with the cursor movement keysor with the Again, Find

, -

fmd and Jump commands. These commands may bepreceded with a repetition count. When the cursor is positioned at the end of theblock, press the Esc key or the letter 'B' to terminate the buffering operation. SEEwil copy the contents of the block into its copy buffer. The previous contents of thecopy buffer are thrown away.

oerep Copy

The copy command insert the contents of the copy buffer at the current cursorlocation. If a repetition count is given, the contents of the buffer wil be insertedthat many times.

Delete

The delete command is used to delete a block of text. The deleted text is placed inthe copy buffer, as mentioned in the Buffer command. To use the Delete commandfirst move the cursor to the beginning of the block of text to be deleted and type 'for Delete. The character under the cursor wil be temporarily overwritten with a

Page 55: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

block to indicate the beginning of the block. The menu line wil be replaced with thenew menu line:

Delete: cursor keys esc I D Again Find -find Jump

Now move the cursor to the end of the block, either with the cursor movement keysor with the Again, Find, -find, and Jump commands. These commands may bepreceded with a repetition count. When the cursor is positioned at the end of theblock, press the Esckey or the letter 'D' to delete the block. The text wil beremoved and placed in the copy buffer.

.:rep I ?:; Finq

The find command is used to locate the next occurrence of a given string. Thesearch runs from the cursor location to the end of the fie. To use the Findcommand, type the letter 'F for Find. The Find command wil then prompt for thesearch strng. The last string given in a Find, -find, List, or Replace command isdisplayed on the message line. If the same strg is to be found, hit the Esc orReturn key to select the argument. Otherwise, edit the message line to create thenew search strng. When the strg is entered, press the backquote or Return key toindicate completion. The Find command wil then search for the next matchingstring. If found, the cursor wil be moved to the character following the strng,otherwise the message:

can t find " string

wil be displayed and the cursor wil not move. -cstring:; is the search string. If arepetition count is given, the strg wil be located that many times before thecommand is done. For example, typing the command stream:

3 F hello -cReturn:;

wil place the cursor after the third occurrence of the string "hello . If a questionmark (1) is given as the repetition count, the editor wil move the cursor to the nextoccurrence of the string and prompt with the message:

continue? (y/n)

Typing the letter 'Y' wil move the cursor to the next occurrence of the searchstring. Any other charcter wil stop the Find command.

Page 56: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

.(rep I? finq

The -find command works similarly to the Find command except that the text issearched backwards from the cursor to the beginning of the fie. When the -findcommand terminates, the cursor is left on the character prior to the located string.The question mark repetition count works as in the Find command.

Get

The Get command is used to insert the contents of a fie into the current fie. Thetext from the fie is inserted at the cursor location. To use the Get command,position the cursor at the insertion point and type the letter ' . The Get commandwil prompt for a fiename. Enter the fiename and type -cReturn . The Getcommand wil prompt with

reading from -Cfilename

...

and attempt to read and insert the text from the fie. If everythng goes well, the 'word "completed" wil be added to the prompt. If an error occurs (usually meaningthat the fie does not exist), the words "can t read fie" wil be appended to theprompt. Finally, if the buffer was filled as a result of the Get command, the wordsbuffer filled" wil be appended to the prompt indicating that only par of the fiewas inserted.

Insert

The Insert command is used to place the editor into insen mode. Once in insertmode, characters other than the command charcters wil be inserted in the text atthe cursor location. The cursor movement charcters always move the cursorappropriately. The Insert command does not normally do anything with therepetition count. However, if the I' repetition character is specified, then a newlinecharacter is inserted at the cursor location before entering insert mode. If the Inskey is pressed, the mode wil be changed to Exchange mode. To terminate the insertmode, type the Esc character.

o:rep:: Jump

The Jump command is used to move to a location previously marked withthe Tagcommand or for moving to a line when given a line number. When a repetition

Page 57: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

count is given, the cursor wil be moved to the beginning of the corresponding line(the line number given by the repetition count). Otherwise, the Jump command wiIdisplay the menu:

Jump:

indicating the four tag names to use. If one of these letters is typed, the cursor wilbe moved to the location associated with the tag. Ths location is set with the Tagcommand. If the tag has not been set, the cursor wil mOve to the end of the fie.

c(rep:: List

The List command is used to display all lines containing the given string. The Listcommand prompts for the search strng the same way as the Find command. Oncethe search strng has been entered, the List command temporaly takes over thescreen and displays all lines, beginning from the cursor location, which contain thesearch strng. A line wil be listed once, even if it contains multiple instances of thesearch string. After the screen is filed with lines, the prompt wil read:

hit a key to continue

Any key other than control-C wil display the next set of lines. If there are no morelines with matching strngs, the screen reverts to its normal display with the cursorpositioned after the last matching strg. If no repetition count is given, alloccurences are assumed. Qtherwise, the repetition count wil control the number oftimes the List command wil search for the string.

Macro

The Macro command is used to record input from the keyboard and the mouse.This recording can then be played back to perform the same sequence of operationsbeginning at another point in the text. Thus macros give the abilty of creatingcustom functions built from the standard set of operations. There are eightdefinable macro keys, F1 though F8. When one of these function keys is pressedthe macro associated with the key is replayed. Note that macro keys and the Macrocommand Qi be recorded.

Page 58: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

When the Macro command is invoked, the menu:

Macro: Delete Load Record Save

wil appear with the following meanings:

Delete: used to delete a macro definition. Delete prompts with the menu line:

select function key: F1 ,- Fa

When a function key is selected, the macro associated with the keywil be removed. Typing the Ese key wil exit the command withoutdeleting any macro.

Load: used to reload the macros and controls settings from the "see.macfie. This fie is created by the Save command.

Record: used to star the macro recording. Record prompts for the macronumber with the menu:

select function key: Fl - Fa

When the function key is selected, the old macro associated with thatkey, if any, is deleted and a new recording is begun. All input wil berecorded as par of the macro. To tenninate the recording, reinvokethe Macro command by typing the letter ' . Now when thecommand key is held down and the number is typed, therecordingwil be replayed as if the inputs were coming from the keyboard.

Save: used to save the macro definitions and control settings (see the Setcommand) into the fie named "see.mac" in the current directory.This fie is read, if it exists in the current directory, when the editor isfirst invoked and when the Load command is used. If the fie does notexist in the current directory, then each directory in the PATH systemparameter is searched.

For example, the following sequence of commands wil create macro Fl which canbe used to delete the current line:

M R Home down-arrow D M

Now when the Fl key is typed, the line that the cursor is on wil be deleted.

Page 59: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

Other

The Other command is used to toggle between the two fies available for editing.The first time the Other command is used, it wil prompt for a command line as inthe Quit-Initialize command. Subsequent uses of the Other command wil changethe active fie from one to the other. If the F10 key had been used to temporarilyexpand a split-screen display to use the entire screen, use of the Other command wilreset the display to the split-screen configuration.

The Put command is used to write a block of text out to a separate fie. To use thePut command, move the cursor to the beginning of the block to be written and type'the letter ' . The charcter under the cursor wil be temporarly overwritten witha block character to indicate the beginning of the block. The menu line wil bereplaced with the new menu line:

Put: cursor keys esc I Again Find -find Jump

Now move the cursor to the end of the block, either with the cursor keys or with theAgain, Find

, -

find, and Jump commands. These commands may be preceded with arepetition count. When the cursor is positioned at the end of the block, pressEsc orthe letter 'P' to select the end of the block. The Put command wil then prompt for afiename. Enter the fiename and type -cReturn::; the block of text wil be written to

The Quit command is used to terminate an editing session. When the letter 'Q' istyped, the Quit command wil display the menu:

Quit: BAKup Compile Exit Initialize Save-exit Update Write

and wil show the name of the fie, an indication if the memory buffer has beenmodified, and the size of the fie, on the message line. To leave the Quit menuwithout executing any commands, type the Esc charcter. The menu items have thefollowing meanings:

BAKup: causes SEE to change the extension of the old fie to .BAK and thenwrite the contents of the memory buffer to the fiename given onthe invocation line. If a new fie is being edited, no .BAK fie iscreated.

Page 60: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

Compile: causes the SEE editor to invoke the C88 compiler using the C88Flags from the SET menu. The message compilng is displayed onthe message line. If an errors occurs, the error message is displayedon the message line, and SEE resumes editing the fie at the errorline. If no error occurs, SEE wil invoke BIND using the BIND Flagfrom the SET menu. The message binding is displayed on themessage line. If an error occurs, th error message is displayed onthe message line.

The fie is not saved prior to the compilation.

Ex it: causes the SEE editor to exit back to the system. If the memorycopy of the fie has been modifed, SEE wil prompt with thequestion:

ignore changes? (y/n)

Typing ' ' wil leave the editor and tle changes made to thememory image of the fie wil be lost. Any other character wilabort the Exit command.

Ini tialize: causes the SEE editor to reinitializethe editor and prompt for a newinvocation line (excluding the SEE progra name). If the text has'been modified and not saved, SEE wil prompt as if Exit had beenselected, giving one last chance to save the changes to the fie. Thenew fie is then read in and the editor is restarted. Note that themacros and the copy buffer are left intact and can be used with thenew fie.

Save-exi t: writes out the fie to the disk and exits from the editor withoutfurter prompting.

Update: writes a copy of the memory buffer out to the fie given on the ,invocation line. This command is useful for quickly, saving thecontents of the memory buffer out to the disk to prevent a large lossof data if a fatal error should occur (either software or hardware).

Wr it e: writes a copy of the text toa specified fie. The Write commandwil prompt for fiename and wil then write the text to that fie.Ths command is usually used when no fiename was given on theinvocation line.

Page 61: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

-(rep I ?-; Replace

The Replace command is used to locate a specific string of characters and replace itwith another string. Replace uses the same search string specified in the Find, -findand List commands. To replace a strng, type the letter 'R' and enter the search string (or just type Return if the current search strng is correct). Then enter thereplacement strng and type ocRetum::. The editor wil find the !1 occurrence ofthe search strng and replace it with the replacement strng. If the search stringcannot be found, the following message wil be displayed:

cannot find "Csearch string;:"

The repetition count controls the number of times the replacement wil beperformed. To replace all occurrences, move the cursor to the beginning of the fieand use /, for the repetition count. If the question mark (1) is given as the repetitioncount, then before the string is replaced, the editor wil prompt with:

replace? (y/n) or quit

(q)

Typing the letter 'Y' wil replace the strng and the cursor wil move to the nextoccurrence of the search strig. Typing the letter 'N' wil simply move the cursorto the next occurrence of the search strng. And typing the letter 'Q' wil abort theReplace command.

Set

The Set command is used to change severnl controls in SEE; tab width, indentationcase sensitivity on search strngs and a special auto-insert mode. The values of thecontrols may be saved with the Macro Save command so that the settings wil be thesame each time the editor i& invoked. The Set command wil display one of twomenus: Set :Auto-ins (off) Case (no) Flags Height (0) Indent (yes) PC -space-

Set:Right(80) SpilleD) Tabs (8) Word-wrap (off) ' -indent(2) -space-

The current settings of the controls are displayed in parentheses. To change acontrol , pick its menu item and follow the prompts. The controls are defined asfollows:

Page 62: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

Auto-ins: This control forces the editor into insert mode after each command.To execute a single command, type the Esc key to temporarilyterminate the insert mode and bring up the command menu. Selecta command as u:;ual. After the command executes, SEE wilautomatically place itself back in Insert mode. Selecting this menuitem wil display one of the following two messages, depending onthe state of the control:

if the Auto- insert control is off (default)

Set auto-insert mode? (y/n)

otherwise

Reset auto-insert mode? (y/n)

Typing 'Y' wil change the control from one state to the other.Anything else wil leave it alone.

Case: This control is used while searching for strings in the Find, -find,List, and Replace commands. When the control is on, the case of thesearch strng and the text is ignored during the string comparison,so the strng "AbC" is equal to the strng "aBc . When this controlis off, the case of the characters in the strng must match exactly.Depending on the state of the case-ignore flag, one of the followingmessages wil be displayed when ths menu item is selected:

if the case-ignore control is on (default)

Make case significant on searches? (y/n)

otherwise

Ignore case of searches? (y/n)

Typing 'Y' wil change the state of the control.

Flags: This control specifies ' the command line for invoking the compiler(C88) and the linker (BIND). The cho,ices for this menu are:

Set Flags: Bind caa

Page 63: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

The Bind option displays the line that wil be use to invoke BIND.The default is:

BIND %0

BIND is the name of the linker. %0 contains the name of the fiebeing edited. Edit the flag to add any BIND options you wish.

If you are compilng several modules, set the Bind Flag to a NULLstrng (use "RETURN, so that BIND is not called for each module.Then, use the F9 key to invoke DOS and BIND the fies mantially.

The C88 Flag displays the line that wil be use to invoke C88. Thedefault is:

caa %0

c88 is the name of the compiler. %0 contains the name of the fiebeing edited. Edit the flag to add any C88 options you wish.

Height: Ths control controls how two fies are displayed on the screen.The submenu is:

enter second screen height (0, a. . 17)

If 0 is entered, the second fie is shown alone on its own screen.Using the Other command flps the display between the twodisplays. This is the default height.

If a number between 8 and 17 is entered both fies are displayed

together. A dashed line separtes the two areas. The height of thesecond area is the number of lines entered.

Indent: Ths control indic:ates whether the blans and tabs from theprevious line are copied to the begining of the the new line when aReturn is inserted. When this control is on, the indentation iscopied. This provides an aligned left margin to the indented text.When this control is off, no indentation is copied when a Return isentered and the cursor moves to the left edge of the screen.Depending on the state of the Indent control, selecting the Indentmenu item wil result in one of the following messages:

Page 64: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

if the Indent control is on (default)

Reset auto-indent mode? (y/n)

otherwise

Set auto-insert mode? (y/n)

Typing 'Y' wil change the state of ,the control.

pc: This menu item selects the IBM-PC specific information. Thesesettings may be v31id for other direct clones but it is not guaranteed.The following menu wil be displayed:

Set PC:Add- Z Cursor-height Foreground-color Background-color

Add- Controls whether a DOS 1.0 EOF charcter(ClZ, OxlA) is appended to the end of thefie. Selecting ths menu wil display one of thefollowing two messages, depending upon thestate of the control:

If the IIZ control is off (default)

add control-Z at the end of files? (y/n)

otherwise

stop adding control-Z? (y/n)

Typing 'Y' wil change the state of the control.

Cursor-height: Sets the height, in pixels, of the charcter cellsize. By enabling this control, the cursor wilchange shapes according to the mode that theeditor is in; a double bar for command mode, asingle bar forinsert mode and a block for

. exchange mode. Enter

disable this featurecolor graphics adaptermonochrome adapter.

Page 65: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

\ ,

The SEETM Text Editor

Foreground-color: Sets the foreground color attribute. The colorsare defined by the IBM-PC as follows:

blackblue,greencyan,redmagenta,brownlight grey,dark grey,light blue,light greenlight cyan,light red,light magenta,yellowwhite.

Background-color: Sets the background color attribute. Thebackground colors for the IBM-PC are definedas follows:

black,blue,greencyan,redmagentabrownlight grey.

Values above 7 cause the characters to blink.

Right: This control sets the character column for the Wrap command andthe automatic word-wrap mode. Words which extend beyond thiscolumn are moved to the next line. The following message isdisplayed:

enter wrap right column:

Page 66: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

Enter a number between 0 and 255. An invalid specification issignaled with

bad wrap width (0 256)

Spil: This control determines the drive on which the editor s spil fieswil be created. A ' (g' indicates the current default drive. Thefollowing message wil be displayed:

enter spill device letter:' (A-Z, 0 for default)

Type a single letter to signify which drive to use or the ' 0' characterto indicate the use of tIe current default drive.

If spil fies have already been opened, they wil be moved to thenew drive (the contents of the copy buffer wil also be deleted).This is useful if the original spil disk becomes full and another diskis available.

Tabs: This control determines the expansion factor of tab characters in thetext. The following message wil be displayed:

select tab size (1. . 19)

By default, this value is 4. However, if the fie on the invocationline has an extension which sta with the letter A' (as in xxx.a),then the tab size wil be set to eight; a useful size when writing inassembly language. If the extension stas with the letter 'C', thenthe tab size is set to four. Otherwise the tab size remains at itscurrent setting. The tab size may be a value from one to nineteenindicating that the tab stop locations wil be separated by one tonineteen character locations, respectively

Word-wrap: When this control is on, the editor wil automatically move words tothe next line if the current column is greater than the right columnSelecting ths menu wil display one of the following two messages,depending upon the state of the control:

If the "Z control is off (default)

set word-wrap mode? (y/n)

Page 67: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEE Text Editor

otherwise

reset word-wrap mode? (y/n)

Typing 'Y' wil change the state of the control.

'f- indent: This is a special indentation mode for assisting in C programming.The following mesaage wil be displayed:

enter indent mode (0, 1, 2)

An error is signaled by

bad indent mode

When this control is on and the Indent control is on, the editor wilautomatically add an extra tab charcter to the indentation when a-:Retum is inserted just after the left brace (-0 character. Thereare two possibilties for -:Return s which follow the right brace n)charcter. If mode 1 is selected and a tab character preceded theright brace character, it wil be removed and the indent levelreduced accordingly. This corresponds to the following type ofindentation:

main () .

int i;for (i = 1; i 10; i++)

printf ("hello, world\n

If mode 2 is selected, then the indentation of the new line isdecreased by a tab if the Return was inserted just after the right-brace 0 ) charcter. This corresponds to the following type ofindentation:

main () int i;for (i = 1; i 10; i++)

printf ("hello, world\n

Page 68: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor,

Tag

The Tag command is used to set markers in the text fie. Once a tag is set, themarked character can be located with the Jump command regardless of theinsertions and deletions around the marked character (unless the marked characteris deieted). The Tag command displays the menu:

Tag: C D

where , A, B, C, and D correspond to the four tags available. To use the Tagcommand, move the cursor to th character to be marked and type 'T' . Now selectone of the tag names by typing the corresponding letter.

Version/View

When the cursor is at the begining of the fie, this command displays the SEEversion number on the second line of the display. With the cursor at any otherlocation in the fie, it redisplays the current screen with the line containing thecursor at the third line of the display.

Wrap

The Wrap command is used to reformat a pargraph. All of the lines, starting withthe line that the cursor is currently on to the next blan line, are reformatted tomake sure no word extends beyond the right margin (set by the Right-col control).Indentation for the lines is determined by the indentation of the first line of theparagraph. The Wrap command requires a confirmation to avoid wrapping code bymistake. The letter 'W' may also be used to confinn the Wrap operation.

Xchange

This mode is similar to Insert mode except that charcters in the text areoverwritten by the new charcters. The only characters not overwritten areReturns. An attempt to overwrite a Return simply insert the character prior to theReturn. If the Ins key is pressed while in Exchange mode, the mode wil be changedto Insert mode.

Page 69: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The SEETM Text Editor

Finally, there are a few single charcter commands which are not listed on the menuline but may be of use:

The number sign (#) command displays the current line number on the messageline.

When the cursor is on a left brace 'f, left parenthesis '(' or left bracket '( and oneof these command characters is typed, the cursor wil be moved forward to thecorresponding right brace T, right parenthesis ' )', or right bracket T. If.thecursor is on a right charcter ' )" it wil move backward to the corresponding leftcharacter '

-((,

('. Note that this command, does not know about comments sounmatched charcters wil confuse the search routine.

4(rep:; \

The backs lash command is used to insert literal characters into the text by enteringtheir decimal equivalents. When backs lash is typed; the editor wil prompt for adecimal value. Numbers from 0 to 255 are valid but 254 and 255 have specialmeaning to SEE. The repetition count determines the number of times thecommand wil prompt for input.

Configuration

Distributed with the package, are a number of fies used to reconfigure the editor torun on other DOS based machines with different keyboards and/or screens:

SEE.PCIO.CONFIG.

relocatable object fie

source code for an IBM-PC BIOS based interface.source code for terminal based screen interfaces. Containsinterfaces for ANSI terminals , a Hazeltine 1500, Dee VT-and the Zenith ZIOO.

Page 70: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The' SEETM Text Editor

The PCIO.A and CONFIG.C fies should contain enough information in thecomments to build your own interface if necessar.

To build the editor, compile/assemble one of the interface fies, or one of your ownmaking, and link it with the editor with the following bind command:

bind see config

This wil generate a new SEE.EXE fie with your interfaces linked in instead of thestandard IBM-PC interfaces.

' '

Page 71: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Chapter 4

The C88 C Compiler

Introduction

InvocationExamples 4.3

The C LanguageEnvironment

Character Set

Trigraph SequencesLanguage

KeywordsIdentifiersFloating constantsInteger constantsCharacter constantsStrng constants

Hardware data typesEnumerated typeFunction prototyping

PreprocessorConditional compilationSource fie inclusion

Macro replacementLine controlErrorPragmaNullPredefined macros

ExtensionsAsmCase range

RestrictionsForward referencesExterns

4.44.4

4.54.5

Large Case Option

Page 72: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 73: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

Introduction

C88 is the C compiler for the 8088/8086 family of microprocessors. It accepts C

source programs as input and produces object fies. The compiler supports both theSmall memory model which effciently utilzes the 8088/8086 architecture butlimits a program to 64KB code and 64KB of data, and the Large Memory Modelwhich is limited only by the amount of available memory.

Invocation

C88 -(fiename). (options)

-(fiename). is the name of the fie contaning the C source. If it does not includean extension, the extension ' C' is assumed.

You may use a hyphen, , to enter the source from the predefinedfie stdin. The fie must be a disk fie, compilng from thekeyboard is not supported. You can redirect the input

c88 - -(filename

or you can use a pipe

yourpgm I c88 -

Options: The case of the option is not significant. Each option should beseparated from other options by blanks. Options may be precededwith the dash (-) character.

A - assembly output. Ths option indicates that the compiler shouldproduce an assembly language source fie instead of an objectfie. The name of the assembly language fie wil be the same asthe name of the source file but wil have the extension '

B - big. This option instructs the compiler to produce Large CaseMemory Model output. You need the Large Case Option (notincluded with the DeSmet C Development Package) to use thisoption.

C - produce check information. This option causes the compiler togenerate information for BIND to create the .CHK fie used bythe debugger and pro fier.

Page 74: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

D.:name:: - compiler drive specification. The compiler assumesthat the fies GEN.EXE and ASM88.EXE are in the d faultdirectory on the current drive. This option is used to inform thecompiler that the files are On a different drive. For example, if

, the compiler is on drive ' , then the option 'DM' is needed. '

Under MS-DOS 2.0 and Mer versions of the operating system,this option is rarely needed as the system PATH variable is alsoused to find the other passes of the compiler.

E - run the preprocessor and output the result to the predefined fiestdout. All macros and include fies are resolved.

I.:name:: - include path name. This option overrdes the defaultdrivel directory for fies included with the #include control. Thedirectory name must end with a trailng backslash (\) character(e.

g. -

ic: \src\include\). See the Preprocessor section for#include details.

M This option is used to produce Intel object fies rather than thestandard .0 object fie format. To work properly, the fieTOOBJ.EXE must be in a directory in the PATH.

N.:defname::=.:defvalue:: - specify #definename and value.Used to set debugging switches or constant values withoutediting the fie. This option is equivalent to

#define defname defvalue

at the beginning of th program. To . t .:defname:: to 1, enter

n.:defname:: , which is equivalent to

#define defname 1

Spaces are not allowed.

O.:fiename;: :' output fiename. The compiler wil produce anobject file with the specified' name. If the name lacks anextension, the extension ' 0' wil be added. The default objectname is the same as the source name with the extension of '

Page 75: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

Pc:switch:: - sets the indicated pragma swit& on. The switchesare:

T - requests that ANSI trgraph sequences be processsed.

W - requests the display of all waring messages. Strctureassignment, structure arguments, and prototype conversionwaring messages are not normally displayed.

X -requests that the extended keywords be recognized. Use thisswitch when you use the #asm featUre to embed assemblerinto your C program.

T c:drive:: This option specifies the drive that the compiler shoulduse for its temporar fies. If not specified, the compiler wilbuild its temporary fies on the default drive. If this drive isclose to being full, the 'T' option should be used to change thedrive for the compiler work fies. Also, if the RAM Disk hasbeen installed, placing the temporary fies there wil drasticallycut the time needed to compile a program.

Examples

C88 blip

compiles the fie named blip.c. The object fie wil be named blip.

C88 blip b

compiles the fie named blip.c using the Large Case Option. The object fiewil be named blip.o. You must use BBIND to link this program.

m:C88 b:blip. ccc tm dm

runs the compiler from drive M on the file b:blip.ccc. Temporary fies arealso written on drive M. Note the use of the D option to indicate the location ofthe other passes of the compiler. The object fie wil also be named blip.

c88 blip pwx

compiles blip.c in the current directory. Strcture assignment, structureargument, and prototype coersion warnings are reported. The extendedkeywords are recognized.

4.3

Page 76: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

The C Language

DC88 compiles C programs that conform to the definition of the C language asdescribed in the Draft Proposed American National Standard for InformationSystems Programming Language C.

ENVIRONMENT

Character Set

DC88 recognizes the following characters:

letters the 52 upper-case and lower-case letters of the English alphabetand the underscore ( a- z, A-Z,

digits the ten decimal digits ( 0- 9 J

white-space the space, horizontal tab, vertical tab, form feed, cariagereturn, and line feed characters. Comments, sequences ofcharacters begun with a / * sequence and ending with a * /sequence, are equivalent to a space character. Comments do notnest.

others the following 28 graphics charcters

' ( , .: ; ? (

J A

In addition, any of the 255 characters in a byte (excluding ,0) are valid in a stringconstant.

Trigraph sequences

When trigraph processing is enabled (through the -pt command line switch or the#pragma trigraph option), the following sequences of three characters arereplaced with the corresponding single character.

??= ??) ??! ?? (

??/ -4 \

??.: ??' ??). ??-

4.4

Page 77: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

LANGUAGE

Keywords

The DC88 C Compiler

The following tokens are reserved as keywords of the language. A * indicates anextended keyword (enabled though the -px command line switch or the #pragmaextended option).

* asmautobreakcase

* cdeclcharconstcontinuedefault

Identifers

doubleelseenumextern

* farfloatfor

* fortrangoto

* huge

int* interrupt

long* near* pascal

registerreturnshortsigned

sizeofst;aticstructswitchtypedefunionunsignedvoidvolatile

, while

An identifier is a sequence ofletters (which include the underscore) and digits. Thefirst character must be a letter or an underscore. Only the first 31 characters aresignificant. Corresponding lower-case and upper-case letters are different.

Floating constants

A floating constant has a value par, followed by an optional exponent part,followed by an optional suffix that specifies its type. The value par consists of anoptional digit sequence representing the whole-number par, followed by a period

), followed by a digit sequence representing the fraction part. The exponent partconsists of either an e or an E , followed by an optionally signed digit sequence.Either the whole-number par or the fraction part must be present; either the periodor the exponent part must be present.

The digit sequences are interpreted as decimal integers. The exponent indicates thepower of 10 by which the value par is to be scaled.

An unsuffixed floating constat has type double. If suffixed by the letter f or F , ithas type float. If suffixed by the letter lor L, it has type double.

Page 78: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Integer constants

The DC88 C Compiler

A)1 integer constant begins with a digit, but has no period or exponent part. Itmayhave a prefix that specifies its base and a suffix that specifies its type.

A decimal constant begins with a nonzero digit and consists of a sequence of decimaldigits. An octal constant consists of the prefix 0 optionally followed by a sequence

of the digits 0 though 7 only. A hexadecimal constant consists of the prefix Ox orOX followed by a sequence of decimal digits and the letters a (or A) though f (or with values 10 through 15 respectively. ;

An unsuffixed integer constant has type int or long depending on its size. Ifsuffixed by the letter u or U, ithas type uns igned. If suffixed by the letter 1 or L,

it has type long:

Character constants

A character constant is a sequence of one or more characters enclosed in single-quotes, as in I x ' or ' ab ' . The characters can be any of the 255 byte values,excluding O. The single-quote " the double-quote " , the question-mark?, thebackslash \, and arbitrar integer values, are representable according to thefollowing table of escape sequences.

\ I Ox2C single-quote

\ ?

Ox3F question-mark?\000 1 to 3 digit octal value\a Ox07 alarm\f OxOC formfeed\r. OxOD carriage return\ v OxOB vertical tab

String Constants

\"

Ox22 double-quote

\ \

Ox5C backslash \\xhhh 1 to 3 digit hexadecimal value\b Ox08, backspace\n OxOA linefeed\t OxOg. horizontal tab

A string constant is a sequence of zero or more characters enclosed in double-quotes, as in "xyz . Each character in the sequence is treated as if it were in acharacter constant, except that the single-quote ' can be represented either by itself

or the escape sequence \ ' . The double-quote " must be represented by the escapesequence \ " .

Page 79: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

The maximum size for a source fie string constant is 255 bytes. Larger object fiestring constants can be constrcted by concatenating source fie strng constants, asin:

char xyz ( J

which is equivalent to

= "

aaaaaaaaaaaabbbbbbbbbbbb"cccccccccccc

" ;

char xyz (J = " aaaaaaaaaaaabbbbbbbbbbbbcccccccccccc

" ;

Hardware data types

DC88 Typechar

8088 TypeBYTE

int WORD

short

uns igned WORD

long DWORD

float DWORD

double QWORD

(pointer) WORD

DWORD

DescriptionUnsigned byte with a range of 0 to 255.

Signed integer with a range of -32768 to 32767.

Unsigned integer with a range of 0 to 65535.

Signed integer with a range of -2147483648 to2147483647.

Four byte IEEE floating point value. A float has

about 7 digits of precision and has a range of about1.E-36 to1.E+36. Eight byte IEEE floating point value. A doublehas about 13 digits of precision and a range of about1.E-303 to 1.E+303.

In the Small Case Memory Model, pointers are twobytes, limiting total data space to 64KB.In the Large Case Memory Model, pointers are fourbytes.

To take advantage of the 8088/8086 instrction set, expressions involving only chartypes are not coerced to int before evaluation. The sum of a char equal to 255 and achar equal to 1 is 0 rather than 256. Constants are considered to be int values so thatconstant plus char is a two byte integer operation.

Page 80: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

Enumerated type

Enumerated type provides a convenient method of declaring an ordered set ofnamed constants. Values star with zero, and may be reassigned with a name val ueexpression. The same value may be assigned to several names. For example

enum color ired, blue=4, g,reen) ca, * cp;enum color cb;if (ca == red)

cb = *cp = green;

is equivalent to

#define#define#defineint ca,int cb;

red blue green 5

cp;

if (ca == red)cb = *cp = green;

Function prototyping

Both the type of value returned by a function, and the type(s) of the arguments to thefunctiQn may be specified. To specify the type of each argument to a function, place

the types of the argument, separated by commas, between the parentheses in thefunction declaration. For example to indicate that a function taes a double:

double sqrt (double) ;

If you call sqrt (1) , the integer 1 wil be converted to a double. If you want toknow when these conversions are made, use the -pw command line option, orspecify #pragma warning in your program.

To indicate that a function takes no arguments, specify:

void abort (void) ;

To indicate that an unknown number of arguments, of unknown type, are valid,specify:

int printf (char *

.. . ) ;

Page 81: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

int xxx

();

is equivalent to int xxx

( . . . ) ;

You can also define functions using the prototypical style, as in

int main (int argc, char * argv())

Only prototypically declared functions are checked for possible argumentconversions.

PREPROCESSOR

Before any interpretation of source fie text is stared, all occurrences of abackslash-newline sequences are deleted. Thus you can break text anywhere forcosmetic purposes without changing its meaning, as in

# de f i \

ne Fa\a 10\

which is equivalent to #define FaQ 1024

A preprocessing directive consists of a sequence of preprocessing tokens begun by a# character that is the first character of a line (following optional whitespacecharacters), and ended by a linefeed character.

Conditional compilation

#if expr, #elif expr, #ifdef id, #ifndef id, #else, #endif

#if and #elif evaluate expr. expr must be a constant expression, but may notcontain a s i z e 0 f operator, a cast, or an enumeration constant. expr may contain aunar expression of the form

defined identifer

de fin e d identifer

which evauates to 1 if identifier is currently defined as a macro name, 0 otherwise.All constants are evaluated as long.

Page 82: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

#ifdef and #ifndef are equivalent to #if defined id and #if ! definedi d, respectively.

If the test evaluates to 0, the source code up to the next #elif, #else, or #endifis skipped. If the next directive is #elif, its expr is evaluated. If it is #else, thefollowing source code, up to the terminating #endif, is passed to the compiler. IfIt is #endif , the conditional compilation is complete.

If the test evaluates to non-zero, the source code up to the next #el if, #else, or#endif is passed to the compiler. Then the remaining source code, up to theterminating #endif , is skipped.

Conditional compilation groups can be nested.

Source fie inclusion

#include name

Includes other fies into the program. #include s can be nested to a maximum depthof20.

#include " filename " wil search the default directory for the file filename

#include ":filename? wil first search the default directory for filename . Ifthe file was not found; the environment (see the DOS SET command) is searched forthe key DSINC. If DSINC is not found, the environment is searched for the keyINCLUDE. If INCLUDE is not found, a "cannot open include fie" error isgenerated. The DSINC key is used in case you have other applications that also usethe key INCLUDE.

If the key is found, it should contain a set of directory prefixes separated bysemi-colons and terminated with a backslash ( \). For ex ple, if DS INC is set asfollows

C;:set DSINC=c: \; c: \usr\include\

then the line #include ":world. h;: would cause C88 to search for

world. hc:\world.c: \usr\include\world.

# in c 1 u de name behaves like the previous two examples, where name is a macrothat expands into one of the two forms.

4.10

Page 83: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

Macro replacement

#define name replacement defines an object-like macro that causes eachsubsequent instance of name to be replaced with replacement.

#define name (parameters) replacement defines a function-like macrothat causes each subsequent instance of name followed by a ( to be treated as aninvocation of the macro. When defining the macro, the ( must immediately followname. When using the macrQ, the ( may be separated from name by whitespace.

Each argument specified in the macro call is expanded ana used to fil in the parameter placeholder specified in replacement.

If a parameter placeholder in replacement is immediately preceeded by a #, thenboth are replaced by a string constant that contains the unexpanded spellng of theparameter. Leading and trailng white space of parameter is deleted. Thebackslash \ and double-quote " characters are escaped with a backs lash character.

If a parameter placeholder is immediately preceeded or followed by a # #, then the# # operator is deleted and the preceeding and following tokens are concatenated.The unexpanded form of the parameter placeholder is used. The # # operator canbe first or last in replacement.

Line control

line digits resets the line number of the next source line to digits.

#line digits string resets the line number of the next source line to digits

and the name of the source fie to string. string must be a string constant.

#line name behaves as the preceedingtwo forms, where name expands to one ofthe two forms.

Error

terror text produces text as a diagnostic message.

Pragma

Pragma directives consist of a name and an action. The bold portion of the name inthe following specifications shows the minmum amount of the name that must bespecified. The action can be + to turn the switch ON, - to turn the switch OFF, ! toinvert the switch, and = to reset to the default state. No action turns the switch ON.

4.11

Page 84: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

#pragma trigraphs controls trigraph processing. Default is OFF.

#pragma t+

#pragma warn ing controls whether structure assignment, strcture argument,and prototype argument type conversions are reported. Default is OFF.

#pragma warn -

#piagma extended cO:ntrols whether the extended.- keywords, including #asmare recognized; Default is OFF.

' '

#pragma extended =

Null

A # on a line by itself is ignored.

Predefined macros

All predefined macros begin with two underscore characters' I , except for the

LARGE CASE macro (which is retained for compatiblity with previous releases).

LINE is the number of the current source line (can be reset with # 1 ine).

FILE is the name of the source fie (can be reset with # 1 ine).

DATE is the current date in the form "Mmm dd yyyy

TIME is the current time in the form " hh: mm: s s

" '

STDC " 1" = Standard-conforming implementation

, "

0" otherwise

DESMET identifies this compiler

LARGE CASELARGE indicates the Large-Case option was selected.

SMALL indicates the Large-Case option was n.ot selected

4.12

Page 85: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

EXTENSIONS

Asm

A #asm directive has been included to allow in-line assembly language code for timecritical applications. All lines following a line staring with #asm are passedthrough to the assembler. A line consisting of the " #' character ends the in-lineassembly code. Object-like macros (without arguments) as well as arguments andvariables local to the function can be referenced by prepending a # to the name.Global variables are accessed by name with an ' ' appended. Be sure to specifyoperand size (BYTE, WORD

, ...

). Extended keywords must be enabled (px).

#pragma ex+

#define eOMl Ox3B4

int Xi

zip (int count,int Y

#asmMOV

MOV

MOV

char * src, char *tar)

ex, #count countSI, #src srcDI, #tar idst

mov WORD #y, #eOMlmov WORD X - ' #eOMl

Case range

As an alternative to coding

case ' case ' b' : case ' c ' : case ' d' : case ' e

' :

you can specify

case ' a '

.. '

Extended keywords (px) must be on.

Page 86: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

RESTRICTIONS

Forward references

C88 is effectively a one pass 90mpner so forward referenc s wil not work. Thefollowing program:

main 0 i=99;

extern int

wil produce a warning that ' i' is undefined and is assumed to be a local variablenamed' . The global variable ' i' wil not be changed.

Structure tags must be defined before being referenced. The only exception ispointers, so that legal structure declarations include structures of the form:

struct a tstruct b *

struct b tstruct a *

Externs

A declaration that includes the keyword 'extern ' may not include initializers anddoes not allocate any memory. Thus a variable so declared must be declaredsomewhere else without the 'extern' keyword in order to reserve memory for thevariable. For example, if a fie contains the declaration extern int blip, thensome other fie must contain the declaration int blip to actually allocate storage.If this is not done, the binder wil complain about a reference to the unresolvedsymbol blip. It is permissible to have both an 'extern and non- extern' declarationin a single fie. For example

extern int blip;int blip;

is valid.

Page 87: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

To create include fies containing data declarations include the declaration:

extern int blip;

add the declaration:

int blip;

to one of the fies to actually allocate the storage. If the varable needs initializationinitialize the value in the one file:

int blip = 1985;

Large Case Option

With most programs, just compile with the -b switch on, and link using BBIND.Remember that all the object fies must have been compiled or assembled with theb switch.

Most of the difficulty in converting to Large Case is in the area of pointers. InSmall Case, pointers and int s are the same size if you don t declare a functionto return a pointer there is no har done. The default int return of the function isthe same size as a pointer.

In Large Case, however, pointers are four bytes and ints are two bytes long. Youwil get an error message if you try to assign an int or an uns igned to a pointeror vice versa.

The macro names LARGE and LARGE CASE wil be tre (defined) when theoption has been sp ecified the command line. You can test for this condition

using #ifdef or #ifndef

#if defined#define#define#define

#else#define

LARGEstdin stdout 1Lstderr 2L

stdin 0

#endif

4.15

Page 88: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The DC88 C Compiler

The things to watch out for are:

functions returning pointers must be declared before use.

fopen () now returns a pointer, and must be declared before being called.

FILE * fopen () ; 1* Assumes STDIO.H included

The pointer is used by fclose (), fgetc (), fgets

() ,

fprintf 0, fputc (), fputs (), .;read (), fscanf () ,fseek (), fwrite (), getc (), getw (), putc (), putw

ungetc () ;

open () stil returns, and the other I/O functions stil use, an into Notethat this means that fclose () and close () are not interchangeable.

This should make these functions more portable to other C environments;

Large Case arid Small Case object fies canot be linked together.

A long can be assigned to a pointer, and vice versa.

malloc () is slow as it calls DOS. This was done to leave as much space aspossible free for calls to exec () .

The C88 Compiler supports both small and large case compilations. To compile alarge case program, use the b switch, as

c88 blip -b

The hyphen is optional.

There are a few new Large Case Option error messages:

ilegal indirection something other than a pointer has been used as apointer.

ilegal index a pointer cannot be used as an aray index

ilegal assignment only a pointer, long, or constant can be assigned to apointer. Note: this is a pass 2 error the -c (checkoutoption) must be used to get the line number of theerror.

4.16

Page 89: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Chapter 5

The ASM88 Assembler

Introduction

Invocation

Examples

Lage Case ASM88 5.3

Page 90: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 91: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The ASM88 Assembler

Introduction

ASM88 is the 8088/8086 assembler. It reads assembly language source fies and

, produces linable object fies. The assembly language is described in appendix B:

Invocation

ASM88 fienae:; ( options)

fiename:; is the name of the. assembly language source fie. If it does not includean extension the extension ' A' is assumed.

Options: The case of the option is not significant. Each option should beseparted from other options by blans. Options may be preceded withthe dash (-) charcter.

The assembler creates Large Case (big) memory model objectfies. You need the Lage Case Option (not included with theDeSmet C Development Package) to use this option.

L( flename:; ) - The assembler wil produce a listig from theassembly language input 'Ts listig includes the hex-valuesgenerated by the' assembler as well as line numbers andpagintion. If no nae is specified, then the name of thesource file with the extension ' L' is used. If the specified fiedoes not have an extension

, '

L' wil be used. Otherwise the

listing is written to the specified fie. To generate a listing onthe printer, use ' LPRN:

The assembler wil produce an object fie with the Intelformats rather than the stadard .0 format. The fieTOOBJ.EXE from the DOS LIN package must be in thesae dirctory as the GEN.EXE and ASM88.EXE fies. Youneed the DOS LIN Option (not included with the DeSmet CDevelopment Package) to use ths option.

flename:; - The assembler wil produce an object fie with thespecified name. If the name lacks an extension, then theextension ' 0' wil be appended to the name. The defaultobject fie name is the name of the source fie with theextension changed to '

5.1

Page 92: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The ASM88 Assembler

T c:drive;: - The 'T option specifies the drive where the assemblertemporar fies wil be created. If a RAM Disk is available,redirecting tempora fies to that drive wil greatly speeddevelopment. The assembler normally creates its temporarfies on the default drive/directory.

PnD Specifies page length, in lines. The default is 66.

Specifies page width, in charcters, for the list fie. The valuenn must be a number from 60 to 132. The default is 80.

Won

Examples

asm88 blip

. assembles the fie naed blip.a and produces a Small Case memory modelobject fie named blip.

asm88 blip b

, assembles the fie named blip.a and produces a Large Case memory modelobject fie named blip.

M:asm88 blip. asm -Ob:blip Lblip. lstruns the assembler from drive M: on the fie naed blip.asm. The output is anobject fie naed blip.o on drive B: and a listing fie named blip.lst on thedefault drive.

asm88 blip. a TM -oa:blip. o -lb:blip. lst assembles the fie named blip.a. Tempora fies are created on drive M:. Theoutput of the assembler is placed on drive A: in the fie blip.o. A listing fie isgenerated and written to drive B: in the fie blip.lst

Page 93: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The ASM88 Assembler

Large Case ASM88

ASM88 also support large and small case assembly. To assemble a large caseprogra, use the b switch as

asm88 blip -b

The hyphen is optional:

In addition to the stadard CSEG (Code Segment) and DSEG (Data Segment) directives, there is a ESEG (Extr Segment) directive. CSEG and ESEG can be anysize, while DSEG is restrcted to 64K. CSEG is addressed with

CS, DSEG with DS,and ESEG with either DS or ES. The Stack is a separte segment whose default sizeis 8K (chageable using the -8 option ofBBIN). The Stack is addressed by SS.

The long call and return, LCALL and LRT, are normally used instead of CALL'and RET. You can mix the short and long forms of call/return in a program, but besure that each form of return is matched to the corresponding form of call.

The DD directive creates a long (4 byte) pointer

label DD zip, zap

See Chapter 10 for the Large Case memory model layout.

All Assembly Language fuctions must preserve BP and DS.

There are two new prefix operators - SEG and G. SEG is similar to OFF SETexcept that it generates the segment of the varable ther than the offset. G isspecial- a long (4 byte) pointer is created (ifneeded).in DSEG and its offset isgenerated. is normally used with LES to load a long (4 byte) pointer to a varable.For example:

msgESEG

I Hello World!! ' 10,

DSEGmsgptr DD msg

main

CSEGPUBLICpushmov

main , puts

BP, SP

5.3

Page 94: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The ASM88 Assembler

les S I, msgptr ;, long ptrpushpushleall putsmov SP, BP

mov AX, seg msg get segmentmov ES,

SI, offset msg

"',

get offsetmovpushpushleall putsmov SP, BP

les SI, msg seg:offsetpushpushleall putmov SP, BP

push msg+2 segpush msg offsetleall puts

mov SP, BPpoplret

To faciltate writing assembler modules that can work with both Large and SmallCase programs, the builtin symbol LARGE CASE is recognized by ASM88. It hasthe value 1 if the -b flag is set, otherwise it is zero.

The control directives IF, ELSE, and ENDIF have been added to support conditionalassembly. Any symbolic name set by an EQU directive can be used. Forexample:

strlen :CSEGPUBLIC strlenpush xor AX, AXmov BP, SP

5.4

Page 95: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The ASM88 Assembler

LARGE CASEles BX, (BP+6) point to string

SL LOOP: cmp BYTEES: (BX) , test for EOSELSEmov BX, (BP+4) point to string

SL LOOP: cmp BYTE (BX), 0 test for EOSENDIF

SL RETinc lengthincjmp SL LOQP

SL RET: pop

LARGE CASElretELSEretENDIFEND,

When combinn Lage Cae C8S and ASM88, keep the following in mind:

. Long calls (LCALL) and returns (LRET) are used.

. With the stadard'PUSH BP/MOV BP,SP prolog, pareters star at (BP-I6)

Pointers are returned in ES:SI

Static and fundamental data are placed in DSEG, structures and arrays inESEG

5.5

Page 96: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 97: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Chapter 6

The BIND Object File Linker

Introduction

Invocation

Examples

Small Case BINSpace Considerations 6.3Overlays 6.4

Large Case BIN

Libraes

Page 98: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 99: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The BIND Object File Linker

Introduction

BIND is the progra that lins together object and libra modules and forms anexecutable progra. For very long command lines, see the -f option.

Invocation

BIN c:fiename:: c:fiename::.. (options),

c:fiename:: A sequence of fienames separted by blan. The filenamesshould be the names of object (.0) or libra S) fies. If afiename does not have an extension

, '

0' is assumed. BINautomatically looks for the supplied libra CSIDIO.S so itsname should not be included in the list of fienames.

Options: All options may be in upper or lower case. Options must beseparted by blan and preceded by a hyphen to diferentiatethem from c:fiename::s. Note that this is different from othercommands where the hyphen is optional.

The assembler option keeps BIN from genera ng the Cintialization code. Intead, execution begins at thebeginng of the code rather than stag at the main publiclabel. ARGC and ARGV ar not calculated and the stack isI1 set up. Unitialized varables are I1 filled with zero.Libra functions such as creatO and openO canot be usedas they depend onthe zero initialization. The ' A' and'options ar useful for a few cases but caution should beexercised in their use.

Ths option indicates that BIN should also generate acheckout (.CHK) fie. This fie is required when using theDBB debugger and the profier.

Fc:f1ename:: identifies a file containng c:fiename::s andoptions to be us d by BIN. Ths is used for very long listsof fienames and options.

Lc:name:: specifies the drive/directory containing theCSTDIO.S ,standard libra. If this option is not specifiedthe CSTDIO.S fie musfbe on the default drive. WithMS-DOS 2.0 and later versions of the operating system, theP A TI system pareter is used to, locate the libra.

Page 100: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The BIND Object File Liner

Mn Indicates that the object fies following this control should becollected in the memory-based overlay indicated by thevalue n ( 1 to 39). See the description on overlays below fordetails on the overlay mechanism.

Oc:fiename:: changes the name of the output fie toc:fiename::.EXE. If this option is not specified, the name ofthe fIrt pbject fie in the list with the .EXE extension wil beused.

P( c:fiename::) Generates a sorted list of publics and offsets. Cprocedures and data declared outside of procedures areautomatically public (or extern) unless explicitly declaredstatic. Publics with names staiIg with an underline ' ' arenot listed unless the -- option is also specified. The optionalname is the destiation for the publics list. If omitted, thepublics and offsets are listed on the console. The size overlays, if any, wil also be displayed.

Shhh Specifies the stack size. hhhh is in hex. Normally,BIN wil set the stack size as large as possible for the SmallCase memory model, and to 8K bytes for the Lage Casememory model.

- Vo Ths option is used to create disk'-based overlays. All objectfies following ths option, until the end of the list or anotheroverlay option, ar collected into the overlay indicated bythe value n (1 to 39). See the overlay section below fordetals.

- (underscore) - BIN normally suppresses names that stawith an underscore (usually intemaI names) from the publicslist and the .CH fie. The underscore option makes thesenames available. Ths option is required when you need tosee all the modules bound to your program.

Page 101: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The BIND Object File Linker

Examples

bind blip

binds the fie blip. with CSTDIO.S and produces the executable fieblip.exe.

bind progaprogb progc lib. s -

binds the fies proga. , progb. and progc. with the user librar lib.and the standard I/O librar, CSTDIO.S, into the application fieproga.exe. The map is prited on the screen.

bind proga progb -VI progc -V2 progd -Pmap -- -Omyprog

binds the fies proga. , progb. with CSTDIO.S and creates theexecutable fie myprog. exe and the overlay fie myprog. ov whichconta two overlays consisting of the object fies progc. and prod.The publics map is sent to the fie named map and wil also list theinternal naes that begin with the underlie charcter.

Small Case Bind

Space Considerations

A progra is restricted to a maximum of 64KB of code and 64KB Of data plus thestack. BIND calculates the size of code and data and wil' report the size of eachsegment (in hex) when the -P option is specified. BIN cannot calculate the actualstack requirements. If the 'stack' and ' locals' size reported by BIND seems smallthe actual stack requirements should be calculated by hand to make sure there isenough space. The actual requirements are the worst case of four bytes per call plusthe size of locals (including parameters) for all active procedures plus about 500bytes for the Operating System calls. In practice, 2KB plus the size of the localarys simultaneously active should be suffcient.

If BIND report that the code limit is exceeded, look in the publics map for thescanfO and printfO routies. These ar relatively large routies (around 2KB each)and also link in the floatig-point routies. Eliminatig the use of these routines canresult in a large savings. If scanfO and/or printfO are necessary but nofloating-point values wil be used, tr using the CSTDI07.S instead of the stadard

Page 102: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The BIND Object File Linker

CSTDIO.S librar (Rename the CSTDIO.S librar to something else and renamethe CSTDI07.S libra to CSIDIO.S). This wil assume the availabilty of the 8087math chip and wil not bring in the software floating-point routines.

Another way to save some space is to use the CREA T2.C fie from the optionalHACKERS disk (not distrbuted with the compiler) which contains a version of the110 routines openO, c1oseO, etc. that only work with MS-DOS 2.0 and laterversions of the operating system. This saves around 3KB but wil not allow theprogra to be run under MS-DOS Lxx.

Overlavs

Another way to solve the space problem is the use of overlays. The overlay systemprovided by this package is very simple. An application is divided into a rootportion that is always resident and two or more overlays. Only one overlay resident (executable) at any given time. The following diagra outlines therelationship between the root and the overlays:

rootcode

overleycode

rootdete

overleydete

steck

overley

overley 2

overl ey n

There are two types of overlays, disk-based overlays and memory-based overlays.The difference between the two types is the location of the overlays. Disk-basedoverlays, created with the -V option, are stored in a separate fie. Memory-basedoverlays, created with the -M option, ar loaded into memory along with the rootcode. Memory-based overlays should only be used when there is sufficient memoryfor the root and all of the overlays. The advantage of memory-based overlays overdisk based overlays is in the amount of time needed to make an overlay resident,memory-based overlays being much faster to load.

6.4

Page 103: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The BIND Object File LinerThe application program is responsible for initializing the overlay subsystem andensuring that the correct overlay is resident before callng any of the functions inthe overlay.

For disk-based overlays, the routine overlay in it () must be called from theroot with the name of the overlay fie to initialize the overlay system. Overlays areloaded by calling the routine overlay (n) where n is the number of the overlay tobe made resident.

For memory-based overlays instead of disk-based overlays, do ll call theoverlay init () routine and call the routine mover lay () in place of theroutine overlay () .

In the following example the root is composed of the fie X.C. The first overlay isthe fie Y.C and the second overlay is in the file Z.

File X.main ()

overlay init (" OV" ); /* initialize */puts ("this is the root program\n"overlay(l); /* make 1st overlay resident */zip () ; /* call into 1st overlay * overlay(2); /* make the second resident */zap(); /* call into second overlay */puts ("bye\n

File Y.zip () (

puts (" this is ZIP

) ; ,

File Z.zap ()

puts (" this is ZAP

Page 104: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The BIND Object File Linker

The fies are compiled in the usual fashion:c88 xc88 yc88 z

Ordinarly, the fies would be lined together using the command:bind x y z

Instead, to create the two overlays, the command: ,-bind x -VI y -V2 z

is used. The -V option is followed by the overlay number. Ths number stas at Iand runs in ascending order up to 39: All fies following the -V or the -M option areincluded in the overlay. All libra modules (from .S fies) are included in the root.The result from the execution of the BIND program with the -V option is theexecutable root (.EXE) fie and the overlay (.OV) fie which contais the overlays.The result with the -M option is an .EXE fie containing both the root and theoverlays.

D88 knows about the overlays and wil not display public symbols that are notresident. The profier does not know about overlays and should not be used.

The -P option of BIND wil also display the size of each overlay as well as theoverlay for each symbol.

Large Case BINThe Lage Case Binder s name is BBIND. In most respects, BBIN is identical toBIND. The differences ar:

BBIN only works with Large Case object fies' and librares.

. BBIND uses BCSTDIO.S intead of CSTDIO.S. Rename BCSTDI07.S toBCSTDIO.S if you use an 8087.

. The default stack size is 2000H (8096) bytes. This should be more thanenough unless you have a huge amount of local data. The stack requirements

, are six bytes plus the local data space required for each active function call.You can change the stack size with the -s option.

. Overlays are not supported.

. The -p (Publics) map displays four byte addresses.

Page 105: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The BIND Object File Liner

Librares

Libraes are just concatenated .0 files. The .S extension tells BIND to only includemodules that are referenced. If all of the routines in a librar are required, renamethe .S fie to a .0 fie to force all of the modules in the libra to be included.

BIN includes the entie .0 module from a libra if any of its public names havebeen selected by other object modules processed by BIND. Thus, if a .0 fiecontais several functions, all of them wil be bound into a program if any of themare called.

, BIN searches a librar once. Thus if you have two modules, and and calls, the must follow in the librar. LIB88 attempts to order the librar so that

these inter-librar references are ordered so that BIND wil find them. ' One wayaround any circular dependencies (e.

g.,

also calls A) is to include the librartwice on the command line.

Page 106: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 107: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Chapter 7

The LIB88 Object File Libraran

Introduction 1 '

Invocation

Examples

Librares

Page 108: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 109: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The LIB88 Object File Libraian

Introduction

LIB88 is the progra that combines object modules into libra modules. Libraresare simply collections of object fies in a single fie from which the BINDer canselect the necessar modules. By using a libra, only those modules required by anapplication wil be bound into the executable (.EXE) file.

You can t mix Small Case memory model and Lage Case memory model objectfies in the same libra.

Invocation

LIB88 c:fiename c:fiename .. (option)

c:fiename names of object fies or other librares. If no extension is givenon the filename, ' 0' is assumed.

Options The case of the option is not significant. Each option should beseparated from other options by blanks. Options must bepreceded by the minus sign ('- ) character to distinguish themfrom o(fienae

Fo(fiename the ' pathame of a fie containing fienames andoptions to be used byLIB88. This is used to get around the128 charcter command line limit.

forces al input modules to be included in the output even ifpublics clash. Normally when there are duplicate publicsymbols, the module with the first occurrence of thesymbol is kept; al others are ignored.

Odilename supplies the name of the target library. Noextension should be included as LIB88 wil add the

ension S' which is required for a library. If omittedthe first fiename forms the basis for the librar name.

Caution: if a librar S) fie is first on the LIB88invocation, the -0 option must be used or no librar wilbe created. The c:fiename cannot be the same as the .name.

P( d1Iename ) A list of code puplics is produced. The list goesto the named fie if present, otherwise to the console. Data

Page 110: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The UB88 Object File Libraan

publics are not included in order to make the list shorter. Aminus sign is in columnJ at the star of each ' module.

(underscore) Publics that start with underscore arenormally omitted from the publics list. The underscoreoption wil include them.

Examples

LIB88 xx yy zz -Oxlib

combines the object fies xx.o, yy.o, and zz.o into a librar named xlib.

LIB88 xx -Fblip

where blip contains

yy zz-Oxl ib

behaves exactly the same as the fIrst example.

LIB88 xx xlib. s -Oylib

replaces the object fie xx.o in the xlib.s libra and places the result in a newlibrar named ylib.

Librares

Librares are simply collections of object modules that ar included into a prograby BIND as necessar. A librar is only searched once by BIND so if a librarmember A calls libra member B , module B ID follow module A in the librar.The libraran wil attempt to sort modules so the caller comes fIrst in the targetlibrar. If modules call each other, LIB88 wil print the warng

circular dependencies

The -N (for need) option is used to force object fies in a paricular order (ignoringcircular dependencies). It ignores the LIB88 sort logic and concatenates all theocfiename::s into a libra.

LIB88 installs the firt OCCUITance of a PUBLIC name into the taget libra. Thusif two modules have PUBLICs in common, then the module encountered fIrst wil

Page 111: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The LIB88 Object File Libraan

be installed in the librar. Thus to replace the CSTDIO.Sversion of qsort () withyour own, you would do the following

c88 qsortren cstdio. 5 cstdio. 0lib88 qsort cstdio -ocstdiodel cstdio.

CSTDIQ.S was renamed to 'CSTDIO.O to avoid any conflct of reading and writingto CSTDIO.S durig the update. LIB88 k. replace object modules in libraes with circular dependencies. Toupdate libraes that have circular dependencies, use both the .F option to name thefie of module names, and the .N option to suppress LIB88 sorting.

Libraes are just concatenated .0 fies. The .S extension tells BIND to only includemodules that are referenced. If all of the routines in a librar are required, renamethe .S fie to a .0 fie to force all of the modules in the libra to be included.

Page 112: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 113: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Chapter 8

The D88 C Language Debugger

Introduction

D88 Usage

Command Input 8.3

Expressions 8.3

CommandsAgaiBreakointCollectionDisplayExpressionFlip

ListMacroOptionsProc-stepQuitRegisterStepUnasembleVarablesWhere

Page 114: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 115: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The D88 C Language Debugger

Introduction

D88 is the C source language debugger for C88. Its features include:

Full screen display.

C source can be displayed while executing.

All local and global varables can be displayed.

C expressions can be evaluated.

Special support for debugging interactive progras on the PC.

Breakoints by address or line number.

088 only works with progras produced by the C88 compiler because it needsspecial symbol, type and line number inonnation. It is not as good as DEBUGwhen dealing with assembler progras. Like al debuggers, 088 needs lots ofmemory - about 45K extr for smal progras and 64K for large ones. Forsystems th are not IBM PC compatible, D88 wil bave to be configured before itcan be used. See th the intrctions in the CONFG.C fIe on Disk #2.

CAUTON: do not chage floppy disks whie 088 is executing. Changing any diskwhile a progra is rug may clobber the new disk.

D88 Usage

D88 needs symbol inormation that is not normally created. Before using 088, progra should be compiled and bound with the 'C' option in order to create thesymbol inormation. You can bind in modules that were not compiled with the 'option, but their symbol and line ,number information wil not be available.Assuming that the C88 compiler, binder, libra (CSTDIO.S) and 088 are on driveA: and that the D88 sample progra CB.C is on drive B: the following commandswil compile CB.C and create the symbol fIe.

A::C88 B:CB -cC88 Compilerend of C88

V2. (c) Mark DeSmet, 1982, 83, 84,04B7 code OOD7 data 21% utilization

A::BIND B:CB -CBinder for C88 and ASM88 Vl. 9(c) Mark DeSmet, 1982, 83, 84,end of BIND 19% utilization

8.1

Page 116: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The D88 C Language Debugger

The 'C' options wil create the checkout fie CB.CHK in addition to the usualexecutable CB.EXE fie. The CB.CHK fie contas pathames so the user shouldinvoke D88 with the same default drive (and current directory with MS-DOSV2.

...

) that was in effect during compilation so that D88 can find the C source.

The CB.C program is executed by

B:CB filename

For example, to run CB on itself:

B:CB B:CB231 linesA-;

No errors were detected. To debug or trace a program, prefIx the normalexecution lie with D88. Using the above example:

D88 B:CB B:CB

D88 wil clear the screen, prit the baner and issue the following prompt.

Again Breakpoint Collection Di8play Expre88ion Flip Go --8pace--

procedure MAIN file B:CB.C line D88 Debugger V1. 4 (c) Mark DeSmet 1984,

D88 command input is similar to SEE command input. The top line contas aparial list of available commands. To see the rest, hit the space bar and the top linewil change to the next prompt line. The prompt lines are:

Again Breakpoint Collection bi8play Expre8sion Flip Go --space--Li8t Macro Options Proc-step Quit Register Step --space--Unassemble Variables ere --space-- '

Page 117: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The D88 C Language Debugger

Error messages are displayed on line two. The fourt line gives the name of thecurrent procedure, the name of the curent source fie and the current line number.This line is always displayed. The remainder of the screen scrolls in the usualfashion.

Command Input

As with the SEE editor, commands are entered by typing their first letter. Forexample, tying ' R' wil display the registers. Commands may be entered in upperor lower case and the command need riot be displayed on the prompt line to beexecuted. The Agai Display, List andUnassemble commands can be preceded bya decimal repetition count. The count specifies how many lines should be processed.

If a command ha options, a prompt is issued to ask for them. For example: type 'for List and the following prompt wil be issued on the top two lines.

enter list line number or search stringexchange: 18

The cursor wil be at the first letter of ' 18' . Typing return or ESe means thenumber is correct. To change it, the number may be overtped or edited with thefollowing keys.

The right arow moves the cursor to the right.

00- The left arow moves the cursor to the left.

Ins The In key toggles between Exchange mode and Insert mode. Theprompt changes between 'exchange: ' and ' insert:

Del Deletes the charcter under the cursor.

backspace Deletes the charcter to the left of the cursor.

When any editing is complete, press Return or ES. During input, type control-to abort the command and return to the main prompt.

Expressions

Several commands wil accept expressions. Expressions follow the usual C rulesand are composed of varables and constats combined .by operators.

8.3

Page 118: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The D88 C Language Debugger

Varables can be referred to by name; case is ignored by D88. Only extern or staticvarables, local varables in the current procedure and parameters of the currentprocedure can be referenced. There is no way to reference locals of anotherprocedure. Statics are not scoped by fie -- the first entr in the symbol table isused. Statics that ar defined withn a procedure have their name prefixed by theprocedure name and ' , e.g. static int i; in mai is called MAIN I. The Varablescommand wil list the names of varables and the Expression command wil displaytheir values.

Examples: argc nextin main _

Registers may be referrd to by name. Example: ax

Constats may be of type int, long or float. Hex constats must sta with 'but must omit the ' . Octal constats are not permitted. Strgs and character

. constats are as usual. Examples: 2 23. le6 Olabc 'A' "hello world!"

Member references may follow the ' .' or '

-:;

' operator.

Examples: stru . mem spt r- ;:mem

Most of the usual C operators are supported. They are listed below in order ofprecedence.

assignmentaddition, subtractionmultiplication, division, moduluscontents ofaddress ofprefix minus

, aIYparenthesisfunction call

*/%

nameO

Examples of expressions:

2+2 arqv(l) stru-:;mem 'vara ax-44 "hello" (2) printf (" \d" , 2+2)

The last example shows that functions in the progra under debug can be executedby the Expression command. An expression followed by (arguments) wil be calledbut referrng to a function name not followed by the '(' yields the offset of thefunction.

8.4

Page 119: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The D88 C Language Debugger

Commands

To lear D88 tr out all of the commands on the CB progra. One caution: when afunction is fIrst entered, locals and pareters canot be accessed unti you use theStep command to move down to the fIrst executable instrction.

(n) Again only has meang afer a Display, List or Unassemble command.It displays the next n lies of bytes, source Iin s or disassembledintrctions respectively. If the count is omitted, 10 lines of source or 3lines of bytes or disassembled intrctions are displayed.

Prompts: none.

Output: Depends upon prior command.

Breakpoint sets a 'sticky' breakpoint A breakoint is a place whereexecution wil stop afer a Go command. A 'sticky' breakoint is onethat remai in effect unti changed or the Quit-Int command is ,entered.

Prompts: enter number of sticky breakpoint, 1 2 or

There can be up ' to thee sticky breakoints, numbered 1 2 and 3. Enter

the number of the breakoint you wish to change.

Address-break Line-number-break Procedure Forever

Enter A or P if you want to break at an address or procedure. Thenext prompt wil be:

enter procedure name or address

Enter an expression that indicates where you wish to stop, e. g. puts orDale.

Page 120: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The D88 C Language Debugger

Enter L if you want to stop at a specific line: number. The next promptwil be :

input line number

The fie is the current fie uness changed by the Options-Listfiecommand. There is no default line number. Only line numbers forlines containing executable instrctions can be referenced. Youcanot break at a declartion or comm

Enter I' for Forever to remove a sticky break or Go to completion.

(n) Collection displays the elements of an ary or strcture. The optionalrepetition count is the number of ary elements that wil be displayed.If a member is specified, that and all subsequent members of thestrcture wil be displayed. The display format is the same as thatdescribed under the description of the Expression command.

Prompts: input an array name , or structure. member.

Output: Assuming the following progra,

char a(5J=(1, 2, 3, 4, 5J,b ( 3 J (5 J =(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 J ,c=&ai

struct (int i, kiJ str=(11, 22, 33J,st=&stri

main (

The following collections ca be displayed.

input an array name or structure . member .exchange: aarray at 0004(OJ- 1 (lJ- 2 (2J- 3 (3)- 4 (4) -

input an array nameexchange: barray at 0009(OJ-array at 0009

or structure . member

(l)-array at OOOE (2J-array at 0013

input an array name or structure . memberexchange: b (1 Jarray at OOOE(OJ- 6 (1)- 7 (2J- 8 (3)- (4 J -

' 8.

Page 121: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The D88 C Language Debugger

input an array nameexchange: c0004-;:(0) '" (6)- 2

or structure . member

(1) '" (7)- 3

(2)" 3(8) '"

(3)= 4(9) -

(4)- (5)=

input an array name or structure . memberexchange: strstructure at 001A

input an array name or structure. memberexchange: str. i. I"" 11 0008 22 0016 33 0021

input an array name or structure . memberexchange: st-;:i. 1- 11 0008 22 0016 33 0021

The examples demonstrte the following rules:

1. If an ary name is entered, the address of the ary is printed followed bythe first 10 (orrepeat) elements.

2. A pointer is handled the same way except that the number of elements is notknown. Notice that arys used as pareters are passed as pointers so thenumber of elements is not known.

3. If the nae of a strcture element is entered, that and all subsequentmembers are displayed. Either the ': or '

-:;

' operator may be used asappropriate.

4. If any other tye of expression s entered, the value is displayed.

See the Expression command for the rules for element display.

(nJ Display displays memory in hex and ASCll. In contrast to Expr ssiontypes are ignored. The 9ptional repetition is the number of lines todisplay. The default number of lines displayed is thee.

Prompts: input (segment:) offsetNormaly a pointer name is input to s e what it points to in hex. Noticethat if a varable name is input, the varable value is used (e.g. if i is 3then a Display of i is the same as a display of 3). . Use the address (&)operator to see how a varable loolc in hex - &i would display i inhex. The data segment is always assumed. Use an overrde to displayother segments e.g. cs:O.

Page 122: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The D88 C Language Debugger

Output: 75B8: 07BE 2F 2A 09 43 42 43 48 45 43 4B 2E 43 20 20 20 2075B8:07CE 09 44 75 60 62 20 43 75 72 6C 65 79 20 42 72 6175B8: 070E 63 65 20 43 68 65 63 6B 65 72 20 66 6F 72 20 43

Expression evaluates and displays the results of an expression. A procedurecan be executed by including its name and pareters in an expression-- be careful of side effects. Only a subset of the normal C operators issupported but otherwise expression ru s for precedence, pointerarthetic and type conversion apply. '%e assignment operator can beused to set a varable or register. Static varables within functions havetheir name preceded by the procedure name and an underscore.

zipO t static int i; i' would be referred to as ' zip in the debugger. Examples:

2+2 argc argv(l) nexti bp+4 puts("hellol") puts ptr-:;off i=44

, Prompts: input an expression

Output: Chars ar displayed in unsigned and ASCII if possible, e.

67.

Unsigned ar displayed as unsigned and hex.

A pointer is displayed in hex. In addition, the strng '

.;:

' prints and theelementpointed to are displayed. In the Ca&e, of a pointer to a charcterup to 21 charcters ar displayed on the assumption that the pointer isto a strg.

Ints are displayed as decimal and hex.

Float and double are displayed as %9.2E.

Longs ar displayed in decimal.

Arys ar displayed as 'ary at' hex address.

Functions and strctures are similar to arys.

Page 123: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Flip

Prompts:

Output:

(n) Go

The D88 C Language Debugger

Debugging graphic or full screen applications can be a real problem asboth debugger and application need to use the screen and the twodisplays interfere with each other. The Flip command is par of themechansm designed to deal with ths problem.

The Flip command wil flp the screen. It only works on PC compatibles as it is hardware dependent (see notes in CONFG.C andFLIP.A on confgurig ths capabilty). The idea is that the user shouldhave two screen displays - one which is prod\lced by the programunder debug and the other which is used for the D88 display. Theapplication screen is automatically restored before the Go commandresumes execution. The Flip sub-option of the Step and Proc-stepcommand must be used to restore the application screen beforeexecutig any command tht affects the screen display. When thescreen image is preserved in th way, the Flip command can be used todisplay the application screen. Pressing any key wil return to the D88screen.

none.

The application screen wil replace the D88 screen. Hit any key toreturn to D88.

causes the progra being 'debugged to execute. . The user is promptedto enter one breakpoint. The description of the Breakpoint commanddescribes how th breakoint may be entered. The breakpoint may beat the curent address; if you enter an address breakpoint of IP, theprogra wil execute until it return to the staing point. Ths can used to execute one iteration with a loop.

After a Go command, 9 lines of the source are displayed. A '

-;:

' pointsto the currnt line. The Option command can turn ths feature off.

The optiona repetition specifies how many breakoints should be hitbefore execution ceases. A count of 10 Go s to IP would execute a loop10 times.

If the Option command sets the ' Flip on Go' option off , the output ofthe debugged progra and D88 output wil be intermixed. The defaultis to display the debugged progras output before executioncommences.

Page 124: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Prompts:

Output:

, (n) List

Prompts:

The D88 C Language Debugger

Once staed, a program wil execute until a Breakpoint break is hit, theGo breakpoint is hit, EXIT is called or control break is hit. In anyevent the Go breakpoint wil be removed. Under DOS Lx (andCP/M-86), EXIT and control break wil cause D88 to terminate.Under MS-DOS 2.

, ..., '

normal end' prints and D88 continues. TheForever option should be used if you wish the program to run tocompletion or to a sticky break set by the Breakpoint command.

Address-break Line-number-brea Procedure Forever

See the description of breakoint entr under the Breakpoint commanddescription.

The progra wil execute.

lists any ASCII fie. It is normally used to list the source of theprogram being debugged. If the count is omitted, 10 lines wil belisted. After a List command, the Agai command can be used to listmore lines without enterig' the line number.

The currnt fie is the one listed uness the Options-Listfle command isentered.

The prompt asks for the line number or a strg. If somethng otherth a number is input, then the List command only lists lines thatconta the charcters. chig always sta from top of the fie.The searh strng option cal be used to find a procedure defmition orvarable references.

enter list line number or search string

The default is the current line number or the last line listed if the Listcommand was just executed. Enter retu to list source from thecurrent line or a decimal line number or a search strg.

Page 125: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Output:

Macro

Prompts:

Output:

The D88 C Language Debugger

enter list line number or search stringexchange: 1818 main (argc, argv)19 int argc;20 char *argv (); 21 int chi22 char col;

if (argc c 2) error("no file name"

, ""

read file(argv(l)) ;while (1) (

enter list line number or search stringexchange: read file25 read file(argv(l));

47 read file (fil)

remembers commands or sequences of commands. Four Macros can bedefmed FI, F2, F3 and FIO. All keyboard input is collected into aMacro unti another Macro command is entered. Once defined, aMacro is executed by simply hittng the appropriate function key. Macro can be up to 80 keystrokes -long.

enter )name of macro. FI F2 F3 FIOHit the appropriate function key.

enter another Macro command to end definition

Prited after the above prompt is anwered. All input wil beaccumulated into a Macro until another Macro command is entered.

Macro is defined

Prited if the Macro command is invoked to end a Macro defmition.

FIO is a 'permanent' Macro. If defined , it is run every tie the screenis re-wrtten and its output is placed after the top 3 lines. This permitsvarables to be permanently displayed.

Page 126: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The D88 C Language Debugger

For example:

, i, "

, j, "

(hit M for macro command)(ht function key 10 as name of macro)(hit E for expression command)(enter expression note the comma

mean a list of values)(end macro defInition)

FIO

A line like i= 44 j= 2 k= 11 wil be displayed near the top of thescreen until F10 is redefIned. The values are thus continually updated.

Opdons There ar currently thee options: flp screen on go, list after go, andlist fie name. The Flip-on-go option allows D88 output to be intermixed with useroutput. The default is to flp the screen before a go executes. Thedisadvantage of not flpping is that the output of the application wil beintermixed with D88 output. The disadvantage of the default is theflashig that occur if the Flip is not needed.

The Go-list option can disable the listing of source after a go command.Every Go, Proc-step and Step command sets the current listfle name tothe fie containg the cunt statement. Ths name is used by the ListBreakpoint and Go commands. Use the List-name option to change thename.

Prompts: Flip-on- Go-list List-name'

If r is typed,

flip screen on Go (y or n) ?

Enter 'Y' or ' ' to set the option on

, '

N' or ' ' to turn it off.

If G is tyed

list after a Go (y or n) ?

Enter 'Y' or ' ' to set the option on, 'N' or ' ' to turn it off.

If L is typed

Page 127: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The D88 C Language Debugger

input list file name

Type the desired fiename.

Output: none.

Proc-step The Proc-step (:ommand prits the current source line and allows theuser to execute it. Proc-step differs from Step in only stopping on linesin the curent procedure. Proc-step also stops after a return so you canProc-step back to the calling procedure. Step wil stop on any line.

A Flip option allows the user screen to replace the D88 screen duringstepping. If ths option is not invoked before statements that affect thescreen, then progra output wil be intermixed with D88 output.When the screen is flpped, there is no prompt but the user must stil hitspace to execute the next statement. Typing ' F for Flip wil restore theD88 prompt

Only executable lines wil show up while stepping; declartions andcomments are not listed.

The procedure MAINdurig stepping.

file B:CB. line 18 line is updated

Prompts: Flip Proc-step Step space to Proc-step. default=quit.r wil flip the screen. s wil change from Proe-step to Step and step the current line. P wil change back to Proe- step and step theline. Space wil Proe-step or Step, whicheveris current. If thescreen is not flpped, the next line wil prit. Typing anytng else wilterminate stepping.

Output: When the screen is not flpped, the current line prints as a prompt.

Page 128: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Quit

Prompt:

Output:

The D88 C Language Debugger

The Quit command terminates a debugging session and either exits tothe operating system or stars a new session. On exit, the user screen isrestored.

The Initialize option allows debugging to begin again. Caution: fiesar not closed. You may run out of fies or not be able to re-open fies.

Quit : Exit Initialize

E restores :the user screen and return to DOS. If the program hasbeen EXITed or interrpted with control break, you can only Exi t. Idisplays the following prompt:

input command line

Enter the par of the command tal that would follow D88, if D88 werebeing executed; e.

CB CB.

Press the return key if you change your mind and do not want to staover.

D88 quits or sta over with the indicated command tail.

Register The Register command displays all the registers. Use the Expressioncommand to set a register to a value.

Prompts:

Output:

Step

none.

AX-7500 BX-FFEB ex-oooo DX-OOOO SI-FFFF DI-07BE BP-FFBE SP-FF90DS-757E SS-757E ES-757E eS-729E IP-0003 FL-F206

The Step command prits the curent source line and allows the user toexecute it Step differs from Proc-step in stopping at every line notjust lines with the current procedure. If you step a line that containsa call to another procedure, you wil step though the called procedure.See the description of the Proc-step copnand for details on thiscommand as Step and Proc-step are otherwise identical.

Page 129: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The D88 C Language Debugger

(n) Unassemble The Unassemble command disassembles someinstrctions. The repetition count says how many instrctions shouldbe disassembled. The default is 10. The Agai command can be usedafter an Unassemble command to prit more instrctions withoutre-entering address. Disassembled output follows normal assemblerrules except that relative jumps prit their target as absolute numbers(A=hh). If the repetition count is the Unassemble Gommand wil disassembleone line and prompt with a . Pressing the space key causes the

instrction to execute. This continues until the user presses a key otherth the space key

Prompts: input (segment:) offsetThe default address is the cuent one. If an expression is entered, it isassumed to refer to an intrction in CS:. An explicit segment can beentered, e.g. 0123: Octa.

Output: 729E:0003729E:0004729E:0006

aB ECa 3 EC 04

PUSHMOV

SUBBP, SPSP, 0004

Varables The Varables command wil list the program varables, optionallywith values. Pressing retu to the prompt wil produce a four acrosslist of all varable naes. The locals accessible to the current procedureare listed fIrst, followed by the publics. Both are sorted. If a name orname pattern is entered, the varables are listed with their value. Thevalues ar formatted according to the rules for the Expressioncommand. An asterisk ('*') at the end of a name means match any namethat sta with the preceding letters. An asterisk by itself wil list allvarables with values.

Caution: before the fIrst instrction of a procedure is executed, thestack frae is not established and parameters wil not be printedcorrectly.

Page 130: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The D88 C Language Debugger

Prompt: input variable name or pattern (a* means start with a)

Output: input variable name or pattern (a* means start with a)exchange:

ARGC ARGVATOI ATOL

CSTSEXIT GETCHAR IIIINDEX JJJJJ , JJJJJJJ MAINPUTCHA PUTS RINDEX STRCATSTRCMP STRCPY STRLEN STRNCATSTRNCMP STRNCP Y

Where

Prompts:

Output:

input variable name or pattern (a* means start with a)exchange: i *

III -II

INDEX -I -

5 00053 0003

function2 0002

at 031E

The Where command list the current procedures. The name, fie andline number of every procedure curently executing wil prit.

none.

procedure READ FILEprocedure MAIN

file CB.file CB.

line 56line 25

Page 131: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Chapter 9

Utility Programs

CLlST: a listig & xref utility

DUM: a hex and ascii display utility

FRE: a free space display

GREP: a fie search utility

F ASTSCR: a screen output enhancer

LS: a directory listig utilty 9.4

MERGE: a C source and assembly langugemerge utility

MORE: a fie screen listig utility

PCmake: a progra maintanance utilty

9.5

RM: a file removal utility

PROFILE: a performance monitor utilty

SENSE87: an 8087/80287 sensing libra

TOOLBOX.S: a libra of useful tools

Page 132: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 133: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utilty Progras

CLIST: a listing & xref utilty

The clist utility reads C soure progras and produces a listing, or a fie, whichcontans a paginated, line numbered listig of the C source lines and a symbolcross-reference map.

To invoke the clist progra, enter

clist filename

...

( option

fiename

...

- a list of the C source fies to be listed, in the order that they are tobe listed. If no extension is given

, '

C' is assumed. Clist does notautomatically read the "include" fies so they should be listed first. Thsis to prevent the include fie from being listed by every source fie thatincludes" it. Note: if you specify more th one fie, the symbols wil

be combined into one cross-reference map.

Options: The case of the option chaters is not significant. Each option mustbe preceded by the mius-sign, ' , chacter to distinguish it from afilename. The options ar:

Fc:fienam identifies the fie contang the o:fiename s to belisted.

Lc:size;:/-Pc:ize;: sets the page length used by the clist prografor generating pagination. The default is 66 lines.

elimintes the cross reference listing

Oc:lename;: supplies the nae of the output fie for the listing.Without ths control, the first nae in the list of fienamesis used with the extension, ' . If no extension is given the fiename, ' L' wil be used automatically. If you wishto list on the priter use -OPRN:

sets the width for tab charcters (the maximum number ofspaces that a tab occupies). The default expansion size is 4.

- W c:ize;: sets the width of the listig. Lines wider than the width arewrapped to the the next line. The default width is 80.

- T c:size;:

9.1

Page 134: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utility Progras

For example

clist blip.

wil generate a fie naed blip . 1 with the following contents

BLIP. C dd/mm/yymain ()

int i;hh:mm: ss Page 1

printf ("Table of Characters\nfor (i = 0; i -( 256; i++) (

printf ("Character %d prints as %c\n i);

----XREF----

mainprintfThe symbol, ' , following the 'man' symbol in the cross-reference listig indicatestht the symbol was declared on that line. Clist only supplies the declartion lineinformation for procedures or data declartions which begin in the firt column.

Dump: a hex and ascii display utility

The dump utiity progr is used to display the contents of a fie in hex. It isavailable in both source (.C) and executable (.EX) form.

To invoke the progra, enter

dump -(filename;:

The dump progra displays J 6-bytes per line with each line showing the offset tothe first byte in the lie, the 16 hex values, and the chacter equivalent enclosedbetween asterisks (*). For example:

0000 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 *ABCDEFGHIJKLMOP*

0010 51 52 53, 54 55 56 57 5859 5A 0000 00 0000 00 *QRSTUVZ...... *

Page 135: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utilty Progras

ASTSCR: a screen output enhancer

Ths is a simple progra to make character output to the screen run faster than thestadard IBM-PC BIOS routines. It works by intercepting the level 16 interrpts(int 10H) and routing the charter output(write tty) requests to code which actsdirectly on the screen buffer. Requests which are not supported are passed on to thenonnal BIOS routine.

Works for all progras which use the BIOS calls or DOS calls:

To instal the progra, simply

fastscr

FRE: a free space display

free is a very simple progr to show the amount of free space left on a drivewithout having to watch a dirctory listing. The synta for free is:

free -(device;:

where -(device:: is A: B: ...

GREP: a fIle search utiity.

grep is a progra used to searh fles for lines contag a cert pattern.

Whenever the pattern is found, the line is listed on the screen. The synta for grep

is:grep ( - y ) -(search pattern;: file

...

indicates tht case is to be ignored durig the search.

",search pattern is any sequence of charcters. It may contain the wildcardcharcters * and 7. NOTE: if the pattern contas blans orwildca charcters, then the search pattern must be enclosedwithin double quotes ("

fie is any fiename and may contain wildcard characters.

When a match is found, grep wil display the line along with the line number andfiename.

Page 136: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utility Progras

LS: a directory listing utilty

Is is a directory listing program loosely based on the UNix utility. It featuresmultiple-column listing, sort by name or modification date and reverse ordersortg. The synta for runnng Is is:

ls ( -ltr1? J ( pathnarne ...

invokes the long format which is a 'single column listing with thefollowing format:

':narne ':attrib ":size ..tirne ':date

..a t t r ib has thee chater fields. The firt field displays the tye offie. The second field indicats read permission. The thd field indicateswrte permission.

BE = normal fies

= system fles= dirctories= hidden fles= readable

= not wrteable

= writeable

changes the sort order to list fles by their modification dates rather thanthe default alphabetica order. Times are listed with the most recentlymodifed fies first.

reverses the order of the sort alphabetic ot by time.

produces a single column of output.

displays the input synta for Is.

pathame ca be a drve name ( C: ), a dirctory nae, or fienae which mayconta the wildcard searh chacters * and? If no pathe is given.the current directory is assumed.

At the end of the listig, the number of fies listed and the tota size of the listed fiesis displayed.

9.4

Page 137: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utilty Progras

:MRGE: a C source and assembly language merged listingutilty.

merge is a progra used to merge a C source fie with its corresponding assemblylanguage fie generated by CBB with the -A and -C switches. The synta for mergeis:

merge .cfile

where .cfie:: is the nae of the .C and .A fies to be merged. The output of themerge progra is placed in the file dile::.L For example, to get a merge listing ofa fie named BLIP:

cBB BLIP A Cmerge BLIP

The fie BLIP.L wil be created with the merged information.

MORE: a file screen listing utilty.

more is a progra used to view text fies. Ths version is slightly moresophisticated than the progr which is delivered with PC-DOS. It includes theabilty to searh for a given strng. The synta for more is:

more file

...

where fie may contan wildcard charcters.

When the progra pauses and displays the --MORE-- prompt, you have a numberof choices:

/.cpattern seahes for a line with the given pattern. If the pattern is notfound, the -MORE- prompt is redisplayed.

termnates the progr.

fids the next line with the same pattern used in the last command.

Any other charcter wil display the next 22 lines of the fie.

Page 138: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utilty Progras

PCmake : a program maintenance utilty

PCmake is loosely based on the UNIX make progra. This progra is used tokeep trck of depedencies between fies and, based on the last modification date, Cc-

generate a batch (.BAT) fie for updatig out-of-date fies. This batch fie can thenbe executed to perform the update.

Invocation Synta:

PCmake ( dependent ) (-f input

) (-

output

) (

d) (-a) (-i)

":dependent;: is the nae of the dependent fie to check for update requirements(the first dependent fiename used in the input fie is used default).

-f":input;: causes PCmake to get its input from the given fie (Umakefieused by default).

-o":output;: causes PCmake to wrte the batch file to the indicated fiemakeit.bat is used by default).

lists the dependency tree display to the console.

insures that all fies ar updated regardless of the modificatondates. -

turn off the error checkig produced in the .bat fie

The input fie to PCmake ha the following synta:

":dependent;: (":dependencies;:) ":constructor;:

.. depen dent;: is the file which is to be updated as necessar.

":dependencies;:, is a list of fienaes on which the fie is dependent. Th listcan span multiple lines and is terminated by the u

)".

..constructor;: is a number of lines, terminated by a blan line, which areexecuted in order to update the fie.

Page 139: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utilty Progras

The simplest example of a fie dependency is an object fie s dependency on thecorresponding source fie. When the source fie is altered, PCmake can be used todetect that the object fie is "older" than the source fie and ca generate the compilecommand to update the object file. For example, if we have a source fie namedfoo. c, with its corresponding object fie foo. 0 and executable fie foo. exe, themakefie might look as follows:

foo. exe ( foo. o cstdio. s )foo.o ( foo. c stdio. h )

bind foo. cBB foo.

Note the "extr" dependencies of the .EX fie on the c libra and the object fiedependecy on the stadad include header fie. If a modification was made to foo.and PCmake subsequently executed, it would produce a batch fie with the followinglines:

eBB foo.IF ERRORLEVEL 1bind foo. IF ERRORLEVEL 1:stop

GOTO stop

GOTO stop

which would result in updating the fie foo.exe. However, if the source fie had notbeen changed, but a new cstdio.s libra was copied onto the disk, then PCmakewould simply geneI'te:

bind foo. IF ERRORLEVEL 1 GOTO stop:stop

since the source fie doesn t need to be recompiled.

MACROS

A macro is defined by beginning a line with the macro charcter '$' followed by themacro name and the definition. For example:

$FOO a. o b. o c.

would define the macro$FOO as the strg a. 0 b. 0 c. o and could be used in thedependency line

xx. exe ( a. o b. o c. O J

xx. exe ( $FOO

Page 140: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utilty Progras

Macros may also be use in the constrctor lines to allow fast substition fordifferent enviroiu nts. For example: to enable the checkout flag on the compilerwhile you ar debugging, add the macros

$C88 c88$C88FLAGS -c

and constrct your dependency lines like

foo. ( foo. c stdio. h ) $C88 foo. c $C88FLAGS

When you want to generate a production version. redefine $C88FLAGS to null byspecifying

$C88FLAGS

and then use the -a option to reompile everythg without the checkout option.

SHORTcuS

PCmake also recognzes cert f'ename extensions and can produce dependencyand constrctor lines without fuer user input. The .exe extension, is recognizedas being dependent ona fie with the o extension and is created by using the binder.The .0 extension is recognie as being dependent on either a .c or .a f'e (in thtorder) depending on which file exists and is created by either compiling orassemblig the fie.

For a very simple makefie, with only a single fie that must be compiled (foo.c) andbound, we can simply use the followig two lines:

foo . exefoo.

PCmake wil automaticaly generate the dependency on foo.ofor the foo.exe lineand the constrctor line

$BIND88 foo. 0 $BIND88FLAGS

For the second line, PCmake wil find thb file foo.c on the disk and make thedependency and constrctor line

$C88 foo $C88FLAGS

Page 141: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utilty Progras

Note the use of the macros $BIND88 $BIND88FLAGS $C88 $C88FLAGS. This

allows you to tailor the defaults to your system. For example, if your compiler is inthe root directory and on the default dirctory, you can add the macro definition

$C88 le88

to your makefie and the PCmake progra wil replace the macro name $C88 withthe strng Ic88.

The defaults for the internal macros are:

$BIND88$BIND88FLAGS$C88$C88FLAGS$ASM88$ASM88FLAGS

bind88-Cnone;:e88-cnone;:asm88-Cnone;:

Miniizig the first example would yield the following makefie:

foo. exe ( foo. 0 estdio. s )

foo.

This wil generate the same .BATfile as the origial example. Note the blan linebetween the, two lies. Ths is requird whenever there is a dependency list toterminate the list of constrctor lines. PROFI: a performance monitor utility

Profie is a performance monitorig tool for use with the C8S compiler. It providesa statistical measure of the amount of tie spent in a program or procedure withinthe program.

With the version 2.3 or later compiler, specifying the check option (-C) for C88 and BIN wil create a .CH fie. The profier uses the .CHK fie to producesymbolic output instead of the stadard hexadecimal output.

Profie only works on the IBM-PC and very similar machines as it manipulates thehadware timers. It also requires the use of MS-DOS V2.xx or later.

To invoke the profier, type:A;:profile

Page 142: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utilty Progras

The pro fier wil load and request the command line of the program to be analyzed.Enter the command line as'if you were invoking the program normally. Theprofier wil then display one of the following two menus:

If a corresponding .CHK fie exists:

All List-procs Procedure Range Quit Start

or if no .CHK fie exists:

Range Quit Start

Make a menu selection by typing the fIrst charcter of the appropriate menu item.

All indicates that,theentie progra is to be monitored and broken downby procedure.

List-procs -displays the proedure names and addresses. When enterigthe name of the procedure, the wildcard chacters * and ? may beused. * wil match anyting, ? wil match any single chacter. Allnames which matc the pattern wil be displayed.

Procedure indicates that a single procedure is to be monitored. Theoutput wil be displayed with the line numbers withn the procedure.

Range indicates tht a specific rage of addresses within the program is tobe monitored.

Quit abort the current profiing session.

Start begins , the execution of the progra.

After the monitored progra exits, control is returned to the profier which wildisplay the execution histogra and the following menu:

Disk-list List-again Quit

Disk-list indicates thatthe profIing histogra should be wrtten to a disyfie. The profier wil prompt for the nae of the fie.

List-again indicates that the histogra should be redisplayed from thebegining.

Quit exits the profier.

9.10

Page 143: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utility Progras

Use the space bar to display the next set of procedures or line numbers in thehistogra. The histogra includes the entres "system" and "other

. "

system" is

the amount of time measured outside of the executing progra s code segment.

other" is the amount of time spent within your code segment but outside of themeasured range.

The profier also uses two other progras, profsta.exe and profend.exe. Theseprogras may be placed in the current directory or in a director identified by thePATH environment variable.

Sampling Algorithm

Internlly, the profier maintas 1024 counters which are used to monitor theactivity with certn regions of memory. The location and size of these regionsdepend on the range specification. The size of each region is determined bydividing the entie rage into 1024 equal size pieces. The minum size of a given

piece is 1 byte. For example, if the selected rage is Ox1C to Ox401C, the size of

each region is 16 bytes. Each tie the tier intel'pt is generated, the counterassociated with the locaton of the intrction pointer is incremented. In thsexample, an IP value between Ox1C and OxlC wil appear in the first region. Ycm

ca see tht the selection rage sets the grularty of the sampling mechasm.Shorter rages lead to fmer graularty and therefore more accurte measurements.Because of the graular nature of the sampling method, some sampling errors mayoccur. If the end of one procedure and the beginng of another procedure happento fall into the sae sampling region, then the second procedure wil inerit thecount from the, end of the first procedur.

RM: a file removal utilty

rm is a simple progra to delete files. The mai difference between nn and DEL istht rm wil accept multiple fienames and can work interactively. The syntax forrmis:

rm (-i (-1) filename

...

sets the interactive mode. nn wil ask for confrmation on each of thefies before deletig it.

sets the list mode to list the names of the fles as they are beingdeleted.

filename may contain the wildcard characters * and ?

Page 144: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utilty Progras

If no fienames are given, the progra wil display its synta description. (e.g. ifyou only type nn or if th re are no fies which match) . ' nn does not supportdeletion of directories.

SENSE87: an 8087/80287 SENSING LffRARY

. ,

SENSE87 was developed by Dan Lewis, Key Sbftare Products, 440 Ninth AvenueMenlo Park, CA 94025 (415) 3649847

SENSE87.S contas everyg you need to make an 8087/80287 sensing librafor your C88 compiler. This effectively eliminates the need to build two differentversions of your progrs, one for machines that have an 8087/80287 coprocessorand another for those tht ,don t. Most people have been taking the easy way ' out,Creatig code tht never uses the coprocessor, even if one is instaled; now yourprogra can automatically sense the absence or presence of a coprocessor, and taeadvantage of its speed if instaled.

The modules included here were created by combing 8087 and non-8087 routinfwith, 8087- sensing softar that automatcaly chooses between the originrouties. Since both the coproessor and non-cproessor versions must be in thesensing libra, your EXE fie size (in parcular, the code segment) wil increase, .probably by about 2K bytes, but wil depend on howmany floatig point functions

your progr pulls in from the libra.

NOTE: If you are using tle'088 optizer frin Key Softare Products, be sure todisable the 8087 option (-7) so tht the CALLs to the f16atig;.point libra are NOTreplaced by in-line 8087 intrctions!

HOW TO CREATE YOUR SENSING LffRARYThe fie SENSE87. conta the object f'es required to create.an 8087-sensinglibra CSTDIO.S from the stadad 8087 libra (CSTDI07.S). Large Case fies

are BSENSE87.S, BCSTDIO.S and BCSTDI07. The fie SENSE87.BAT(BSENSE87.BAT) wil create the sensing libra in the directory you specify.

For hard disks, with a copy of distrbution disk #1 in drive A, enter:

C::a: sense87

For floppy disks:

B::a:sense87 b:

Page 145: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utilty Progras

TECHNCAL DETAILS FOR THOSE WITH INQumING MINDSThe modified libra entry points ar the following: (All other libra routies thatdo floating point computations do so by calls to ths floating point kernel.)

chk8087 (added)- floade- fstoree- fc1ear= fneg

fis- fsub- fmulceilata

testint (deleted)

- floadl- fstorel)cmpkeep

fnotfdec

- faddsqrtlog-tan

floadd- fstored- fxch=fcmp

fzero- rmc

fdivfloorexp-

The replacement routies each begin with a JMP intrction that jumps though adata segment "vector . The vector intially points to a short setup routine whichchecks for the 8087/80287. The first execution of the setup routie replaces thevector with a pointer to the appropriate version of the code, and then jumps thoughthe updated vector.

The 8087/80287 check is hadled by a public routie called "- chk8087" whichactuy only checks for the coprocessor once, and saves the result so it can bereturned without resettg the coproessor on subsequent calls made by otherroutines.

The technque used to sense the coprocessor is to execute an FNIN followed by aFNSTCW, then to examine the most significant byte of the control word stored bythe FNSTCW for the approprite value. Some late-model PCA T's are known todestroy the segment containg the location of the stored control word, stangfrom its offset to the end of the segment To avoid ths problem, the routie copiesDS to ES and the offset of the destition address into SI, then backs off ES whileincrementig SI until the offset is within the rage FFO-FF. If it turn out to FF, then it is changed to FFO and ES is incremented. Of course ths requiresthat 32 bytes be reserved withn the data segment where the control word is to bestored.

Page 146: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utilty Progras

TOOLBOX.S : a librar of usefu routines

The following routies are in TOOLBOX. S located on Disk #1. To include them iryour progra, include TOOLBOX. S in your BIND command line

BIND ... TOOLBOX. S ...FINDFILE

int findfile (filename, target buf)

searches for the fie given ,in fiename by checking the current directory and thedirectories listed in the P TI environment varable. If the fie is found, fmdfiereturns 1 and the taget- buf area contans the FUL pathame. If the fie isnfound, 0 is retued.

Requirements: This routie uses 300 bytes of stak.

Limits: only 256 bytes. of the P A TI varable wil be searched.

LINE INPUT ROUTIS:

char *cur line;int line number;line start (fname, position, first line)

opens the fie fnae at the loction position (long). The fIrst line of the fie wil bepointed to by cur line after ths ca and line number wilbefirsUine. Retus 1 ifsuccessful, 0 otherwise.

line next ()

Returns 1 if another line is avaiable, sets cur lie to point at the new line andincrements line number; return 0 if no more lines are available.

line stop ()

closes the input fie.

Page 147: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Utilty Progras

line2 start, line2 next, line2 stop, cur2 1ine,line2 number

Same as above for a second fie.

WILDCARD EXPANSION

main (argc, argv)

Ths is a C mai procedure which expands wildcard fienames out to multiplearguments. Command line items such as * c return all the .c fies in the currentdirectory. The user main progra must be named main1 instead of mai for thelinage to work.

Page 148: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 149: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Chapter

The CSTDIO Library

Introduction 10.

Names 10.

Program Initialization 10.

Callng Conventions 10.4

Memory Management 10.

Input/Output Library 10.Directory Level Functions 10.File Level Functions 10.Stream Level Functions 10.Handle Level Functions 10.Screen Level Functions 10.Console Level Functions 10.

Math Library 10.15

System Interface 10.

Environment 10. 18-

Librar 10. 18-Headers

assert.h 10. 18-ctype. 10. 18-math. 10. 18-setjmp. 10. 18-stdarg. 10. 18-stdio. 10. 18-stdlib. 10. 18-string. 10. 18-

Functions & MacrosAlphabetical by name

Page 150: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 151: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

, The CSIDIO Libra

Introduction

Ths section describes the stadard librar, CSIDIO.S, for the C88 C compiler andASM88 assembler. Ths libra includes routines similar to routines available inUNIX with some inevitable differences due to the DOS Operating System.

All the routines are in the CSIDIO.S fie provided on the distrbution disk. . ForBIN to execute correctly, ths fie must be either on the default drve/directory, ina directory listed in the P 11 system pareter, or on the drive/directoryreferrd to by the option.

Ther CSTDI07.S libra has the same functions as CSIDIO. , but requires an 8087math coprocessor to perform floating-point operations. To use the 8087 librar,rename CSIDI07.S to CSIDIO.

Names

Public names staing with the underline charcter are used by C88 internalrouties and should be avoided. Names of this form are also used for user-callablerouties such as _move () that have names that might conflct with user names.

C88 automatically appends the underline character to public names to avoidconflcts with assembly languge reserved words. ASM88 does not do ths so theunderline must be manualy appended to publics used to lin with code generated byC88. For example, the C put s () routie should be referred to as pu t 5 - fromassembler. Unlie UN, BIN ignores the case of publics, so put 5 - matchesPutS

. n .

Page 152: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

Program Initialization

BIN inserts a jmp _csetup as the first executable instrction in the program.- CSETUP performs the following initialization functions:

Memory Model

1. ' Small Case

Large Case

Sets the datastack segment size to the lesser of: theamount available memory, 64K, or the size of the staticdata area plus the BIN -S option,

Sets the stack size to the value specified in the BIN -option, otherwise sets the stack size to 8K.

2. Both Formats argc and argv () from the Progra SegmentPrefIx,

, 3. , Both Zeros the Unitialized.Data Area, and

4. Both Calls main (argc, argv)

The figure below shows the Small Case memory layout after intialization:

Stack

Free Memory

Unlnltialized Data

Initialized Data

Code

Program Segment Prefix

showspO

memoryO

DS (DSEG)

CS (CSEG)

low memory

Figure 11)-

Small Case memory model

10.

Page 153: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSIDIO Libra

The figure below shows the Large Case memory layout after initialization:

Free Memory

Stack

Uninltiallzed DSEG & ESEG

static & Initialized scalars

Initialized arrays & structures

Code

Program Segment Prefix

DS (DSEG)

(ESEG)

low memory

Figure 10-

Large Case memory model

The intialization code saves the address of the Progra Segment Prefix. To accessthe PSP address from C use

extern char * -pcb;

From assembly languge use

dsegpublic -pcb :word

Assembly language mai progras that require normal C address spaceinitialization should conta the following:

PUBLIC MAINMAIN

See the Memory Management discussion below for information on how to access thefree memory.

Page 154: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

The -A option of BIN inhbits the call to - c s et up. Execution stars with thefirst instrction of the first fiename specified to BIN. See the fie BUF128.A onyour distribution disk for an example.

On entr, the registers have the following values:

ES, DS

Address of Code Segment. Execution stas at CS : a .Address of Data Segment.Address of Program Segment PrefixStack size set by BIN

The librar module that contas - csetup also contas the following functionsthus they canot be replaced in CSTDIO.S without removing - csetup.

ci () co () csts () exit ()get char () put char () puts

() _

memory ()setsp () _showcs () _showds () _showsp ()

Calling Conventions

For a given C fuction, the stack is arged as follows:

Arguments

eturn Address

Previous BP

Local Variables

low memory

Figure 10-

Stack Frame Layout

10.4

Page 155: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The memC?ry model layout is defined in assembler as

The CSIDIO Libra

ARGSSARGCALLRET

ARGSSARGCALLRET

LARGE CASE

equ bp+6equ bp+ 10lcalllretelse

equ bp+4equ bp+6callret

endif

Called functions must preserve CS, DS, SS, SP, and BP across the function call., No other registers have to be preserved.

Function arguments ar pushed on to the stack, rightmost argument first. Thecalling function cleans up the stack. For example

int * i ;zip (i, 6);

would generate the following code in the Small Case memory model

mov ax,push push word ipublic zipCALL- zipadd sp,

and would generate the following code in the Lage Case memory model

mov ax,push push word i (2)push word ipublic zipCALL zipadd sp,

HI '\

Page 156: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

The wo rd modifier is required because C8S allocates variables in bytes rather thanwords, double-words,.... The add sp; removes the words that were pushed asparameters to zip . Note that C8S appended' ' to names. If there had been nolocal varables defined in the callng function, the clean-up code would have been

mov

which is faster.

sp, bp

Data is pushed on the stack as follows:

char

intunsigned

long

float

double

pushed as a word, with high-order byte set to zeromov AL, datamov AR,push AX

pushed as a wordpush WORD data

pushed as two words, with least-significant word pushedlast

push WORD data (2Jpush WORD data (OJ

Changed to doub 1 e and pushed with least-significantword pushed last

mov si, offsetmov ax, mov es, axPUBLIC FLOADECALL FLOADEPUBLIC FPUSH

. CALL FPUSH

data; Large Case only; es:si -)0 float; load float

; push double

pushed as four words with least-significant word pushedlast

push WORD data (6Jpush WORD data (4 J

push WORD data (2 J

push WORD data

10.

Page 157: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSIDIO Librar

struet push (sizeof (struet) 1) ;:;: 1 words, withleast-significant word pushed last.

mov ex, nn ; size in wordssub sp, ex ; make room on stackmov di, sp ; targetmov si, offset data ; source; set up ds for memory modelmov ax, ss ; setupmov es, ax eld ; set direction uprep movsw ; copy to stack

Small Case memory model - 2-byte pointer

push WORD pointer

Lage Case memory model - 4-byte pointer

push WORD pointer (2Jpush WORD pointer

The usual preamble for a called function is

PUBLIC fnamefname :

push bpmov bp,

; save old frame pointer; establish local frame

For functions that d. return strctures, pareters begin in the local frae (ARGS _J , and continue upward based on the size of each pareter. Thus for thefragment

blip (x, y, int x;long y;double z;

the parameters would be referenced in Assembler as

movmovmovlea

ex, WORD (ARGSax, WORD (ARGS +2Jdx, WORD (ARGS- +4 J

si, (ARGS- +6 J

; x; lsw of y; msw of y; addr 0 f z

HI '7

Page 158: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

For functions that return strctures, (ARGS _J contans a pointer to where thestrcture should be returned, and the arguments begin at (SARG -). So if the abovefragment was

struct foo blip (x, y, the parameters would be

movmovmovlea

cx, WORD (SARG":.Jax, WORD (SARG- +2)dx, WORD (SARG- +4)si, (SARG +6)

; x; lsw of y; msw of y; addr of z SS :SI

Local varables are allocated below the current frame pointer regardless of thememory model or what the fuction return, so that the fragment

int aa(2);long b;

would be referenced as

submovmov

sp,ax, (bp-4 J

dx, (bp-8

; allocate space for locals; aa - ( 1 J

; msw b

The stadad exit sequence is

movpopRET

sp, bp ; reclaim any local space; old frame pointer; caller will clean up stack

Values are returned from functions according to the following table

charintunsigned

returned in AX. char values are returned in AL with AHset to zero

long

doublefloat

returned in DX : AX. (AX contains lsw)

returned on floating point stack (s/w or 8087).

10.

Page 159: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIQ Libra

struet returned to address in (ARGS

Small Case memory model- returned in AXLarge Case memory model- returned in ES:SI.

Memory Management

Function

The Memory management functions are:

eaIIoe ()free ()freeall malloe ()reaIIoe ()

Allocates a block of data and clear it to zeroesMarks a block of data as available for allocation

, Intializes the free memory areaAllocates a block of dataResizes an existig allocated block of data

The Small Case memory model data segment looks like

mallocO Area

Global Data Area

Figure 10-

Small Case memory management

showspO

memoryO

DS,low memory

Page 160: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

The default stack exansion area is 1024 bytes. The size of the area is fixed

freeall () , specifying the size of the area. Note that freeall () releases allallocated storage in themalloc() area, so in general it is best to call freeall prior to any malloc () or calloc () calls.

The malloc() area is divided into blocks with the following format:

struct fchar status;unsigned size;char data (1) ;'

status is one of: allocated (OxA), unallocated(Ox9D), or end-of-area marker(OxC6). size is the size of data in bytes. The address of data is returned by malloccalloc, and realloc and used by free.

The following function prits out a map of the memory allocation area.

#define UNALL Ox9D#define ALLOC OxA#define EOA OxC6

printMap () fchar *cp, * memory();struct f

char status;unsigned size;char data (1) ;J ;

cp = _memory () ;while (cp- status ! = EOA) f

printf (" %5u %2salloc bytes at %u\ncp- size,cp- status == ALLOC ? ""

: "

cp) ;cp = cp- data + cp- size;

free marks a block as unallocated. malloc searches the allocation area in orderfrom bottom to top. '

10.1 0

Page 161: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Librar

Thus in the following fragment

fp = malloe (size) ;free(fp)inp = malloe (size) ;

fp may not equal np .

In the Lage Case memory model, malloe (), ealloe (), realloe (), andfree () use the DOS memory management facilties.

Input/Output Librar

The YO routines work at different levels. Directory level functions manage theDOS 2 and later directory strcture. File level functions manage $e contents ofdirectories. Stream level fuction access fies as a sequence of bytes. Handle levelfuction manage fies as blocks of data.

Screen level functions simplif the interface between C progras and the IBM-and its clones. Console level fuctions read and write to the console.

Directorv Level Functions.

Directory level functions manage the DOS 2 and later directory strcture.Each of the function works on a directory specified by a pathame.

Function

ehdir ()getdir ()mkdir ()rmdi r ()

Changes the currnt workig directoryReturns the pathame of the current working directoryCreates a new directoryDeletes an existing directory

File Level Functions

File level functions manage the contents of directories. Each fuction works on afie identified by a pathame or fie handle.

Function

ehmod ( )filelength

Changes the fie attrbutesReturns the length of the indicated fie

Page 162: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

isatty locking ()rename ()unlink ()

Stream Level Functions

The CSTDIO Libra

Tests if the fie is a charcter deviceLocks par of a fie (MSDOS 3.0 and later)Changes the nae of a fieDeletes an existing fie

Stream level function access fies as a sequence of bytes. They buffer the data readfrom and written to disk fies in private stomge areas. They use a pointer to a FILE(defmed in st di 0 . h) to associate a stram with the pathame of the fie.

Function

fclose ()fflush ()fgetc ()fgets ()fileno fopen ( fpri.ntf fputc ()fputs ()fread ( freopen ()fscanf ()fseek ()ftell fwrite ()get c ()get char ()get w ()printf putc ()put char ()puts ()putw ()rewind ()scanf ()sprintf sscanf ()ungetc ()

Closes a streamWrites buffered data out to disk fieReads a charcter from a stream

Reads a strg from a streamRetus the fIe handle of a streamOpens a streamWrites formatted strng to streamWrites a charcter to a stream

Writes a strg to a streamReads a block of data from a streamRedirects a FIE pointerReads formatted data from a streamPositions a stram at a specifc charcterRetu the position of a streamWrites a block of data to a streamReads a charcter from a stream

Reads a charcter from stdinReads an int from a streaWrites formatted strg to stdoutWrites a charcter to a stramWrites a charcter to stdoutWrites a strg to a straQWrites an int to a stramPositions a stream to the begining of the fieReads formatted data from stdinWrites formatted strng to a strngReads formatted data from a strng

Pushes one charcter back into a stream

10.12

Page 163: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

There are five predefined streams available for reading o writing. They donhave to be opened before, or closed after use. To refer to them, use the followingpredefined FILE pointers (defined in stdio. h):

Stream

stdinstdoutstderrstdauxstdptr

keyboard, can be redirecteddisplay, can be redirec:teddisplay, can J1 be redirectedCOMlLPl

Handle I,eve1 Functions

Handle level functions manage fies as blocks of data. They do not buffer or formatthe data. They use an int to associate a fie handle with a pathame.

Function

close ()creat ()dup ( )dup2 ( )lseek ()open ( read ( write ()

Closes a fIe

Creates and opens a fie

Makes another handle for a fie

Redicts a haePositions a fie at a given locationOpens a fieReads a block of data from a fie

Writes a block of data to a fie

The maxum number of handles that can be open at one tie is either 20, ' or thenumber specified in CONFG.SYS, whichever is less. See Installing the Softwaresection of Chapter 2 for detals about CONFIG.SYS.

Screen Level Functions

Screen level functions simplify the interface between C progras and the IBM-and its clones. These routies are not in the stadard CSTDIO.S librar but aredistrbuted in source form in the fie PCIO.A. To use these routines, they must beassembled and bound in. For example:

A::asm88 b:pcioA::bind b:blip b:pcio

'In ....

Page 164: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Librar

See the comments in the IBM Technical Reference Manual for detals on the BIOSinterface used by PCIO.

See the LIB88 chapter for detals on installng PCIO.O in CSTDIO.

Function

scr aputs ()scr ci ()scr co ()scr csts ()scr clr ()scr clrl scr cls ()scr cursoff ()scr curson ()scr rowcol ()scr scdn ()scr scrdn ()scr scrup ()scr scup ()scr setmode ()scr setup ()scr sinp ()

Console Level Functions

Writes a strig to the screen with a specified attrbuteReads a character from the keyboardWrites a charcter to the displayTests for the availabilty of keyboard dataErases the entire screenErases from the cursor to end-of-lineErases from the cursor to end-of-screenTurns the cursor offTurns the cursor onMoves the cursor to the specified row and columnScrolls the screen down 1 line, staing at line 3Scrlls an ara of the screen down 1 lineScrlls an ara of the screen up 1 lineScrll the scen up 1 line, saving lines 1 and 2Chge the mode of the CGAIntialize the screen level fuctionsReads the charcter at the currnt cursor location

Function

Console level functions read and write to the console. They may be redirected.

ci ()co ()csts ()

Reads a charcter from the keyboard, no echo

Writes a charcter to the displayTests for keyboard input

10.

Page 165: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Math Librar

The CSTDIO Libra

If any of the trscendental or sqrtO functions are used, include the fie math. h orthe equivalent declartions to specify them as returning a double.

Function

abs ( )acos ()as in ()atan ()ceil ()cos ( exp ( )fabs ()floor ()frexp ()labs ()ldexp ( log ( modf ( pow ( )sin ()tan ()

Absolute value of intArc-cosine of radian argumentAr-sine of radian argumentArc-tagent of radian argumentReturn ceiling of its argumeCosine of radian arguentExponential fuction

. Absolute value of doubleRetu floor of its argumentDisassembles a doubleAbsolute value of longAssembles a doubleLog functionDecomposes a doublePower functionSine of radian argumentTangent of radian argument

ma t h . h includes the statement

extern int errnOi

errno is set to a non-zero value when: a floating point stack elTors, an argument toa math routine is out of range, or the result of a math routine wouldunder/oveIfow. ElTor codes and names (defined in math. h) are:

ESTK FIP stack oveIfow. The most probable cause is callng afunction that returns a double without declaring it as such to thecompiler. After eight calls, the flp stack wil be full.

EDOM invalid argument, i.e., sqrt( - 0).

ERAGE :. result would under/oveIfow, i.e., ta(PI/2.0).

..

1\

..

Page 166: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Librar

The function rerrno () is called by the floating point routines whenever an erroris detected. rerrno () prints out an appropriate error message and calls exit

( ) .

In order to bypass this effect, install the following function in your program

rerrno () (; J /* null function to suppress printing */

SYSTEM INTERFACE

The System Interface provides access to low-level DOS and BIOS functions.

Function

chain ( exec ( doint ()os ()

Transfers control to another .EXE fie, no returnTrasfers control to another .EXE fieInvokes a 8088 interrpt

Invokes simple DOS interrpt (21H)

chain and exec wil load and execute an arbitr progra. exec returns controlto your progra, chain does not. You specify the complete pathe of theprogra (including the .EXE or .COM suffix) and the arguments to the progra.chain and exec are in the EXEC.O fie provided on the distrbution disks.

exec wil return the completion code from the progra or -1 if an error occurredloading the progra. Completion codes ar set for progras running under DOS

0 or later versions of the operating system. If a progra exits with

exit (n)

the system ERRORLEVEL wil be set to n. , A progra that returns from the mainfunction other than by exit () sets ERRORLEVEL to zero. ERRORLEVEL canbe tested with the DOS batch fie IF command. See the section under ' BATCH' inthe DOS manual for detals on the IF command.

To invoke a Batch fie, or a DOS built-in command, use COMMAN.COM with theswitch as follows:

char shell(128);

getenv (" COMSPEC" , shell);exec (shell, " cxxx

) ;

10.16

Page 167: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

, The CSTDIO Libra

where.x is one of the DOS built-in commands ( 'dir

, '

copy

, ...

) or the name of abatch fie, including the traling .BA T.

exec (shell, " /cc:\\autoexec. bat"

Remember that two backslashes are required to insert a single backslash in a string.

Invoking COMMAN. COM with no pareters wil star another DOS shell (likeF9 in SEE). To return, enter at the command prompt

exit

C88 normally allocates a stak as large as possible. Ths is not desirable when usingexec as litte memory may be left for the second program. The -Shhhh option ofthe BIN progr should be used to reduce the size of the stack and consequentlythe size of the progra. Remember tht the hh value of the option is in andthat it must be large enough for al pareters and locals active at one time. Anextr OxlOO (256) bytes should also be added for any system calls.

chain loads the new progr physicaly above itself in memory so stack size isirelevant. chain is contaed in the EXEC.O fie on your distribution disk. Whenusing chain EXEC.O should be the ftrst pareter to BIN

BIND EXEC progName -oprogName

One way to pass data via exec to another progr is to pass a pointer to data block.The driver progra for a menu progra could be:

struct data int anydata;

char nextMenu (13) ;) comArea;

main () (char parms (1 OJ;

strcpy (comArea . nextMenu, "MENUl. EXE"sprintf (parms, " %u %u

, _

showds (), &comArea);while (exec (comArea . nexMenu, parms)

Page 168: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSIDIO Libra

Each menu program copies comArea, as follows:

struct data int anydata;

char nextMenu (13 J ;) comArea;

main (argc, argv)char *argv (J ; (

unsigned seg, off; /* driver comArea */

sscanf(argv(l), %u %u &seg, &off);lmove (sizeof (struct data),

off, seg, &comArea, showds());/* process menu *

/ -

strcpy (c.omArea . nextMenu, " MENU2 . EXE) ;1 move (s izeof (struct data),

&comArea, _showds (), off, seg);exit (1); /* zero return terminates driver */

- doint wil cause software interrpt inum and may be used to call whateverrouties are available in the parcular machine. The values of the registers can bespecified before, and read afer, the call to - doint .

os provides an elementa interface to the BIOS. inum goes into AH and arg into, and an int 21H is executed.

10.18

Page 169: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

ENVIRONMENT

The function called by the starp code is named main. There is no predefined

prototype for this function. It can be defined with no parameters:

int .main (void)

or with two parameters (refered to here as argc and argv, though any names may beused, as they are local to the function in which they are declared):

int main (unsigned argc, char * argv ())

or with three parameters:

int main (unsigned argc, char * argv (), char * envp)

If they are defined, the paramters of main have the following characteristics:

argc is non-zero,

argv (argc) is a null pointer

argv (0) though argv (argc-l) contain pointers to strings, which are

portions of the command line arguments used to invoke the program. Thestrings consist of chacter sequences that do not contain whitespace,

under DOS 3, argv (0) conatins a pointer to the name that was used toinvoke the program. Under DOS 1 and DOS 2, argv (0) is a null pointer

envp is a pointer to the DOS environment string. In small.,case, envp is

the segment number of the environment strng use _peek () orlmove () to access the strng. In large-case, envp is a pointer to the

string.

In addition, the following envrionmental variables are available:

extern unsigned environ contains the paragraph number of theenvironment string

extern unsigned version contains the current DOS version, withthe major release number in the low-order byte, and the minor number inthe high-order byte.

10. 18-

Page 170: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

extern char _osmajor contains the major DOS release number.

extern char' osminor contains the minor DOS release number.

extern uns igned -psp contains the paragraph number of theProgram Segment Prefix (PSP).

LIBRARY

Each library function is declared in a header, whose contents are made available viathe # in c 1 u de preprocessing directive. The header declares a set of relatedfunctions, plus any necessary types and additional macros needed to faciltate theiruse. All external identifiers declared in any of the headers are reserved, whether ornot the associated header is included. All external identifiers and macro names thatbegin with an underscore are also reserved.

The following section describes the headers, and their associated functions, in ageneral way. Following that is a description of each function argedalphabetically.

Headers

as sert . h This header defines the ass e rt macro and refers to anothermacro, NDEBUG, which is not defined by ':assert. h::. IfNDEBUG is defined as amacro name at the point in the source file Where -(assert. h:: is included, themacro has no replacement text, as in

# if defined NDEBUG# define assert (expr)# endi f

ctype. h This header defines several macro implementations of charactertesting and mapping functions. The macros defined, which are also available asfunctions, are:

isalnum (int)isalpha (int)iscntrl (int)isdigit (int)

is graph (int)islower (int)isprint (int)

ispunct (int) isxdigit (int)isspace (int) tolower (int)isupper (int) toupper (int)

10. 18-

Page 171: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

th . h This header declares several mathematical functions and defines threemacros. The functions take double arguments and return double values.

The macros defined are EDOM, ERANGE , and HUGE VAL .

The trignometric functions are:

acos ()asin ()

atan ()atan2 ()

cos ()sin ()

tan ()

The exponential and logarthic functiona are:

exp ()log ()

ldexp ()modf()

loglO () frexp ()

The power functions are: pow ( sqrt ()

The miscellaneous functions are

ceil fabs () floor

setjmp. h This header declares two functions and one type, for bypassing thenormal function call and return discipline.

The type declared is jmp - bu f which is an array type used to restore a callngenvironment.

The functions are: longjmp () set jmp ()

stdarq. h This header declares a type and defines thee macros, foradvancing though a list of arguments whose number and types are not known atcompile time. The type declared is va list which is used to accessing the arguments.

The macros are: start () arg () end ()

10. 18-

Page 172: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

":stdio This header declares two types , several macros, and many functionsfor performing input and output.

The types are FILE which is an object describing a stream, and fpos t which is anobject describing a location within a fie. '

The macros are:

EOFERRFALSENULL

SEEK CURSEEK ENDSEEK SETstdin

The fie, operation functions are:

remove ( rename (

The file access functions are:

fclose () fflush

The formatted input/output functions are:

fprintf sprintf

fscanf ()sscanf ()

The character input/output functions are:

fgetc ()get c ()putchar ()

fgets ()getchar ()put s ()

The direct input/output functions are:

fread () fwrite

The fie positioning functions are:

fseek () ftell

10. 18-

stdoutstderrstdauxstdprn

fopen ()

print f

fputc ()gets ()ungetc ()

rewind ()

clearerrfeofferror

freopen ()

scanf ()

fput s ()putc ()

Page 173: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

stdlib . This header declares two types and several functions of generalutilty, and defines four macros.

The macros are ERANGE, HUGE VAL, and RAND _MAX.

The string conversion functions are:

atof ()atoi ()

atol ()itoa ()

strtod 0ltoa ()

strtol

The pseudo-random sequence generator functions are:

rand () srand ()

The memory management functions are:

ealloe () free () malloe () realloe ()

The DOS communication functions are:

abort ( atexit

exit getenv () system ()

The searching and sorting functions are: bseareh () qsort ()

The integer arithmetic functions are:

abs () labs ()

10.18-

Page 174: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

.cstring. This header declares several functions for manipulating characterarrays.

The copying functions are:

memecpyOstrncpy ()

memcpy ( memmove ( ) strcpy (

The concatenation functions are:

strcat strncat

The comparison functions are:

memcmp ( ) strcmp () strncmp ()

The search functions are:

memchr ( strchr ()

strcspn ()strpbrk ()

strrchr strspn ()

strstr strtok ()

The miscellaneous functions are:

memset () strlen

10.18-

Page 175: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Library

abortvoid abort (void)

abort prints the message

Abnormal program termination

to stderr, and then exits to DOS.

abort does not return to the caller. A return-code of 3 is returnedto DOS.

FILE *mustopen (char *name, char *mode) tFILE *fdi

if ( (fd = fop en (name, mode)) == NULL) tprintf (" can I t open %s , name)

abort ()

return fdi

10.

Page 176: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Library

abs#include stdlib.

int abs (int n)

abs computes the absolute value of n..

abs returns the int absolute value of its integer argument. Thereare no error values.

fabs (), labs

int x;

if (x ! = abs (x) )puts (" negative

1 0.20

Page 177: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Library

accessint access (char *path, int mode)

The access function tests for the existence of the file specified bypath and whether it can be accessed in mode. The values andmeanings of mode are:

Value Meaning

Check for existence onlyWrite accessRead accessRead and write access

mode 0 and 4 produce the same result, since all DOS fies have readaccess. mode 2 and 6 produce the same result for the same reason.

access returns 0 if the file can be accessed with the specified mode.

access returns - 1 if path doesn t exist or can t be accessed in thespecified mode.

char comspec (65) ;

getenv (" COMSPEC" , comspec, sizeof (comspec) ) ;if (access (comspec, 0))

puts ("whoops, command. com is missingabort ();

10.

Page 178: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Library

aeos#inc1ude math. h

doub1e acos (doub1e x)

acos computes the arc-cosine of in the range 0 to 1t. must be

between - 1.0 and 1.0.

acos returns the arc-cosine of its argument. acos returns 0.0 andsets errno to EDOM for :; 1.0 or 0: - 1.0.

#include O:math. h:;double x, y;

if(x 0: -1.0 II x:; 1.0)pr int f (" %g is invalid

elsey = acos (x) ;

acos () argument \n " , x);

10.

Page 179: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Library

asin#include math.

double asin (double x)

asin computes arc-sin of in the range -1t/2 to 1t/2. x must bebetween 1.0 and -

asin returns the arc-sine of its ' argument. asin returns 0.0 and setserrno to EDOM for )0 1.0 or 0: - 1.0.

#include O:math. h)odouble x, y;

if (x 0: -1.0 II x )0 1.0)printf(" %g is invalid

elsey = asin (x) ;

asinO argument\n , x);

1 0.22-

Page 180: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

assert#include assert .

void assert (expr)

assert prints a diagnostic message and terminates the program ifexpr evaluates to 0 (FALSE). The message has the followingformat:

Assertion (expr) failed: file name, line number

name is the name of the source fie containing the assert macro.number is the line number of the assert macro in name.

The # 1 ine preprocessor directive can alter both name andnumber.

No action is taken if expr evaluates to non-zero (TRUE).

If the macro name NDEBUG has been defined, the preprocessorremoves all assert macros from the source fie.

RETURNS: There is no return value.

EXAMPLE: #include assert. h#include math. h

double tasin (double x)

assert (x = -1. 0 && x = 1. 0);return asin (x) ;

10.22-

Page 181: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Library

atan -- atan2#inc1ude th. h

doub1e,atan (doub1ex)

doub1e atan2 (doub1e x doub1e y);

atan computes the arc tangent of in the range of -1t/ 2 to 1t/ 2.

atan2 computes the arc tangent of y I x in the range of -1t to 1t.

atan and atan2 returns the arc tangent of their argument(s). Ifbotharguments of atan2 are zero, the function sets errno is EDOM and

returns 0 . o.

** return arc tangent in degrees

#include math. h/

extern double PI;

double atan deg (x)double x;

return atan (x) * 180 / PI;

10.22-

Page 182: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

atexit#include stdlib. h

int atexit (void (*func) (void)) ;

atexit registers the function pointed to by func , to be called withoutarguments at normal progra termination.

Up to 32 functions may be registered.

RETURNS: atexit returns 0 if the function was registered, non-zero otherwise.

EXAMPLE: #include stdio. h

#include stdlib. h

/* send eof message to remote */

void eop (void)

fputc (EOF, stdaux);

main ()

if (atexit (eop))

puts (" at exit ()abort ();

error

) ;

10.22-

Page 183: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

, SEE ALSO:

EXAMPLE:

The CSTDIO Libra

at01#include th. h

double atof (cp)char cp

() ;

atof convert the char amY at cp to a double. The firstunecognized character teIminates the conversion. There is I! testfor overfow.

whites pace is either a tab or a space. A digit is an ASCII charcter0' though ' is either an ASCII 'E' or ' . () delimitsequences that ca occur zero or one time. f)- delimit sequences thatcan occur zero or many ties.

Valid character Sequences

fwhitespace H - Hdigit J('.')(fdigit HE

(-

Hdigit)-JJ

atof returns the floatig-point representation of the strng cp , or0 if the strg couldn t be converted. There are no error values.

scanf ()

/* floating-point scanner *

clude math. h

double scand

() (

charbuf(80);

gets (buf) ; /* allow line editing * return atof (buf) ;

1 0 'J

Page 184: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

ataiint atoi (cp)char cp

() ;

atoi convert the char ary at cp to anint. The firstunrecognized character terminates the conversion. There is

Jl testfor overfow.

whites pace is either a tab or a space. A digit is an ASCII charcter0' though ' . (J delimit sequences that can occur zero or one time.

delimit sequences that can occur zero or many times.

Valid character Seqpence

whites pace J (- J t digit

RETURS: atoi retirn the integer representation of the strg cp, or 0 it thestrig couldn t be converted. There are no error values.

SEE ALSO: atol (), scanf

NOTES: To guard against int overfow, or large uns igned values beingstored as negative integers, use ato/ and check that the high-orderword is the same as the high-order bit of the low-order word.

#include math.

atoi (str)char * str;

long val, atol

() ;

unsigned sign, extn;extern int errno;

extn = (val = atol (str)) 16;sign = val & Ox8000;if((!sign && extn !=

II (sign && extn != -1))rerrno (errno = ERANGE);

return val;

10.

Page 185: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Librar

,atol#include th. h

long a.to,l(cp)cha.r cp () ;

atol converts the char array at cp to a long. The firstunrecognized character terminates the conversion. There is testfor overfow.

whites pace is either a tab or a space. A digit is an ASCII character0' though ' . () delimit sequences that can,occur zero or one time.D delimit sequences that can occur zero or many times.

Valid character Sequences

-(

whites pace J (- J -(digit

atol returns the integer representation of the string cp , or OL if thestring couldn't be converted. There are no error values.

scanf ()

See atoi

10.

Page 186: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

bsearch#include stdlib. h

void *bsearch (const void *key,const void *base,size t nmem, size t size,int (*cmp) (void* , void*) );

bsearch searches an array of nmemb objects, the initial member ofwhich is pointed to by base for a member that matches the objectpointed to by base. The size of each object is specified by size.

The array must be in ascending sorted order according to acomparison function pointed to by cmp, which is called with twoarguments that point to the objects being compared. cmp shouldreturn one of the following values:

Value Meaning

-(0

)-0

first argument is less than second argumentfirst argument is equal to second argumentfirst argument is greater than second argument

RETURNS: bsearch returns a pointer to the matching member of the arry, or aNULL pointer if no match is found.

EXAMPLE: #include -(stdlib h)-#include -(string. h)-

struct kwords ( char *name; short value; kwords (J =

( ...

#define SZKWD sizeof (struct kwords)#define NKWDS sizeof (kwords) /SZKWD

int cmp (struct kwords *1, struct kwords *r) return strcmp (l-)-name, r-)-name);

#define kwlook

(p) \

bsearch ( (p), kwords, NKWDS, SZKWD, cmp)

10.26

Page 187: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Librar

calloc#include stdlib. h

char *calloc(unsigned num, unsigned size)

calloc allocates a block of num size bytes. Each byte in the blockis set to OxOO.

See the Memory Management discussion of the memoryallocation functions.

calloc returns a pointer to the allocated block, or NULL if itcouldn t allocate the memory.

free (), freeall (), malloc (), realloc

1* set up float array

float *farraYi

if(!(farray = calloc(500, sizeof(float))))error nb room for farray

10.26-

Page 188: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

The CSTDIO Library

clearerr#include stdio.

void clearerr (FILE *stream);

clearerr clears the end-of-fie and error indicators for stream.These indicators are cleared only when the fie is Qpened or by anexplicit call to clearerr or rewind.

clearerr returns no value.

clearerr is a macro.

#include stdio. h

int output (FILE *fp, char c)

if (fputc (c, fp) == EOF && ferror (fp))

fputs(" write error\n , stderr);clearerr (fp) ;

10.26-

Page 189: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

ceil#include th.

double ceil ex)double x;

ceil return a double with the smallest integer value greater thanor equal to x.

ceil returns the ceiling of x. There are no error values.

Note that ceil (-1., 5) == -1.0, not -

floor (), fmod

/ * round away from zero *

.include math.

double rndfrO (x)double x: (

if (x

return -ceil (fabs (x) return ceil x;

Page 190: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Library

chainvoid chain (filename, commndTail)char filename ()" conuandTail

() ;

chain functions like exec except that control is nQ returned to thecalling program. chain is in EXEC.O on the distrbution disk. Itshould be bound in first to save memory since it loads the calledprogra immediately behind itself. For example:

BIND EXEC BLIP -OBLIP

See the discussion in System Interface for more information onchain.

chain does not return.

exec ()

/* link to assembler** assemble file myprog. a in current directory** use large case flag

chain (" c: \\c88\\asm88. exe myprog b"

) ;

10.

Page 191: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

NOTE:

EXAMPLE:

The CSTDIO Libra

chdirint chdir (pathname)char pathname

() ;

chdir changes the CUITent working directory to pathname.pathname must exist and be a directory.

chdir returns a 0 if successful, or - 1 if it fails.

pathname is of the form (drive:) (path ). Either, or bothcomponents may be specified.

REMEMBER": the backslash "\" is the escape character in C. you ar specifing pathname at COMPILE time, use twobackslashes.

chdir(" c:\\c88"

) ;

Since DOS accepts eith ! a slash or a backs lash as a path separtorthe following is equivalent.

chdir(" c:/c88"

) ;

If the pathname is entered at RUN tie, only a single slash orbackslash is needed.

char path (128);

puts ("Enter New Directory -gets (path) ;if (strlen (path)

if (chdir(path) != 0)patherror (path) ;

Page 192: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

chmod#include dos .

int chmod(filename, mode)char filename r) int mode;

chmod changes the attrbutes of filename as specified by mode.filename must exist.

mode is a value contag a zero or one or both of the constatsCHDIR READONLY and CHDIR HIDDEN specified in dos.h. Bothconstats can be specified as CHDIR READONLY+CHDIR HIDDEN.

Writable dden

yesCHDIR READONLY

CHDIR HIDDEN yes yesCHDIR READONLY+ yesCHDIR HIDDEN

RETURS: chdir returns a 0 if successful, or - 1 if filename could not be found.

EXAMPLE: /* program to hide files** run as hide fn fn

...

#include dos .

main (argc, argv)char *argv () ; (int i;

for(i = 1; argc; i++)hdir (argv (i), CHDI HIDDEN);

10.

Page 193: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

SEE ALSO:

NOTES:

EXAMPLE:

The CSTDIO Library

char ci ()

ci reads the next character from the keyboard. If one is not

available ci waits until one is entered. The character is not echoedto the display, and is ll retained for future access via get c (

) ....

Input to ci can be redirected.

There is no check for Cf-

csts (), get char (), scr ci ()

ci returns a zero as the first character of an extended key sequenceand returns the extended key code on the next call.

To decode an extended key sequence, use s cr - c i ( ). It maps theextended key sequences into char values between Ox80 and OxFF.See the CONFG.C and PCIO.A fies for the mapping.

/* get password from kybd

void getpass (word, Ien)char word (J ;int Ien;

char *cp = word;

whiIe(len-- && (* cp++ = ci())

!=

\r '

cp = ' \0'

11' ...,

Page 194: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Librar

closeint c10se (hand1e)int hand1e;

close writes any buffered data for the fie associated with handle

that fie, and closes the fie.

RETURNS: close returns -1 if han dl e is invalid, not open, or if an erroroccurred writing the buffered data to that fie.

SEE ALSO: closeall (), creat (), dup(), dup2 (), open

EXAMPLE: /* copy file to console */

main (argc, argv)char * argv () ; t

int fd, 'sz;char buf (2048), *bp;

if ( (fd = open (argv ( 1 ), 0)) == 0) tprintf(" can t open %s , argv(l));exit (1)

while(sz = read(fd, buf, sizeof(buf)))for(bp = buf; sz; sz--)

co (*bp++) ;close (fd) ;

10.

Page 195: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

closeallint closeall

closeall flushes all buffers and closes all open fies.

closeall returns -1 if an error occurred closing any fie.

close (), creat (), dup (), dup2

( ),

open ()

/* fatal error routine *

#include stdio .

void fatal (msg, ret)char *msg; t

fputs (msg, stderr);closeall

() ;

exit (ret) ;

10.

Page 196: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

SEE ALSO:

EXAMPLE:

The CSTDIO Library

void co (ch)char ch;

co writes the charcter ch on the screen at the current cursorposition. The cursor is advanced to the next position on the screen.There is no automatic conversion of the newline character \ n intothe \ r \ n (carage return, line feed) sequence needed by the screendriver.

co output can be redirected.

No test for Cf-C is performed.

putchar(), scr co()

/* puts() equivalent */

void puts (string)char *string; (

char ch;

while (ch = *string) (if(ch == '

co('co (* string++) ;

10.

Page 197: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

cos#include th.

double cos ex)double x;

cos computes the cosine of its radian argument x. The meangfulness of the result depends upon the magnitude of theargument.

cos returns the cosine of x. There are no error values.

acos (), asin (), atan (), sin (), tan

/* cos with degree argument */

iinclude math. h

extern double PI;

double dcos (x)double x; (

return cos ((PI + PI) * x);

10.35

Page 198: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

NOTE:

EXAMPLE:

TheCSTDIO Libra,

creatint creat (name) ;char *name;

creat creates the fie name. If name doesn t exist, a new fie iscreated. If the fie exists, its contents are deleted.

The fie is opened in update mode so that after the fie is written, aprogra can seek to its begining and read it without closing the fieand reopening it.

creat returns an handle that is used to reference the fie in futureoperations, or -1 if the fie couldn t be opened.

dup (), dup2

( ),

open

creat can open the console (" CON" ), the serial port (" AUX" ), orthe priter ("PRN"

int fd;

if((fd = creat(" c:\\temp1" )) == -1)fatal(" can t create temp1" , 5);

10.

Page 199: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

SEE ALSO:

NOTES:

EXAMPLE:

The CSTDIO Libra

cstschar csts () ;

csts is similar to ci except that if no character has been typed in, itwil return zero instead of waiting for a character from thekeyboard.

The charcter is retaed and wil be returned by the next call to ci.

get char (), scr ci (), scr csts ()

csts returns a zero as the first character of an extended keysequence, and returns the extended key code on the next call.

In order to decode an ext nded key sequence, use scr csts (). Itmaps the extended key sequences into char values between Ox80and OxFF. See the fies CONFG.C and PCIO.A for the mapping.

csts leaves the charcter in the input queue. Use ci or getchar

read it.

/* empty the input queue

** note - doesn' t work for extended key' codes

**

use scr csts ()

void emptYKbd

() (

while (csts () ciO;

10.

Page 200: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Library

datesvoid dates (buf) ;char buf r 9J ;

dates formats the strng buf with the current date as mml dd/ yy

If mm or dd are less than 10, they wil be formated with a space(0x20) as their first charcter.

dates doesn t return a value.

ct ime ()

1* current date

char * currdate () (static char cdate (9);

if (cdate (OJ == 0)dates (cdate) ;

return cdate;

10.38

Page 201: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Librar

dup - dup2int dup (filel)int filel;int dup2(filel, file2)int filel, file2;

dup creates a second fie handle for the open file filel. Either

handle can be used to operate on the fie.

dup2 forces file2 to refer to the same fie as filel. If file2 refersto an open fie, that fie is closed.

dup returns the new fie handle, or - 1 if an error occurs.

dup2 returns 0, or - 1 if an error occurs. .

close (), creat (), open

1* redirected i/o *1

*include stdio.

int printer, fno;char pname (32 J ;

sprintf (pname, " c: \\spool\\F%d . pfl" , fno++);if ((printer = creat (pname)) == -1)fatal (" can t allocate printer , 1);

if (dup2 (printer, stdout))fatal(" can t redirect to printer , 2);

exec (command, parms);close (printer) ;

10.

Page 202: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

execchar exec (filespec, commandTail)char filespec (), commndTail () ;

exec loads and executes an arbitrar program -filespec is thecomplete pathname of the program (including the .EXE or .COM'extension). commanaFail contains the arguments to the program.exec is in the EXEC.O fie provided on the distribution disks.

RETURNS: exec returns the completion code from the program, or - 1 if anerror occurred loading the progra. Completion codes are set forprogras running under DOS 2. 0 ,or greater. If a program exitswith

exit (n)

the system ERRORLEVEL wil be set to n. A progra that returnsfrom the main function other than by exi t () sets ERRORLEVELto zero. ERRORLEVEL can be tested with the DOS batch fie IFcommand. See the section under 'BATCH' in the DOS manual fordetals on the IF command.

SEE ALSO: chain (), exit

EXAMPLE:** invoke command. com to process batch file

** use Ic switch

dobatch (fname)char fname ( J ; (

char shell(64J, parms(l28J;

if (getenv ("COMSPEC" , shell)return 256; 1* getenv()

strcpy(parms,

strcat (parms, fname);return exec (shell, parms);

== 0)error *

10.40

Page 203: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

NOTE:

EXAMPLE:

The CSTDIO Library

exit

void exit (code)char code;

exit terminates the calling process and sets the completion code.main () can also exit with a completion code of zero by " fallingthough the end of the function.

Only the low-order byte of code is used.

ext does Il close open fies.

exit does not return.

exec (), chain

Completion codes are set for progras running under DOS 2.0 orgreater. If a program exits with

exit (n) ;

the system ERRORLEVEL is set to n. A progra that returnsfrom the main function other than by exit sets ERRORLEVEL tozero. ERRORLEVEL can be tested with the DOS batch fie IFcommand. See the section under ' BATCH' in the DOS manual fordetals on the IF command.

/ * fatal error dler *

#include stdio.

fatal (msg, level)char *msg, level; (

fputs (msg, stderr);exit (level) ;

1 ().11

Page 204: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSIDIO Library

exp, exp10

"include th.double exp ex)double x;

double explO ex)double x;

exp returns the exponential function of x; expJO returns the base10 exponent.

ex returns

exJO returns lOx

Both return a very large value when the result would overfow;errno is set to ERAGE.

log (), loglO

#include math.

double X;

X = exp (x) ;if (errno = ERANGE)

puts ("This isnelse

printf(" %f" , x);

a GRAY II\n

1 0.42

Page 205: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Library

fabs#include th.

double fabs (x)double x;

fabs computes the absolute value of x .

fabs returns the absolute value of its double argument. There areno error codes set.

abs (), labs

iinclude math. h

double Xi

if(x != fabs (x))puts ("negative

10.43

Page 206: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

fclose#include stdio. h

int fclose (fp) ;FILE *fp;

fclose writes any buffered data for the fie fp to that fie andcloses the fie

RETURNS: fclose returns 0 , or - 1 if fp is not open or if an error occurredwriting the buffered data to that fie.

SEE ALSO: close(), fflush(), fopen(), freopen()EXAMPLE: /* file copy */

include stdio. h

static fatal (msg, level)char *msg, level;!

fputs (m g, stderr);exit (level);

main (argc, argv)char * argv () ; (

char buf(I024);FILE *ip, *op;

if(argc != 3) (fatal(" Usage: copy name name\n , 1);

if ( * a rgv ( 1 )

== '

ip = stdin;else if (ip = fopen(argv(l), " )) == NULL)

fatal (" can t open input file , 2);if(*argv(2) == '

op = stdout;else if((ip = fopen(argv(2j, " )) == NULL)

fatal(" can t open output file , 3);while (fgets (buf, sizeof (buf), ip))

fputs (buf, op);fclose (op); /* write buffered data out */

10.44

Page 207: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

The CSTDIO Library

feof#include stdio. h

int feof (FILE * stream) ;

feof tests the end-of-fie indicator for stream.

feof returns a non-zero value it the end of-fie indicator is set forstream.

feof is a macro.

#include stdio. h

/* line oriented file copy *

main () tchar buffer (1024)

while(l) tgets (buffer) ;if (feof (stdin)

break;puts (buffer) ;

10.44-

Page 208: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

The CSIDIO Library

ferror#include stdio. h

int ferror (FILE *stream);

ferror tests the error indicator for stream.

ferror returns a non-zero value it the error indicator is set forstream.

ferror is a macro.

#include stdio. h

int output (FILE *fp, char c)

if (fputc (c, fp) == EOF && ferror (fp)) fputs ("write error\n , stderr);clearerr (stream)

10.44-

Page 209: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

NOTE:

EXAMPLE:

The CSTDIO Library

fflush#include stdio. h

int fflush (fp)

FILE *fPi

ffush writes any buffered data for the fie fp to that fie. The fieremains open.

ffush returns 0, or - 1 if fp is not open or if an error occurredwriting the buffered data to the fie.

fclose ()

Only disk fies are buffered, so ffush does nothing on non-diskfies.

** write record to file and** release to network

#include stdio. h#include dos.

nwrite (buf, size,r buf (J

int size, recnOiFILE *fp; (

int fno;

recno, fp)

fseek (fp, (long) size * (long) recno, 0)

locking(fno = fileno (fp), LOCK, size);fwrite (buf, size, 1, fp);fflush (fp) ;locking (fno, UNLCK, size);

10.45

Page 210: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

fgetc#include stdio. h

int fgetc (fp)FILE *fp;

fgetc returns the next charcter from the streamJP. JP must be

open.

RETURNS:fgetc returns the next charcter from the stream , or EOF on erroror end-of-fie.

SEE ALSO: getc(), scanf(), fread()

EXAMPLE:** fgets

#include stdio.char * fgets(buf,char buf ( J ;int n;FILE * fp; (

int i, Chi

n, fp)

n--for(i = 0; i n && ((ch = fgetc (fp)) != EOF)

(ch != ' ' " ch

!= '

); i++)buf(iJ = Chiif(i != n)

bUf(i++J = 'bu f ( i J

= '

\ 0 ' ;while (ch == .' \r .' II ch == '

ch = .fgetc (fp) ;return buf;

10.46

Page 211: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

NOTE:

EXAMPLE:

The CSTDIO Library

fgets#include stdio. h

char *fgets (buf,char bufr);int len;rILE *fp;

len, fp)

fgets reads the next line, but not more than len - 1 characters fromthe fie fp into but The last character read into buf is followed bya ' \0 '

fgets returns buf, or NULL on end of fie or an error.

fscanf(), fread()

fgets returns the CR character.

** copy file to console

finclude stdio.

void f con (fp)FILE * fp; (

char buf(8l);

while (fgets (buf, 81, fp))puts (buf) ;

10.47

Page 212: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Librar

file lengthlong filelength (handle)int handle;

filelength accesses the size of the open fie associated with hal/die.

file length returns the actual length of the' fie in bytes, or - Lonerror.

fileno

** reprocess additions

process (fh)int fh;

long restart, filelength

() ;

restart = filelength (fh) ;doAdditions jfh) ;lseek( h, restart, 0);reprocess (fh) ;

10.48

Page 213: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Librar

file no#include stdio. h

int fileno (fp)FILE *fp;

fileno returns the handle associated with the fie fp. If more than

one handle is linked to the fie fileno returns the handle assignedwhen the fie was opened. fileno returns tte fie handle. The value is undefined if there is nofie associated withjp.

filelength (), fopen (), freopen

** Find length of a stream

*include stdio.

long flen(fp)FILE *fp; t

long filelength

() ;

return filelength (fileno (fp) ) ;

10.49

Page 214: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra!)'

floor#inc1uda th.doub1a f100r (x)doub1a x;

dva1 = f100r (x) ;

floor returns a double with the largest integer value less than orequal to x.

floor returns the floor of x. There are no error values.

Note that floor (-1 . 5) = - 0, not - 1.0.

ceil

/* round towards zero. cf. ceil() */

#include math. h

double rndtoO (x)double x: (

if(x

return -floor (fabs (x) ) ;return floor (x) ;

10.50

Page 215: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTES:

EXAMPLE:

The CSTPIOLibrary

fopen#include stdio. h

FILE *fopen (name, method)char *name, *method;

fopen opens the fie name.

method is a strng having one of the following values:

Method Meanin

open for reading (fie must exist).open for wrting (same as creat

open for append - open for writing at end of fie, orcreate for writing.

fopen returns a FILE * that identifies the file in future fieoperations, or retus NULL if the fie couldn t be opened.

Even thoughfopen can open the console (" CON" the serial port(" AUX" ), or the priter (" PRN" ), you save fie handles by using thestandard fies (stdin, stdout, ...

** initialize (possibly) empty file

#include stdio .

FILE *finit (name) (char name (J ; (

long ftell

() ;

FILE *fp;

if((fp = fopen(name,error(" can t open

if (ftell (fp) == OL)fileInit (fp);

return fp;

II a "

)) ==

, name);

10.51

Page 216: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

FP _OFF, FP _SEG(Large Case Option)

#include dos. h

unsigned FP OFF (ptr)char *ptr;unsigned FP SEG (ptr)char *ptr;

FP OFF and FP SEG are macros that decompose an 8088 physicaladdress (SEG:OFF into its constituent pars.

RETURNS:

FP _OFF and FP _SEG work only with Lage Case programs.

FP _OFF returns the offset component of the 8088 physical address;FP _SEG returns the segment component.

EXAMPLE:** Large 64K) array addressing

** base address assumed to be SEG: 0

#include dos .

char *larray (ptr,char *ptr;long off;

long addr

off)/* base adr of array * /* offset into array *

addr = (long) (FP SEG (ptr)

addr I = (off & OxFFFFOL) addr I = off & OxFL;return addr;

16;12;

10.52

Page 217: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

The CSTDIO Library

fprintf#include stdio. hint fprintf( fp, fcs,FILE *fp;char fcs () ;

( ,

arg J _..

/printf formats the data infcs and fargl to the fiejp, which mustbe open.

The format control strng,jcs, can contain both ordinar characterswhich ar copied unchanged to the output fie, and conversioncontrol strgs which describe how each arg is to be formatted. fcsis specified in printf

/printf returns - Ion error.

The maximum length offprintf output is 256 bytes. If you needmore use sprintf followed by fputs ().

** write name, index, val in text format

tinclude stdio.

Twrite (fp, n, i, v)FILE *fp;char n (J ;double v,; t

return fprintf (fp, "

\ "

%s\" , %d, %f\n n, i, v);

10.

Page 218: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

fp ute#include stdio. h

int fputc (ch, fp)char ch;FILE *fp;

fpurc writes ch to the fie fp. fp must be open.

RETURNS: fpurc returns ch , or -1 on error.

SEE ALSO: printf(), putc(), fwrite()

EXAMPLE:** u**x put

#include stdio.

static int DOSputc (ch, fp)char ch;FILE *fp;(

if (ch == I \n I )

fputc ( \r " fp);return fputc (ch, fp);

uputs (str)char * str;(

char ch;

while (ch = * str++)if (DOSputc (ch, stdout) == EOF)

return EOF; return DOSputc ( '\n " stdout);

. )

10.54

Page 219: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

The CSTDIO Library

fp uts#include stdio. h

int fputs (buf, fp);char buf();FILE *fp;

/puts copies the strng buf to the file/p.

NOTE:

SEE ALSO: fprintf (), fwrite

/puts returns a - 1 on error.

EXAMPLE:

/puts convert linefeed ('\n ) to carage return - linefeed('\r\n ). Output wil stop ifCf-S is entered, and resume whenany other key is pressed. Each output wil check for a CTRL-entr, and terminate the program if one is encountered.

1* file copy

finclude stdio. h

main (argc, argv)char * argv ( J ; (

char buf(1024J;FILE *ip, *op;

if (*argv (lJ ==

' -

ip = stdin;else if((ip = fopen(argv(l), "r

exit (1)

if(*argv(2J == 'op = stdout;

else if((op = fopen(argv(2), "exit (2)

while (fgets (buf, sizeof (buf) , ip))fputs (buf, op);

fclose (op); 1* write buffered data

10.55

== NULL)

== NULL)

out *

Page 220: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDI.o Lib

franddouble frand () ;

frand computes the next pseudo-radom number.

frand returns the next pseudo-random number in the range from0 to 1.0. There are no error values.

rand (), srand

** draw element from the set (min, max)

draw (min, max)int min, maXi

double ceil (), frand () ;

return min + ceil ((max - min) * frand

() )

10.

Page 221: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

The CSTDIO Library

fread#include stdio. h

unsigned fread(buf, size,char buf(J;unsigned size, nitems;FILE *fp;

nitems, fp)

fread reads into buf, nitems of data of size size from the fie fp .

fread returns the number of items actually read (which may be lessthan nitems if end-of-fie is encountered), or 0 if an erroroccurred.

fgetc (), fgets (), scanf

10.

Page 222: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

SEE ALSO:

EXAMPLE:

The CSTDIO Library

free, freeallvoid free (op)char *op;

void free all (stackSize)unsigned stackSize;

free marks the block at op as unallocated.

freeall reserves stack bytes for the stack expansion area, andintializes the memory allocation area.

See the Memory Management section for a discussion of thememory allocation area.

Neitherfree orfreall return a value. No error codes are set.

freeall releases any storage allocated by malloc

,....

You can resetthe memory allocation area by callingfreeall. Otherwise, call

freeall prior to any calls to malloc,

....

calloc (), malloc (), realloc

** reserve 20k for stack expansion

freeall (20 * 1024);

* * process a line

if ((cp = malloc (MAXLINE)) && process (cp) )free (cp) ;

1 f) ,Q

Page 223: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

EXAMPLE:

The CSTDIO Libra

freopen#include stdio

rXLE *freopen (filename, method, fp)char *filename, *method;rXLE *fp;

freopen closes the fie associated withfP and redirects to the fie

name. It is nonnally used to redirect stdin, stdout, stderr;stdaux, and stdprn .

T1thod is a char strg having one of the following values:

Method Meanin

open for reading (fie must exist).open for wrtig (same as creat

open for append open for writing at end of fie, orcreate for wrtig.

freopen return an FILE * that identifies the fie in future fieoperations, or retu NULL if the fie can t be redirected.

** redirected i/o

*include stdio .

FILE *prn, * freopen () ;char pname r 32) ;int fno;

sprintf (pname, "c: \\spool\\F%d.pfl" , fno++);if( (prn = freopen(pname, " , stdout)) == NULL)

fatal (" can t redirect to printer , 2);exec (command, parms);fclose (prnt) ;

10.59

Page 224: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

frexp#include th. h

double frexp (value, eptr)double value;int *eptr;

frexp disassembles value into a fraction (-c 1.0), and its base 2exponent.

RETURS: frexp returns the fractional par of value as a double, and the base2 exponent of value as an integer at eptr.

The value 0.0 return both 0.0 as the fraction and 0 as the exponent.

There are no eITor codes set.

SEE ALSO: ldexp (), modf

EXAMPLE:** multiply by power of 2

#include -Cmath. h

double mpyPow2 (num, pwr)double num;int pwr;

int exp;

num = frexp (num, &exp);return ldexp (num, exp + pwr);

10 hO

Page 225: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

fscanf#include stdio .

int fscanf (fp, fcs (, ptr J ...rILE *fp;char fcs ();

fscanf reads from the fiefp, assembles data under the specificationoffcs and stores the data at ptr.

The format contrl strg, fcs, is described in scanf.

fscanf retu the number of fields scaned and assigned. A returnof zero means no fields were converted.

fscanf returns EOF for error or end-of-fie.

scanf (), sscanf

** read next numeric field from fp

** if there is any non-numeric data in the** stream, discard it

.include stdio.

FILE *fp;

int n;

while (fscanf (fp,fgetc (fp) ;

%d" , &n) == 0)

10.

Page 226: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

fseek#include stdio. h

long fseek (fp,F:ILE *fp;long offset;int mode;

offset, mode)

fseek sets the location of the next input or. output operation on thefie fp as follows:

Locati(;m

offset bytes from the begining of the fie

offset bytes from the current locationoffset bytes from the end of the file

offset may be either positive or negative. ,

If the resultig location is before the beging of the fie, it is set tothe beging; if it is after the end of the file, it is set to the end.

RETURS: fseek return the curent location, or - lL if there was an error.

SEE ALSO: ftell (), ls ek (), rewind ()

EXAMPLE:** rewind to begining of file

#include stdio.

long rewind (fp)FILE -kfp; f

return fseek (fp, OL, 0);

HI h"J

Page 227: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSIDIO Libra

ftell'include stdio .

long ftell (fp)rILE *fp;

ftell gets the current location of the fie fp as the relative byte

offset from the beginnng of the fie.

ftell returns the current location, or - IL if there was an error.

fseek (), lseek (), rewind

** process all records in file

.include stdio.

process (fp, fun, siz)FILE *fp;int

( *

fun) () ;int siz;

long eof, filelength(), fseek(), ftell();char *buf = mailoc (siz) ;

eof = fiIeIength (fileno (fp)) ;fseek (fp, OL, 0);while (ftell (fp) eo f) (

fread(buf, 1, siz, fp);(*fun) (buf);

free (buf) ;

10.

Page 228: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

#include stdio. h

fwrite

int fwrite (buf, size,char buf;unsigned size, nit em ;FILE fp;

nit ems , fp);

fwrite appends from buf, at most nitems of data of length sizethe fie fp .

RETURS: fwrite retus the number of items actually written, which may beless than nitems iran error occured.

SEE ALSO: fputc(), fputs(), printf()EXAMPLE:

** write Large Case huge array to stream** return: 0 == OK, otherwise error

hwrite (at, size,char *at;long size;FILE *fp;

(int rc;char * lar+ay () ;

fp)/* array *//* size in bytes * /* stream * /* return code *//* see FP OFF */

while (size OxFFFF) (if(fwrite(at, 1, OxFFFF, fp) 1= OxFFFF)

return at = larray (at, OxFFFFL);size -= OxFFFF;

if (size &&fwrite (at, 1, (int) s,ize, fp) 1= (int) size))

return return 0;

10.

Page 229: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

NOTE:

EXAMPLE:

The CSTDIO Libra

getc, getchar'include stdio. h

int qetc (fp)I'ILE*fp;

int q.tchar 0

getc reads the next charcter from the fie fp. fp must be open.

getchar reads the next charcter from stdin.

getc and getchar return the next charcter, or EOF on error orend-of-fie. getchar returns EOF when a CTR-Z character isread.

scanf (), fread

getc and getchar ar functions rather than a macros.

getchar can hangup reading redirected input under DOS 2.X andhigher. Use getc (std1'n) if the input could be redirected.

* * read integer from keyboard

** leave terminating char

iinclude stdio. h

int geti

() (

char digits (128), *dp = digits;

while (isdigit (*dp++ = getc (stdin)))

ungetc (* (--dp), stdin);*dp = ' \ 0' ;return atoi (digits) ;

10.

Page 230: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

getdirchar *qetdir (drive, pathBuffer)char drive, pathBuffer(128);

getdir writes the full pathame of the current directory intopathBuffer.

drive is the drive number: 0 = default drve, 1 = A:, ....

pathBuffer should be a 128 charcter aray.

RETURS: getdir retus the address of pathBuffer or -1 on error.

EXAMPLE:** display prompt as (hh:mm)path

prompt () (char pbuf (137) ;

strcpy (pbuf, " \0 ("

) ;

times (&pbuf (2));pbuf (7) = 'getdir (0, &pbuf (8)) ;strcat (pbuf, "puts (pbuf) ;

1 (\ ?,?,

Page 231: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

SEE ALSO:

EXAMPLE:

The CS1DI Library

getenvchar *qetenv(key, buffer)char*key, buffer (80J ;

getenv searches the DOS environment for an entry of the form

ke =value

and copies value into buffer. value is a strng (terminates with'\0'

getenv returns the address of buffer or NULL if key was notfound.

key is terminated by the ' ' character, so

PATH=C: \

and

PATH =C: \

ar different environment entres.

putenv ()

** get path ot COMMND. COM

#define COMSPEC (but) getenv ("COMSPEC" , but)

10.

Page 232: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

NOTE:

EXAMPLE:

The CSTDIO Libra

getschar *qets (buf)char buf();

gets reads a line-edited strg from the console (stdin ) into buf.During input, -(ESC:: means backup and sta over, -(BACKSPACE::means delete the previous charcter and -(RETURN:: means end ofstrg. -(RETURN:: is replaced in buf by a ' \0'

gets returns the address of buf, or NULL on end of file or error.

fscanf (), fread

gets doesn t return the CR character.

** copy a file from stdin to stdout

cat () (bu f ( 1 02 4 ) ;

while (gets (buf) )puts (buf) ;

1 () h

Page 233: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

SEE ALSO:

EXAMPLE:

The CSIDIO Libra

getw#include stdio. h

int qetw (fp)FILE *fp;

getw returns the next int from the fiefP. fp must be open.

getw returns the next integer value, or EOF if an error or end ofme was sensed.

There is no way to distiguish the integer value - 1 from EOF.

scanf (), read

** Sum numbers in file

finclude stdio.

long sum(fp)FILE *fp; (

long value = 0;int word;

while ((word'" get w (fp) )vaJ.ue += word,

return value;

! = -1)

10.

Page 234: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

indexchar * index (src, ch)char src (), ch;

index fmds the first occurence of ch in src.

index works on a null-terminated strng. There is no test foroverfow.

RETURS: index returns a pointer to the first occurence of ch in src, or 0 ifch wasn t found.

EXAMPLE:** dispatch on key pressed

* * use index rather than switch statement

static char keys

( ) = "

\003

" .

extern int ctl c (), ...

static int (*fun)()() = (ctl

...

dispatch (ch)char ch

() ; (

char *kp;extern char scr attr;if (kp = index (keys, ch (0)))

return (*fun) () (kp - keys);scr aputs (ch, scr attr);return 0;

10 7()

Page 235: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

The CSTDIO Librar

isalnumint isalnum(c);char c;

isalnum determines if c is a letter or a digit (A- , a-z, 0-9).

isa/num returns TRUE (non-zero) if c is a letter or a digit, FALSE(zero) otherwise.

isalnum is a function rather than the usual macro implementation.

** is (c) alpha or numeric?

isalnum (c)char c; (

return (c )-= '(c

)-= '

(c

)-= ' & & .:= '

I I

& & .:= '

I I

&& c .:= '

10.

Page 236: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

The CSTDIO Libra

isalphaint isalpha (c) ;char c;

isalpha determines if c is a letter (A-Z, a-z).

isalpha returns TRUE (non-zero) ifc is a letter, FALSE (zero)otherwise.

isalpha is a function rather than the usual macro implementation.

** is (c) alpha?

isalpha (c)char c; (

return (c

;:= '

(c

;:= '

&& c oe= '

& &

oe= ' z I ) ;

n "7"

Page 237: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

The CSTDIO Libra

isasciiint isascii (c) ;char c;

isascii if c is an ASCII charcter (OxOO-Ox7F).

isascii returns TRUE (non-zero) if c is less than Ox80, FALSE(zero) otherwise.

isascii is a function rather than the usual macro implementation.

** is (c) an ascii char?,

isascii (c)char c; (

return (c & Ox80) == 0;

10.

Page 238: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

isattyint isatty (handle)int handle;

isatty determines if the fie handle refers to a character device console, priter, or serial port .

RETURNS: isatty returns TRUE (non-zero) if the handle refers to a characterdevice, FALSE (zero) otherwise.

EXAMPLE:** is (handle) a character device?

ide fine ISDEV Ox0080ide fine CHARDEV Ox8000

isatty (handle)uns igned handle; (

extern unsigned _rax, _rbx, _rdx;

rax = Ox4400;rbx = handle;doint (Ox2l);

return ( rdx &

/* get device info */

ISDEV) && ( rdx & CHARDEV);

10 7.1

Page 239: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

NOTE:

EXAMPLE:

The CSTDIO Libra

iscntrlint iscntrl (c)char c

iscntrl determines if c is acontrol character (OxOO-OxlF , Ox7F).

iscntrl returns TRUE (non-zero) if c is Ox7F or less than Ox20(space), FALSE (zero) otherwise.

iscntrl is a function rather than the usual macro implementation.

** is (c) a control char?

iscntrl (c)char Ci

return (c == Ox7F) II(c 0( Ox20)

10.

Page 240: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

The CSIDIO Libra

isdigitint isdiqit (c) ;char c;

isdigit determines if c is a digit (0-9).

isdigit returns TRUE (non-zero) if c is a digit, FALSE (zero)otherwise. isdigit is a function rather than the usual macro implementation.

** is (c) numeric?

is digit (c)char c; (

return (c = '0' && c

= '

1 (\ 71'

Page 241: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

, / *

The CSTDIO Librar

is lowerint islower (c) ;char c;

islower determines if c is a tower-case letter (a-z).

islower returns TRUE (non-zero) if c is a lower-case letterFALSE (zero) otherwise.

islower is a function rather than the usual macro implementation.

** is (c) lower-case?

islower (c)char e; (

return (e

= '

' && e

= '

10.

Page 242: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

The CSTDIO Libra

isprintint isprint (c) ;char c;

is print determines if c is a printable charcter (Ox20-0x7E ).

isprint returns TRUE (non-zero) if c is a printable character,Ox20 (space) though Ox7E ('- ), FALSE (zero) otherwise.

is print is a function rather than the usual macro implementation.

** is (c) printable?

#define SPACE Ox20

isprint (c)char c; (

return (c = SPACE && c

= '

1 () 712

Page 243: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

The CSTDIO Libra

ispunctint ispunct (c) ;char c;

ispunct determines if is neither a control nor an alphanumericcharcter. ispunct returns TRUE (non-zero) if

! (isalnum(c) II iscntrl(c))FALSE (zero) otheIWise.

ispunct is a function rather than the usual macro implementation.

10.

Page 244: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

NOTE:

EXAMPLE:

The CSTDIO Libra

isspaceint isspace (c) ;char c;

isspace determines if c is a whitespace charcter (Ox09-0xOD,Ox20).

isspace returns TRUE (non-zero) if c is a Ox20 (space), I \t'(tab), ' \ r ' (carage return), I \n' (linefeed), or ' \ f I(formfeed), FALSE (zero) otherwise.

isspace is a function rather than the usual macro implementation.

** is (c) white-space?

isspace (c)char c; (

static char wspace

() = "

\t\r\n\f\040"return index(wspace, c) !- 0;

10,

Page 245: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

TheCSTDIO Librar

isu' pperint isupper (c) ;char c;

isupper determines if c is an upper-case letter (A-Z).

fsupper returns TRUE (non-zero) if c is an upper-case letterFALSE (zero) otherwise.

isupper is a function rather than the usual macro implementation.

** is (c) upper-case?

isupper (c)char c;i

return (c

= '

A I & & c I Z I ) ;

10.

Page 246: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

isxdigit#include ctype.

int isxdigit (int c);

isxdigit tests whether c is a valid hexadecimal digit (0- F).

RETURNS: isxdigit returns 1 if c is a valid hexadecimal digit, 0 otherwise.

EXAMPLE: include ,ctype. h

long gethex (char **

p)

long val = char c;

while (isxdigit (**

p))

val " = 4;if (isdigit (c = * (*

p++)))

val 1= c - I 0 ' ;

elseval 1= toupper(c) - (' A' - 10);

return val;

10.

Page 247: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Library

itoa#include stdlib. h

char *itoa (int val, char str () , int rad);

itoa converts val into a mill terminated strIng at str. rad specifiesthe base of val; it must be in the range 2 36.

If rad is 10 and val is negative, the first character of str wil be the

minus sign

, '

itoa returns a pointer to str.

#include ,stdlib. h#include ,stdio.

/* put a decimal number to stdout *

putn (int dig) char buffer (256);

return fputs (itoa (dig, buffer, 10), stdout);

10.82-

Page 248: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Library

l.onq l.abs (n)l.onq n;

labs

labs computes the absolute value of

labs returns a long absolute value. There are no error codes set.

abs (), fabs

** long absolute value

long labs (val)long val; t

return val a ? - val : val;

10.82-

Page 249: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

EXAMPLE:

The CSIDIO Libra

Idexp#include th. h

double ldexp (value, exp)double value;int exp;,

ldexp computes value 2ex

ldexp bqilds the floatig-point representation. There is no test foroverfow.

frexpO, modf

Seefrexp

10.

Page 250: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

NOTE:

EXAMPLE:

The CSTDIO Libra

locking#include dos .

int lockinq(handle, mode, count)int handle, mode, count;

locking locks or unocks count bytes of the fie identified by handlestaring at its current position. Locked areas of a fie canot be reador written by other processes.

mode specifies the action to be performed. The constants definedin o:dos. are:

Constant

LOCK Lock the specified bytes. If the bytes canot belocked, retuman error.Unlock the specified bytes. The bytes must belocked.

UNLCK

More th one area of a fie can be locked, but the areas must notoverlap.

Only one area can be unlocked per call. If two contiguous areas ofthe fie are locked, each ara must be unlocked separtely.

All locks should be removed before closing the fie or exiting theprogra.

locking returns 0 if successful

, -

1 L on error.

open (

locking works only with DOS 3.0 and later.

See fflush

10.

Page 251: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

Iog,- log1 0#include th.

dou'ble log (x)double x;

double loglO (x)double x;

log computes the natural logarth of x; 10g1O computes the base10 logarth.

log and 10g1O return the indicated logarths. They both return0 when is zero or negative and errno is set to EDOM.

exp (), pow()

** n-th root

finclude math.

double root (n, x)int n;double x; (

return exp ( log (x) / (double) n );

10.

Page 252: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

longjmp#include setjmp.

void lonqjmp (env, val);jmp - buf env;int val;

jmp _buf is defmed in .:setjmp. It creates an environment used bysetjmp for future use by longjmp. longjmp restores theenvironment from env and returns val. val canot be zero.

RETURNS: longjmp does not return.

NOTE: env can be specified as zero for compatibilty with previous releases.There can be only one "zero env active at a time.

If the environment stored in env points into an overlay area, then theoverlay that called setjmp must be resident when longjmp is called-if another overlay is resident, then sttge thgs wil happen. It isbest to call setjmp from the root.

1 () R";

Page 253: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Library

Iseeklong lseek(handle, offset, mode)int handle, mode;long offset;

Iseek sets the location of the 1)ext input or output operation on thefie handle as follows:

mode Location

offset bytes from the begining of the fileoffset bytes from the current locationoffset bytes from the end of the fie

offset may be either positive or negative.

If the resulting location is before the beginning of the fie, it is set tothe beginning; if It is after the end of the fie, it is set to the end.

lseek returns the current location, or -1 L if there was an error.

fseek (), ftell

** ansi fseek

** returns 0 == OK

#include stdio .

int fseek (stream,FILE * stream;long offset;int ptrname;

long ret;

offset, ptrname)

ret = lseek (fileno (stream), offset, ptrname);return ret != offset;

10.

Page 254: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

Itoa#include stdlib. h

char * toa (long val, char str (), int rad);

ltoa converts val into a nulllerminated string at str. rad specifies

the base of val; it must be in the range 2 36.

If rad is 10 and val is negative, the first character of str wil be the

minus sign

, '

RETURNS: ltoa returns a pointerto str.

EXAMPLE: #include stdlib.#include stdio. h

/* put a decimal number to stdout */

putn (long dig)

char buffer (256) ;

return fputs(ltoa(dig, buffer, 10), stdout);

10.

Page 255: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Library

malloe#include stdlib. h

char *malloc (size t size)

malloc allocates a block of size bytes.

See the discussion in Memory Management.

malloc returns a pointer to the block, or NULL if it couldn t allocatethe memory.

calloc (), free (), freeall (), realloc

** strdup - copy a string

char * strdup (char *str) char * sav, *malloc

() ;

if (sav = malloc (strlen (str) + 1))strcpy (sav, str);

return sav;

10,88-

Page 256: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

memccpy#include strinq. h

void *memccpy(void *dst, void *src,char c, size t n);

memccpy copies 0 or more bytes of src to dst , copying up to andincluding the first occurrence of c or until bytes have beencopied, whichever occurs first.

RETURNS: memccpy returns a pointer to the location of c in dst. Otherwise itreturns NULL if c was not copied.

EXAMPLE: #include ,string. h#include ,stddef. h#include ,stdio. h

char *memccpy (char *dst, char * src, char size t n);

while (n--)if ( (*dst++

returnreturn NULL;

= *

src++) == c)dst -

10.88- 2

Page 257: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

TheCSTDIO Library

memchr#include string. h

. void *memchr (void *str, char c, size t n);

memchr locates the first occurrence of c in the initial charactersof the object pointed to by str .

memchr returns a pointer to c , or NULL if c doesn t occur in theobject.

#include string. h?#include stdio. h?#include stddef. h?

/* look for a string *

char *memchr (char * str, char c,

while (n--)if (*str++ ==

return str - return NULL;

10.88-

size t n)

Page 258: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSIDIO Librar

memcmp#include string. h

int memcmp(void *sl, void*s2, size t n);

memcmp compares the initial characters of the object pointed toby s2 to the the object pointed to by sl .

RETURNS: memcmp returns a value indicating the lexicographical relationshipof sl to s2 as follows:

Meaning

..0

)-0

sl is less than s2 .

sl is identical to s2 .

sl is greater than s2 .

EXAMPLE: #include ":stddef. h)-#include ..string. h)-

/* compare two objects *

int memcmp (char * sl, char * s2, size t n)

while (n--)if ( * s 1 ++

! = *

s 2 ++ )

return * (sl - return

*(s2 1);

10.88-

Page 259: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Librar

memcpy#include string. h

void *memcpy(void *dst, void *src,size t n);

memcpy copies bytes of src to dst .

There is no test for overlap between src and dst .

memcpy returns the value of dst .

#include string.#include stddef. h

char *memcpy (char *dst,char *beg = dst;

size t n) tchar * src,

while (n--)*dst++ =

return beg;src++;

10.88-

Page 260: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

memicmp#include string.

int rnernicrnp(void *sl, void *s2, size t n)i

memicmp compares the initial characters of the object pointed toby s2 to the the object pointed to by sl , without regard to the caseof the characters.

RETURNS: memicmp retums a value indicating the case insensitivelexicographical relationship of

sl to s2 as follows:

Value Meanin

..0

)-0

sl is less than s2 .

sl is identical to s2 .

sl is greater than s2 .

EXAMPLE: #include ..stddef. h)-#include ..string. h)-#include ..ctype. h)-

#define TU (c) toupper (c)

/* ,

compare two objects *

int memicmp(char *sl, char *s2, size t n)

int c1, C2i

while (n--if ( (c 1 = TU ( * S 1++) )

return c1 - C2ireturn 0

!= (c2 = TU(* s2++)))

10.88-

Page 261: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Library

memm,ove#include strinq. h

void *memmove (void *dst, void *src,size t n);

memmove copies characters from src to dst .

memmove correctly copies overlapping objects.

memmove returns dst .

tinclude string.#include stddef. h

char *memmove (char *dst,char *beg = dst;

char * src,

if (src + dst) tsrc += n;dst += n;while (n--

*--

dst = *-- src;

elsewhile (n--)

*dst++ =return beg;

src++;

10.88- 7

size t n)

Page 262: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

memset#include stdlib. h

void *memset (void *dst, char c, size t n);

memset sets the initial bytes of dst to c .

RETURNS: memset returns dst .

EXAMPLE: #include string. h#include stddef. h

char * memset (char *dst, char c, size t n)

char *beg = dst;

while (n--*dst++ = c;

return beg;

10.88-

Page 263: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Librar

mkdirint mkdir (pathName)char pathName

() ;

mkdir creates a new directory pathName.

If drive and path components of pathName are specified, they mustexist.

mkdir returns a 0 if the directory was created, or - 1 on error.

chdir 0, rmdir (

** create index file sub-directory

** form: path/name/index-name or data-name

** returns 0 == OK

int icreat (name)char *name; (

char buf (128);

getdir (0, buf);s1rcat(buf, "

\\"

strcat (buf, name);return mkdir (buf) ;

10.

Page 264: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

modf#include th. h

double modf (value, ipart)double value, * ipart;

modf decomposes value into a positive fractional par and aninteger par.

RETURNS: modf returns the positive fractional par and stores the integer partat *ipart .

SEE ALSO: frexp (), ldexp

( )

EXAMPLE:** format the first n digits of val

#include math. h

char *ndig (n, val, buf)int n;double val;char *buf; (

double i, int len;char wrk (32), * index () ;

f = modf (val, &i);if(i)

sprintf(buf, " Of" , i);else

bu f ( 0

) = ,\

0 ' ;sprintf (wrk, "

% .

16f" , f);

if ((len = strcspn (buf, "

))

= n) (bu f (n)

= '

\ 0 ' ;else

strncat (&buf (len), index (wrk, '

. '

) +1, n-len);return buf;

Page 265: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

'include -Cdos .

int sopen (name, mode)char *name, mode;

open

open makes an existig fie available for subsequent read, writeand Iseek calls.

With any DOS release, mode can be:

VALUE NAMEREAD

READWR

open the fie for reading onlyopen the fie for writig onlyopen for reading and writing

With MSDOS version 3 and later, a sharng mode may be specified.The shag modes ar:VALUE NAMEOxOO COMPAT

Oxl00x20Ox30Ox40

DENYRWDENYWRDENYRDDENYNO

Compatibilty mode, share with allother compatibilty opensdeny read/write opensdeny wrte opensdeny read opensdeny no opens

RETURNS: open retus a handle that identifies the fie in future fieoperations, or -1 if the fie can 't be opened.

NOTES: open can open the console (" CON" ), the serial port ("AUX ), or thepriter ("PRN"

EXAMPLE:** open, share with everybody

#include ..dos. h;:

if((fh = open (name, READ + DENYNO)) == -1)

10.

Page 266: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

overlay(Small Case Model)

int overlay init (overlayFilename)char *overlayFilename;

int overlay(overlayNumber)int overlayNumer;

void overlay close ();

int moverlay(overlayNumer)int overlayNumer;

overlay _init must be caIled prior to the fIrst overlay call and mustbe used when the -v option of BIN is used. overlayFilenameconta the overlays. With DOS 2.0 and greater, the overlay fiecan be in the default dirctory of any directory listed in the PATHsystem pareter. Otherwise the fIe must be on the default driveor must explicitly contan the drive number, e.g. "B:X.OV"

overlay loads overlay overlayNumber as created by the -v optionof BIND. It must be called before any reference or call to data orcode in the overlay. Overlays are nQ automatically loaded byreferencing a value in the overlay.

moverlay loads the indicated overlays created by the -M option ofBIND. It works the same as the overlay fuction described above.

overlay close closes all overlay fIes.

RETURNS: overlay- init return - 1 if the fIe could not be found. overlay andmoverlay return - 1 if overlay _init has not been calledsuccessfully, if the .OV fIe is bad, or if overlayNumber does notcorrespond to an existig overlay.

NOTE: When an overlay call is made, the functions in the previous overlayscan no longer be caled and the data associated with the last overlayis lost. If an uninitialized varable is referenced by both a modulein the root and a module in an overlay, it is placed in the root. If adata item is initialized in , a root module, it is placed in the root. If itis initialized in an overlay, it is placed in the overlay.

10.

Page 267: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

pow#include th.

double pow(x, y)double x, y;

pow computesxY.

pow retu the yth power of x, or 0.0 if x = 0.0 and y 0( 0.0, or ifx 0( 0.0 and y is not an integer (errno is set to EDOM).

exp (), log (), sqrt

** ndn-integer appx of pow

.include o(math. h

double nipow (x, y)double x, y); (

eturn exp (log (x) * y);

10.

Page 268: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

printfvoid printf (fcs (, arq

) ... );

char fcs () ;

printf formats the output to the fie stdout.

The format control strg,fcs, contans both ordinar characterswhlch are copied unchanged to the output, and conversion controlstrgs which describe how each arg is to be formatted.

Conversion conttol strgs have the following format (( encloseoptional entres):

% ( -)

(width) (pa:rs) code

where the optional ' ' specifies that the field is to be left justified the default is right justification.

The optiona width specifies the minum field width in bytes. A'*' mean that the width is specifed by the next int arg in thecaing sequence. A leading zero indicates tht the field should bepadded with zeroes intead of blan. The field i:; not trncated ifthe width is too small.

Both parms and code depend upon the specifc conttol strng, asfollows.

Character: % (-) (width) c

printf("

, "

printf (" %*c -3, "

-+

IAI

-+

-+ IA printf(" %3c

, "

String: % (width) ( .precision) s

precision specifies the maximum size of the strng. An '*' meansthat the size is specified by the next int arg in the callingsequence. If the strg is longer than the precision then the strngis trncated. printf(" %5s

, "

abcdefgh"printf (" %-5. 3s, "abcdefgh"printf(" %5. 3s, " abcdet:gh"

10,

-+

abcdefgh I

-+

I abc

-+

abc I

Page 269: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

p ri ntfSigned Integer: % (-) (sign) (width) (1)

A leading minus sign ' ' is automatically output for negativenumbers. If the optional sign is a ' , a leading plus sign is outputfor positive numbers; a space outputs a blan for positive numbers.

The optional (lowercase ' ) specifies that the corresponding argis a long.printf(" %d" , -45)

printf (" %+d" , 45)

printf(" % ld" , 45L)

printf (" %O*d" , 3, 45)

1-451

1+451

I 451

10451

Unsigned Integer: %

( -)

(#) (width) (1) code

# specifies that a leading '0' is output for octa numbers, and leading ' ' is output for hexadecimal numbers.

code is ' ' for decimal format, ' ' for octal format, and ' ' forhexadecimal format. printf(" , 255) 12551

printf(" , 255) 13771printf(" , 255) 10xFFI

Floating Point: % ( - J (sign J (#) ( . precision J code

# specifies that trling zeroes are to be output, and that a decimalpoint is output, even for zero precision.

precision specifies the number of digits output after the decimalpoint for code ' and 'f, or the number of significant digits forcode . An '.' means that the number of digits is specified by thenext int arg in the calling sequence. Truncation causes rounding.The default for precision: is 6.

code is ' ' for (- Jd. ddddd E( - Jdd format, 'f for (- Jddd. ddd format,and ' ' for the shorter of ' ' o f formats.

10.

Page 270: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Literal %:

NOTE

The CSTDIO Libra

p ri ntfprintf (" %f" , 1234. 56789)printf(" 1f" , 1234. 56789)printf(" , 1234. 56789)printf (" , 1234. 56789)

11234. 567890 I

11234.11.235E03111234. 571

printf(" %5. 2f%%" , 99. 44) 199. 44%1

The maximum printf andfprintf output is 256 bytes. If you needmore use sprintf followed byp ts ().

1 () Qr-

Page 271: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

NOTE:

The CSTDIO Libra

pute, putehar#include stdio. h

int putc (ch, fp)char ch;FILE *fp;

putc wrtes ch to the fie.f . .f must be open.

putchar wrtes ch to stdout .

Linefeed (' ) is converted to carage return - linefeed ('\r\n

Output wil stop if Cf-S is entered, and resume when any otherkey is pressed. Each output wil check for a Cf-C entr andterminate the progra if it was pressed.

putc and putchar retu ch , or EOF on error.

printf (), write

pUlchar is a function rather than a macro.

10 Q7

Page 272: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

putel1int put$nv (k$Y, n$wValu$)char *k$Y, n$wValu$ r)

putenv changes the value associated with key in the environment tonewValue. newValue is a NULL-terminated, possibly empty,strg.

putenv searches the DOS environment for an entry of the form

key =oldV alue

If key is found, newValue replaces oldValue. If key is not foundthen a new key=newValue entr is inserted in the environment.

putenv returns 0, or -1 on errr.

ke is terminted by the ' ' charcter, so

PATH=C: \

and

PATH =C:\

are different environment entres.

getenv ()

** update parents cycle number

char buf (16)

getenv (" CYCLE" , buf);sprintf(buf, " %d" , atoi(buf) + 1);putenv (" CYCLE" , buf);

10 QR

Page 273: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

NOTE:

The CSTDIO Librar

puts#include stdio. h

int puts (buf)char buf();

puts copies the null terminated strng bl!f to the console (stdout

On output, linefeed C\n is converted to carage return - linefeedC\r\n . Output wil stop ifCf-S is entered and resume whenany other key is pressed.

puts . wil check for a Cf-C entr and terminate the program ifone occurrd.

puts return a - Ion error.

fprintf (), fwrite

puts doesn t append a newline.

10.

Page 274: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

NOTE:

The CSIDIO Libra

putw#include stdio. h

int putw(w, fp)int

FILE *fPi

putw writes the int to the fieJP . JP must be open.

putw returns or - Ion error.

printf(), write()

There is no way to distinguish the return from put w ( -1 , fp)from an error.

1 0 1

Page 275: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

NOTE:

The CSTDIO Libra

qsortvoid qsort (array, num, width, compare)char array () ;int num, width, (*compare) () ;

qsort is an implementation of C. A. R. Hoare quicker-sortalgorith. It sort an array of num elements, each width byteswide. compare is called with two arguments (pointers to the twoelements being compared), and returns an integer less than, equalto, or greater than zero accordingly as the first argument is lessthan, equal to, or greater an the second argument.

qsort does not return any value.

The usual function for compare is st rcmp ( ). If you are sortinganytg other th strgs, the following may serve as a model:

int compare (left, right)int *left, *right;

return *left - * right;

'define TCAR'defini: ISIZE

1024sizeof (int)

int itab (TCAR) ;

qsort (itab, TCARD, ISIZE, compare);

Remember that int, long, float, and double values are storedwith their low-order bytes first. Thus string comparsons (i.e.,strcmp () ) may not produce the expected results.

10. 101

Page 276: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

randint rand()

rand computes the next pseudo-radom number in the range fromo to 215 1. Repeated runs of the progra produce identicalsequences of pseudo-radom numbers.

If you wish different sequences of numbers, or to restar thesequence with a run, call srand to intialize the pseudo-radomnumber generator.

rand returns the next pseudo-random nllmber. There are no errorcodes.

frand (), srand

** flip a coin

int coinFilp

() (

return rand() OX4000i

Page 277: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

readint: read (handle, buf,int: handle;char *buf;unsigned count:;

count: )

read reads count bytes into buf from the fie

/p.

read stars reading from the current position of fp. After the readthe current position has advanced count bytes or is at EOF.

read retus the number of bytes actually read (which may be lessthan count if end-of-fie is reached), or -1 if an error occurred.

There is no way to distinguish a normal read of OxF bytes froman error.

fgetc (), fgets (), s anf ()

** Small Case block transfer

xfer (ih, oh)int ih, oh;

char *buf, * _memory () ;unsigned size, amt;

freeall(256); min stack */buf = _memory () + 1; /* point tosize = (unsigned *)buf & OxF800;buf += 2; / * point to buffer * do (

if( (amt - read(ih, buf, size))puts ("xfer: read error);exit (1);

write (oh, but, amt);) while (amt == size);

close (oh) ;

size *

/ *

% 2K *

= -1) (

10. 103

Page 278: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

reallocchar *realloc (op, size)char *op;unsigned size;

realloc changes the size of the block at op to size bytes.

RETURS: realloc returns a, pointer to the (possibly moved) block, or 0 if itcouldn t allocate the memory. If realloc returns 0, the originalblock at op is still allocated and useable.

See the description of malloc for a discussion of the memoryallocation area.

SEE ALSO: calloc (), free (), freeall (), malloc

EXAMPLE:** enlarge saved string

char *savcat (str, add)char * str, *add); (

unsigned size;char *new;

size = strlen (str) + strlen (add) + 1;if (new = realloc (str, size)), strcat (new, add)

return new

Page 279: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Library

remove#include stdio .,

int remove (char *pathname);

remove deletes the fie specified by pathname .

remove returns 0 if the fie was deleted

, -

1 otherwise.

#include stdio. h

int mustDelete (char *name)

if (remove (name))

printf(" can t remove %s\n , name);

abort () ;

10.104-

Page 280: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

-t- -1;

(; (- ,

'i"e. Ci.q,(f

tY\./

-"-," , ,'

Page 281: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

renameint rename (oldFile, newFile)char *oldFile, *new ile;rename changes the fie name old File to newFile.

Under DOS 2 and later, oldFUe may contain a path specification.

RETURS: rename return - 1 if oldFUe is open or if an error is detected.

EXAMPLE:** create . BAK file

makeBAK (old)char *old; (

char *suf, new(128);

strcpy(new, old);if( (suf = rindex(new, '

. '

&& suf old && * (suf - suf = '\0'

strcat (new, II . BAK"return rename (old, new);

!= '

10. 105

Page 282: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

The CSTDIO Librar

rewind#include stdio. h

long rewind (fp) ;rILE * fp;

rewind is the same as f seek ( fp, OL, 0) it seeks to thebeginig of the fie fp .

rewind returns OL, or -1 in case of error.

fseek (), ftell

1 () 1 ()/;

Page 283: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

rindex,

char *rindex (arc, ch);char arc (), ch;

rindex locates the last occurence of ch in src.

rindex returns a pointer to the last occurence of ch in src , or 0 ifch isn t in src.

index (

See rename.

10.107

Page 284: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

rmdir, int rmdir (pathname)char pathname

() ;

rmdir deletes the directory pathname.

pathname must be empty and must not be the current workingdirectory or the root directory.

RETURS: rmdir returns 0 if the directory was deleted, -1 otherwise.

SEE ALSO: chdir (), mkdir

10 tOR

Page 285: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Character:String:

Integer:

The CSTDIO Libra

scanfint scanf (fcs (, ptr J ... char fca () ;

scanf reads fromstdin. The format control strng,fcs contains:blanks or tabs, which match optional whitespace (blans, tabs,newlines, form feeds, and vertcal tabs) in the input; a non-character which must match the next charcter in the input, andconversion control strngs which describe the type and format ofeach ptr. Conversion control strgs have the following format ((enclose optional entres):

% (*J (widthJ (parmaJ code

where: * indicates tht the field should be skipped and not assignedto a ptr and width specifes the maximum field size in bytes. BothparT and code ar described below. The examples have thefollowing form:

I inppt strinq I

-+

function call

-+

rp.sult

% (*)

(width)c% (*J (widthJ.

width specifies the number of charcters to be read into the aray at 'ptr. The default is 1. ' ' whitespace skipped

, '

' whitespaceisskipped.

abc! -+ scanf("%3c" , buf) -+

abc I -+ scanf ("%3s , buf) -+ abc I

%(*J (widthJ (sizeJcode

size equal to 'I' (lowercase ' ) specifies that ptr point to a long,an 'h' specifes a short int.code is one of:

' '

d' signed decimal format

, '

unsigneddecimal format, ' unsigned octa, and ' unsignedhexadecimal.

I FF I -+ scanf("%x , &hex)

-+

255

I 377 I -+ scanf ("%0" , &oct)

-+

255

10. 109

Page 286: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

scanf

Floating Point: % (*) (width) (size) code

Scanset:

RETURS:

SEE ALSO:

size equal to 'I (lowercase ' ) specifies that ptr points to adouble rather than a float.

code can be either '

, '

f, or ' they all indicate floating point.I 123. 45 I scanf ("\f" , \f1t) 123.

I 123. 45 I scanf("%41f\d" , &d, &i) 123.

% (*)

(width) acanaet

scanset is specifed by a sequence of charcters enclosed by brackets'( T. It reads a strg, including the terminating null charcter.Leading whitespace iu skipped.

1123 ABC scanf("\(123 )" , str) 1123 I

. A rage of contiguous charters ca be specified by the first andlast element of the rage, separted by a '

1123 ABC scanf("\(l-3 )" , str) 1123 I

, If the first element of scanset is a I A I , then all

charcters exceptthose specified wil be read.

112 ABC I scanf("\("A-C)" , str) 1123 I

To specify ' ' or 'A' in a scanset , specify it as the firt element.Thus to read an integer, skip any intervienig garbage, and readanother integer

scanf("\d\*( -+0-9)%d" , &dig1, &dig2);

scanf returns the number of items successfully scaned, or EOF if aCf-Z was read.

fscanf (), printf (), sscanf

10110

Page 287: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

The CSIDIO Library

scr aputsvoid scr aputs (string, attr);char *string, attr;

scr _a puts writes strg str to the display with attrbute attr.

moves to the beginng of the line, and ' ' moves to the next line.Moving off the bottom line causes scrollng.

attr is defmed in the IBM PC Techncal Reference Manual.

sacr aputs retu no value.

scr aputs is in the fie PCIO.A. It is for use on machines thatsupport the INT 10H interface.

** write text , in reverse video

highLight (text)char *text; (

scr aputs (text, Ox70);J '

10. 111

Page 288: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra'

scr ci, scr co, scr cstschar 8cr ci ();void 8cr co (ch) ;char 8cr csts ();

scr ci reads the keyboard like ci () but uses its own translationtable for command charcters. The table is in the fies CONFIG.and PCIO.

scr csts tests for a charcter in the input queue, and if one is found,reads it. The charcter is not retaned.

scr _co wrtes a character to the display like co () .

scr _ci returns the next charcter from the input queue. scr _cstsreturn the next charcter from the queue, or 0 if no character isavailable. scr co return no value.

All the fuctions ar in the fies PCIO.A and CONFG.

scr ci and scr csts use !N 16H in the fie PCIO.

scr setmode (), scr setup ()

* * empty keyboard queue

** scr csts () reads the character from the

**

input queue - csts() doesn

kbdFlush () (while (scr csts ())

lOll?

Page 289: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

NOTE:

SEE ALSO:

'"-

EXAMPLE:

The CSTDIO Libra

scr clr, scr clrl , scr clsvoid scr clrO;void scr clrl

() ;

void scr cls 0;

ser clr erases the entire screen.

scr clrl erases everythng from the cursor location to the end of theline.

seT cls erases everythg from the cursor location to the end of thescreen. There are no values retued.

All the functions ar in the fie PCIO.

scr setmode (), scr setup ()

/* menu processing */

struct _menu (int trow, tcol;char *text, attrib;int rrow, rcol;char * response;int (*valid) () ;J ;

doMenu (mp)struct menu mp () ; (

scr clr () while(mp- trow != -1)(

scr rowcol (mp- trow, mp- tcol);scr=aputs (mp- text, mp- attrib);scr rowcol (mp- rrow, mp- rcol);while (! (*mp- valid) (mp- response) ) (

scr rowcol (mp- rrow, mp- rcol);scr clrl

() ;

, J

10.113

Page 290: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

scr cursoff, scr cursonvoid scr cursoff () ;void scr - curson () ;

scr _cursoff turns the cursor off; scr _curson turns it back on.

The functions return no values.

Both functions are in the fie PCIO.

scr _setup must be called prior to calling these functions.

scr setmode (), scr setup ()

** display line count

scr setup () ;scr cursoff () ;scr clr () lineno = 0;while (fgets (buf, sizeof (buf), fp))

printf (" \r%u , lineno++);scr curson () ;

10114

Page 291: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

SEE ALSO:

EXAMPLE:

The CSTDIO Librar

scr rowcol

void ser roweol (trow, teol)int trow, teol;

scr rowcol moves the cursor to row trow and column tco!.

scr rowcol returns no value.

scr rowcol is in the fie PCIO.

scr setmode (), scr setup ()

/* menu processing */

struct _menu (int trow, tcol;char *text, attrib;int rrow, rcol;char * response;int (*valid) ()

) ;

doMenu (mp) struct menu mp (J ; (

scr clr () while (mp- trow != -1)

scr rowcol(mp- trow, mp- t:col);scr aputs (mp- text, mp- attrib);scr rowcol (mp- rrow, mp- rcol);while (! (*mp- valid) (mp- response)) (

scr rowcol (mp- rrow, mp- rcol);scr clrl

() ;

10.115

Page 292: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

NOTE

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

scr scdn, scr scrdnvoid ser sedn ()

void ser serdn (lines, fr, fe, tr, te)

int lines, fr, fe, tr, te;

scr _scdn scrolls the screen down one line, but leAves the top twolines alone.

scr _scrdn scrolls th given area down lines. The area is defined bythe upper-left location (j,fc) and the lower-right location (tr, tc).

The functions return no values.

Both functions are in the fie PCIO.

scr setmode (), scr setup ()

** scroll a window

struct _win (char ul row, ul col;char lr row, lr col;char *name;char attril _window (MAWIN) ;

wscroll (window, lines)int window, lines; (

struct _win *wp = & window(windo

if (lines

scr scrdn (-lines, wp- row, wp- col,wp- row, wp- col);

elsescr scrup (lines, wp- row, wp- col,

wp- row, wp- col);

10.116

Page 293: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE

SEE ALSO:

EXAMPLE:

The CSIDIO Libra

scr scup, scr scrupvoid ser seup () ;

void ser serup(lines, fr, fe, tr, te);int lines, fr, fe, tr, te;

scr _scup scrolls the screen up one line, but leaves the top two linesalone.

scr _scrup scrolls the given area up lines. The area is defined by thethe upper-left location if, fc) and the lower-right location (tr, tc).

The functions return no values.

Both functions are in the fie PCIO.

scr setrnode (), scr setup ()

** scroll a window

struct _win fchar ul row, ul col;,char lr row, lr col;

, char *narne;char attr;

) _

window (MAWIN) ;

wscroll (window, lines)int window, lines;

struct _win *wp = & window (window) ;

if (lines

scr scrdn (-lines, wp- row, wp- col,wp- row, wp- col);

elsescr scrup (lines, wp- row, wp- col,

wp- row, wp- col);

10. 117

Page 294: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The STDIO Libra

scr setmode, scr setupvoid scr setmode (newMode)char newMode;

void 8cr setup () ;

scr setmode sets the mode of the graphics card. newMode must bebetWeen 0 and 6. See the Note below.

scr _setup must be called prior to any of the screen routines if thescreen is curently in 80 column mode orif scr _curson with amonochrome display is used. Ths routie sets the value of theglobal varables described in theNote below.

RETURS: The functions return no values.

NOTE: Both functions are in the fie PCIO.

scr _setmode and scr _setu manage the following global data.

char scrcols; /* number of character positions */char scr rows; /* number of lines */char scr -mode; /* current screen mode:

o = 40 col. BW1 - 40 col. color2 - 80 col, BW3 - 80 col. color4 - 320 x 200 color graphics5 - 320 x 200 BW graphics6 - 640 x 200 BW graphics7 - 80 col. BW

char scr-page; /* current active display page */

1() 11\:

Page 295: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

SEE ALSO:

EXAMPLE:

The CSTDIO Librar

scr sinpchar scr sinp () ;

scr _sinp reads the charcter at the current cursor location.

scr _sinp returns a charcter.

scr _sinp is in the fie PCIO.

scr setmode (), scr setup ()

** read numeric field from screen

** no test that co 1 + len on screen

double readnAt (row, col, len)char row, col, len;

char data (80), dp = data;double atofO;

while (n--) (scr rowcol (row, col++);*dp++ = scr sinp.O;

*dp .. I \0 Ireturn atof (data) ;

10.119

Page 296: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

NOTE:

The CSTDIO Libra

setjmp#include setjmp.

int setjmp (env)

jmp buf env;

jmp buf is defined in setjmp. . It creates an environment usedby setjmp for future use by longjmp .

setjmp saves the environment in env .

setjmp retus 0 after saving the environment, or a non-zero valueas the result of a longjmp call.

longjmp ()

env can be specified as zero for compatibilty with previousreleases. There can be only one "zero env active at any time.

If the environment stored in env points into an overlay area, thenthe overlay that called setjmp must be fesident when longjmp

called - if another overlay is resident, then strge things wilhappen. It is best to call setjmp from the root.

EXAMPLE:. / *

* *

error handler

iinclude set jmp. h

#include stdio. h

jmp buf err;

idefine error (n) longjmp (err, n)

main () (int code;

if (code = setjmp (err) )fprintf (stderr, " \nerrbr(%d) \n

process () ;code) ;

1 n 1"n

Page 297: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

The CSTDIO Librar

sin#include th.

double sin (x)double x;

sin computes the sine of its radian argument x. The meaningfulnessof the result depends upon the magnitude of the argument.

sin return the sine of its argument. sin doesn t set any errorcodes.

acos (), asin (), atan (), cos (), tan

10, 121

Page 298: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

sprintfvoid sprintf ( buf, fCB, (, arg) ...char buf ( ), fcs () ;

sprintf formats the output into buf, which must be large enough tocontan the output.

The format control strg,fcs, contas both ordinar characterswhich are copied unchanged to the output, and conversion controlsubstrgs which describe how each arg is to be formatted. fcs

described in printf

RETURS:' sprint! doesn t return a value.

SEE ALSO: fpr ntf (), prinif (), scanf

EXAMPLE:** format an array of longs as a long string

** (

256 bytes) and send to file fh

int lsfmt (da, n, fp)double *da;int n, fh;

char fcs (256), buf(4096J;int oldsp, newsp, double *dp;

for(i = 0, fcs(O) = '\0' ; i n; i++)strcat(fcs, " 16g

oldsp = _showsp () ;setsp (newsp = oldsp - n * sizeof (double)

) ;

for (i = 0, dp = newsp; i n; i++)*dp++ = , *da++; /*copy to stk for sprintf*

sprintf (buf, fcs);setsp (oldsp) ;

strcat (buf, U\nreturn write (fh, buf, strlen (buf)) ;

101'7'7

Page 299: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

The CSTDIO Libra

sqrt#include th.

double sqrt (x)double x;

sqrt computes the square root of

sqrt returns the computed square root. If is -: 0. sqrt returns0 and sets erro to EDOM.

exp (), log (), pow

10.123

Page 300: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

NOTE:

EXAMPLE:

The CSTDIO Libra

srand. void srand(seed)

int seed;

srand sets the seed for the radom number generator to seed.

sTand returns no value.

frand(), rand()

The internal form of the seed for the generator is along. srand, only sets the low-order word, so the generator canot be restaredto its initial value. Solution: seed the generator with your owninteger before any calls to rand

o.r /rand.

** keep simulating the same pattern

puts ("Starting...do (

srand (1); , / * ini t generator

* /

simulate () ;puts ("One more time? (y/n)...) while (toupper (getchar

()) == ' y ' ) ;

1()1')A

Page 301: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

NOTE:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

sscanf

int sscanf (buf, fcs (, ptr

) ...

char buf(), fcs

();

sscanf reads from the strng buf, assembles data under thespecifcation offcs, and stores the data at ptr.

The format control strg, fcs, is described in scanf.

sscanf returns the number of fields scaned and assigned. A retUrnof zero mean no fields were converted.

Use sscanf when the input line being scaned exceeds 256 bytes.

fscanf (), scanf

** scan a very long line of doubles** with a space from file fp** return number scanned

that begin

lscanf (fp, da)FILE *fp;double *da;

int i, n = char buf (4096) , *bp = buf;

if (fgets (buf, 4096,return 0;

while (i = sscanf (bp,da,

fp) == NULL)

%d %d %d %d"da + 1 , da + 2 , da + 3) ) (

n +a i;da += i;while (i--)

bp = index (bpif(i oe 4)break;

+ 1, Ox20);

return n;

10.12

Page 302: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

strcatchar *strcat (dst, src)char *dst, src t) ;

strcat appends a copy of src (including the terminating' \ 0 I ) tothe end of dst .

There is no test for overfow.

strcat returns a pointer to the concatenated strng, dst.

strncat ()

** concatenate src to the nd of dst.** dst is assumed to be large enough

to hold both dst and src

* *

return dst

*/

char * strcat (dst, src)char *dst, *src; (

char *ret = dst;

while (*dst++)

dst-- ;while (*dst++ = * src++)

return ret;

10 1"'

Page 303: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Library

strchr#include strinq. h

char *strchr (char *str, char c);

strchr locates the first occurrence of c in the string str.

The terminating null character is considered to be part of the string.

strchr returns a pointer to c , or NULL if c doesn t occur in str .

#include string.#include stdio. h

char * strchr (char * str, char c) tint n;

n = strlen(str) + 1; /* include null */while (n--

if(* str++ == return str -

return NULL;

10. 126-

Page 304: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

-- -

Ii

:/

f! . '

/ "

Iii

, ty \....\ V r

: ' " ;',,.\.,

I . ti

'''

,if

/"

;)jvviJrl

Page 305: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

strcmpint strcmp (sl, s2)char *sl, *s2;

strcmp compars the the contents of s1 with the contents of s2. Thecomparson stops when a mismatch occurs or when the end-of-

strg charcter ( , \ 0 ' ) is encountered.

strcmp returns a value indicating the result of the comparison.

Comparisons1 is lexically greater than than

s1 is lexicaly equal to

s1 is lexicaly less than

strcmpi () strncmp ()

** comapre two strings

int strcmp (s1, s2)char *s1, *s2; (

if(s1 == 52)return 0;

while(*s1 == * s2++)if (*51++ == '\0'

return 0;return *s1 - * (--52) ;

10.127

Page 306: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Librar

strcmpiint 8trcmi (81, 82)char *81, *82;

strcmpi compares the the contents of sl with the contents of

without regard for case the upper and lower-case fonns of acharcter are equivalent. The comparson stops when a mismatchoccurS or when the end-of- strig character ( I \ 0 ' ) is encountered.

RETURS: strcmpi return a value indicating the result of the comparson.

Comparisonsl is lexically greater than th

sl . is lexicaly equal to

sl is lexicaly less th

SEE ALSO: strcmp (), strncmp

EXAMPLE:** comapre two strings without regard to case

int strcmpi (sl, s2)char * sl, *s2;

if ( s 1 == s 2 )

return 0;while (tolower (* sl) == to lower (* s2++) )

if ( * s 1 ++ == I \ 0 I )return

return tolower(*sl) - tolower(*(--s2));

1( l?R

Page 307: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

strcpychar *strcpy(dst, src)char *dst, src

() ;

strcpy copies src to dst , stopping after the terminating I \ a I hasbeen trsferred.

There is no test for overfow.

strcpy returns a pointer to the copied strng, dst.

strcat () strncpy()

** copy src to dst

char * strcpy (dst src)char *dst src; (

char *ret = dst;

while (*dst++ = *src++)

return ret;

10.1 29

Page 308: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The STDIO Libra

strcspnint strcspn (sl, s2)

, char sl(J, s2(J;

strcSpn searches sl for any of the characters in s2. The index ofthe fIrst character found is also the length of the begining substringof sl that consists entiely of charcters no in s2. TerminatingI \ 0 I charcters are not par of the search.

RETURS: strcspn returns the index of the fIrst charcter of sl that is in s2..

SEE ALSO: strspn ()

EXAMPLE:** return the number of characters in the** begining of sl that are ' NOT in s2

int strcspn(sl, s2)char *sl, *s2; (

char * slp, * s2p;

for (slp = l; *slp; slp++) for (s2p = s2; *s2p && *s2p != * slp; s2p++)

, if (* s2p)break;

return slp - sl;

10.130

Page 309: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Library

strdupchar *strdup (src)char src();

strdup allocates storage space via malloc for a copy of str andcopief; stT' (including the terminating I \ 0 I ) into that space.

strdup returns a pointer to the allocated area, or NULL if the areacouldn t be allocated.

malloc (), strcpy

** save a copy of a string

char * strdup (str)char *str; t

char *sav, *malloc () ;

if (sa v = malloc (strlen (str)strcpy (savr str);

return sav;

+ 1))

10. 131

Page 310: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

stricmp#include string. h

int stricmp (char *s1, char *s2);

stricmp compares the string pointed to by s2 to the string pointedto by sl , without regard to the case of the characters.

RETURNS: stricmp returns a value indicating the case insensitive

lexicographical relationship of sl to s2 as follows:

Meaning

.:0

::0

sl is less than s2 .

sl is identical to s2 .

sl is greater than s2 .

EXAMPLE: #include ':stddef . h::#include ':string. h::#include ':ctype. h::

#define TU (c) toupper (c)

int stricmp(char * sl, char *s2)

int n1, n2, c1, c2;

n1 = strlen (sl) ;n2 = strlen (s2) ;if (nl :: n2)

n1 = n2;while (n1--)

if ( (c 1 = TU ( * s 1

++)) !

return c1 - c2;return TU (*sl) - TU (*s2) ;

(c2 = TU (*s2++)))

10.132

Page 311: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Library

strlenint atrlen (char arc

())

strlen counts 1i1.e number of characters in src , excluding theterminating I \ 0 '

strlen returns the length. There are no error codes.

** return the string length

int strlen (str)char *str; t

char *beg = str +

while (* str++)

return str - beg;

10.132-

Page 312: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

l)l

/fff\J UrT\ (\.Ef):"l' /

./1-"

.j

Page 313: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Librar

strlwrint strlwr (src)char s rc (J ;

strlwr convert any upper-case characters in src to lower-case.

strlwr returns a pointer to the converted strng, src.

strupr ()

** convert string to lower case

char *strlwr (str)char *str;(

char * ret = str;fore; *str; str++)

str = to lower (*str) ;return ret;

10.133

Page 314: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

strncatchar *strncat (dst, src, max)char *dst, arc r) ;int max;

strncat appends, at most, ma bytes of src to the end of dst .

RETURNS: strncat returns a pointer to the concatenated strg, dst.

SEE ALSO: strcat EXAMPLE:

** concatenate at most n bytes of src to dst;

** return dst

char * strncat (dst, src, n)char *dst, *src;int' n;!

char * ret = dst;

while (*dst++)

dst--while (*dst++ = * src++)!

if (n--)

continue;* (--dst) = '\0'break;

return ret;

10, 114

Page 315: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

, strncmpint 8trncmp(81, 82, ma)char *81, *82;int max;

strncmp compares, at most, ma bytes of the two strngs sl and s2.

strncmp return a value indicating the result of the comparison.

Comparisonsl is lexically greater than th

sl is lexicaly equal to

sl is lexicaly less than

strcmp (), strcmpi

** compare at most n bytes of two strings

int strncmp(sl, s2, n)char * sl, * s2;int n;

if(sl == s2)return 0;

while (n-- && *sl == * s2++)if ( * s 1 ++

== '

\ 0 I ) re:turn 0;

return n == 0 ? 0 : * sl - * (--s2);

10.135

Page 316: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

NOTE:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

strncpychar *strncpy(dst, src, Ian)char *dst, src(l;int Ian;

strncpy copies exactly len bytes of src to dst trncating orpadding with I \ 0' as required; dst may not be null-terminated ifstrlen (src) = len.

strcpy returns a pointer to the copied strg, dst.

The returned strg is not terminated with a ' \ 0' if is greaterthan or equal to strlen (src).

strcpy ()

** copy src to dst -- truncate or pad with 0** so that exactly n bytes are copied

** return dst

char * strncpy(dst, src, char *dst, * src;int n;!

char * ret = dst;

while (n--)if((*dst++ = *src++) == ' \0'

while (n--*dst++

= '

\0'break;

ret urn ret;

10 n/\

Page 317: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Library

strpbrkchar *strprbk (sl, s2)char sl(), s2();

strpbrk searches sl for any character from s2. The terminatingI \ 0 I characters are not included in the search.

strpbrk returns a pointer to the first character found, or NULL ifthe strings have no character in common.

index (), rindex

** return pointer to first char in sl that is** also in s2 -- NULL otherwise

#define NULL (char *)

char * strpbrk (sl, s2)char *sl, * s2; i

char * s2p;

do (for(s2p = s2; * s2p && * s2p != * sl; s2p++)

if(* s2p)return s

) while (* sl++) ;return NULL;

10.137

Page 318: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

strrchr#include strinq.

char *strrchr (char *str, char c);

strchr locates the last occurrence of c in the strng str .

The terminating null character is considered to be part of the string.

RETURNS: strrchr returns a pointer to c , or NULL if c doesn t occur in str .

EXAMPLE: #include ,string. h#include ,stdio. h

char *strrchr (char * str, char c) char *beg = str;while (* str++)

while (-- str = beg)if ( * s t r == c)

return str;return NULL;

10. 138

Page 319: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Library

strrevchar *strrev (src)char src (J;

strrev reverses the order of characters in src.

strrev returns a pointer to the altered string, src.

strcpy (), strset

** reverse elements of a string

char * strrev(src)char * src;-(

char *beg, * end, ch;

beg = end = src;while (* end++)

end -= 2; /* pointwhile(end beg)-(

ch = *end;*end-- = *beg;*beg++ = ch;

return src;

to last char *

10. 138-

Page 320: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

()

:-f_l, rf/l,-.

-tJ:A\/ l'L/

()/

L./vO.l

';

(yf:a"vt/

Page 321: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

EXAMPLE:

The CSIDIO Libra

strsetchar *atraet (dat, ch)char dat rJ, ch

strset sets all of the charcters of dst to ch.

strset return a pointer to the altered strng, dst.

setmem ()

** fill dst with ch

char * strset (dst, ch)char *dst, Chi

char * ret = dst

while (*dst)*dst++ .. Chi

return reti

10. 139

Page 322: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

strspnchar *strspn (sl, s2)char *sl, *s2;

strspn searches i1 for a chacter that is not a member of s2. Theindex of the fIrst charcter in s1 no in s2 is also the length of thebeging substrg of s1 that consists entirely of charcters in s2.Terminating' \ 0' charcters are not par of the search.

strspn retu the index of the fIrst charter of s1 that is no in s2..

strcspn ()

** return length of initial substring of sl** made up solely from members of s2

int strspn (51, s2)char *sl, * s2; (

char *slp, * s2p;

for (sIp = sl; *slp; slp++) for(s2p = s2; *s2p && *s2p 1= * slp; 52p++)

if(*s2p == ' \0'break;

return sIp - 51;

10. 140

Page 323: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Library

strstr #include string h;)

char *strstr (char *sl, char *s2);

strstr locates the first occurrence of s2 (excluding the terminatingnull character) in sf .

strstr re.turns a pointer to the occurrence of s2 , NULL otherwise.

#inc1ude string. h#inc1ude stdio. h

char * strstr(char * sl, char *s2) 'tint n;

it(n = st!len(s2))whi1e(sl = strchr(sl,

it(memcmp(sl, s2,return sl;

s 1 ++;

return NULL;

10. 140-

s2)) tn) ==

Page 324: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Library

strtod strtol#include stdlib.

double strtod(char s(), char **eptr);

long strtol (char s (), char **eptr, int b);

strtod and strtol convert to a double or a long, respectively.

The conversion continues until the first character which cannot beconverted is found. If eptr is notNULL, a pointer to the 'terminating character is put in eptr.

If is between 2 and 36, it is used as the number base for theconversion. If is 0, then the initial digits of are used to

determine the base: if s (0) is I a I and s L 1) is an octal digit, then

the base is 8; if s (0) is ' Ot and s (1) is either I x I or ' X " thenthe base is 16.

strtod expects to contain a string of the form

(whitespace) (+1-) (digits) (. digits) (eIE) (+1-) (digits)

strtol expects s to contain a string of the form

(whitespace) (+1-) (0) (xiX) (digits)

RETURNS: strtod and strtol return the converted value, if any. If noconversion could be performed, zero is returned. If the correctvalue would cause underfow or overfow, plus or minusHUGE VAL is returned from strtod and LONG MAX or LONG MINis returned from strtol , (according to the sign of the value ), and

ermo is set to ERANGE.

EXAMPLE: #include stdlib. h

#include stdio. h

double getIntval (void)

char buffer (80);

fgets (buffer, sizeof (buffer), stdin);return strto (buffer, NULL, 0);

10. 140-

Page 325: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

strtokchar * strtok (str , dl)char *str, *dl;

strtok decomposes str into a sequence of tokens delimited by one ormore of the delimiter characters of dim. The tokens are returnedvia a series of calls to strtok.

The fIrst cal to strtok specifies str, whie subsequent calls subtitueNULL for str.

Each call skips initial delimiters (I.e., strspn (str, dIm) ), andthen scan for the trling delimiter (I.e., strpbrk (str, dIm) ) .

strtok returns a pointer to the fIrst/next token in str, or NULL ifthere ar no more tokens.

All tokens ar terminated with' \ 0 ' .

strcspn (), strspn

/* break string into tokens /*

char *strtok(str, dIm)char * str, *dlm;

char *beg, *end, *strpbrk () ;static char *nxt;

if ((beg" (str == NULL) ? nxt : str) == NULL)return NULL;

beg.. beg + strspn (beg, dIm);if (*beg ..,. ' \0'

return NULL;if ((end = strpbrk (beg, dIm)) == NULL)

nxt = NULL;else (

end++ = ' \0'nxt .. end;

return beg;

10. 141

Page 326: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

struprint strupr(src)char src ();

strupr converts any lower-case characters in src to upper-case.

strupr returns a pointer to the converted strng, src.

strlwr ()

** convert string to upper case

char * strupr(src)char * src; (

char *ret = src;

for (; *src; src++)src = toupper (*src) ;

ret urn ret;

10, 1.:?

Page 327: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

EXAMPLE:

The CSTDIO Librar

system#include stdlib. h

int system (char cmd

() ) ;

system invokes the DOS COMMND. COM to execute cmd .

system uses the environment variable COMSPEC to locate

COMMAND. COM.

system returns 0 if cmd was successfully executed, - 1 otherwise.

#include stdlib. h

int system (char cmd

() )

char path(65), arg(129);

getenv(" COMSPEC" , path);

strcpy(arg,

strcat (arg, cmd);if (exec (path, arg))

return -1;return 0;

10. 142-

Page 328: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

d/r

Page 329: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

The CSTDIO Libra

tan'include th. h

double tan (x)double Xi

tan computes the tagent of its radian argument x. Themeangfulness of the result depends upon the magnitude of theargument.

tan return the tagent, or a huge number and sets errno

ERAGE at its singular points.

acos (), as in (), at an (), cos (), sin

10. 143

Page 330: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

timesvoid times (buf)char buf(9);

times formats the strig buf with the current time as "hh-mm-

If hh, mm or s s are less than 10, they wil be formated with a space(0x20) as their flft charcter.

RETURS: times return no value.

SEE ALSO: ct ime ()

EXAMPLE:** sleep n seconds

sleep (n)int n;

char cur(9), ref(9);times (cur) ;while (1) (

times (ref) ;if (strcmp (cur, ref))

if (n-- == 0)return;

elsestrcpy (cur, ref) ;

t() tllll

Page 331: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

The CSTDIO Libra

to lower, to upperchar tolower (c)char c;

char toupper (c)char c;

wer convert upper-case letters to lower-c se. toupperperforms the opposite conversion.

Both functions retu the converted charcter, or c unchanged if itisn t the correct case.

These are functions rather than the usual macro implementation.

** if c is upper case, return lower case** else return c

tolower (c) (char c; (

if(c

= '

A' && c

= '

c -= ' A' - 'return c;

** if c is lower case, return upper case** else return c

toupper (c) (char c; (

if(c

= '

' && c

= '

C += I A' - 'return c;

10.145

Page 332: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

NOTE:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

ungetc#inc1ude stdio. h

int ungetc (ch, fp)char chiFILE *fp;

ungetc pushes the charcter ch back onto the fiefp. The next callto getc or fgetc wil return ch .

Ony one charcter can be pushed back onto fp between calls to getcor fgetc

ungetc returns or - 1 if it can t push the charcter back.

fseek clears all pushed charcters.

EOF (- 1) can t be pushed.

getc (), get char

1* get an unsigned number from console

ttdefine val (ch) (isdigit (ch) '? ch - '

: \

10 + tolower(ch) - '

long ctol (base)int base;

long num = OL;int d, Chi

if (base 0 II base 36)return val;

while(isalnum(ch = getc(stdin)) &&(d = val (ch)) base)

num = num * base + d;ungetc (ch, stdin);return num;

1n1A,C

Page 333: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

The CSTDIO Librar

unUnkint unlink (oldFile)char *oldFile;

unlink deletes the fie oldFile. Under DOS 2.0 and higher oldFile

may contain a path specification.

unlink returns 0 if successful, or - 1 if oldFile doesn t exist, is open

or if an error is detected.

10.147

Page 334: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

EXAMPLE:

The CSTDIO Librar

utoa#include stdlib. h

char *utoa (unsigned v". char s (), int r);

utoa converts v into a null terminated string at s. r specifies thebase of v ; it must be in the range 2 36.

If is 10 and v is negative, the first character of wil be the minussign

, '

utoa returns a pointer to s .

utoa is implemented as a macro

#include -Cstdlib.

/* convert unsigned to string *

char *utoa (unsigned val, char *str, int rad)

return 1 toa ( (long) val, str, rad);

10.148

Page 335: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Librar

writeint write (handle, buf,int handle;char *buf;unsigned count;

count)

write writes count bytes from but to the fiefp.

write starts writing at the current position of fp. After the writethe current position has advanced count bytes.

write returns the number of bytes actually written, or - 1 if an erroroccurred.

fputc (), fputs (), printf

** Small Case block transfer

xfer (ih, oh)int ih, oh;

char *buf, * _memory () ;unsigned size, amt;

freeall (256); /* min stack * buf = _memory() + 1; /* point tosize = (unsigned *) buf & OxF800;buf += 2; /* point to buffer * do

amt = read(ih, buf, size);if (amt && write (oh, buf, amt)

puts (" xfer: write error);exit (2)

J while (amt == size);close (oh) ;

size *

/ *

% 2K * /

!= amt)

10. 148-

Page 336: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

I/IJ

j, ./ ())\.

(A1)-

,;'

r ,/ t.

;/ '

ttN,JI

Page 337: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

EXAMPLE:

The CSIDIO Librar

dointextern unsigned _rax, _rbx, _rex, _rdx,

rsi, _rdi, _res, _rds;extern ehar - carryf, - zerof;

void - doint (inum)!=har inum;

doint wil cause software interrpt inum and may be used to callwhatever routies are available in the paricular machine.

JGX Jds conta the values of the corresponding 8088 internal

registers that are loaded and saved by doint .

carryis the car flag; zero/is the zero flag

If Jds

is set to -1, the curent value of the DS register is used.

doint returns n9 value. The interrpt may return values in Jox

os ()

** get current cursor location via int 10H

ide fine scr row()fdefine scr col ()

(scr curloc () :;:; 8)

(scr curloc () & OxFF)

scr curloc () (extern unsigned _rax, _rbx, _rdx;

rax = Ox0300;rbx = 0;doint (Ox10);

return _rdx;

/* AH = 3 *

10. 149

Page 338: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

NOTE:

The CSTDIO Librar

getsint _qets (buf, max);char buf (J ;int maxi

gets obtais a strg of not more than max - 1 characters from theconsole into buf

Editig proceeds as with gets.

gets returns the number of charcters obtained, or 0 on end of fieor an error.

fscanf (), fread

gets doesn t return the CR character.

1 n 1

Page 339: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

EXAMPLE:

The CSTDIO Libra

in, _outchar - inb (port)unsigned port;

unsigned _inw(port)unsigned port;

void _outb(ch, port)char Chiunsigned port;

void _outw(wd, port)unsigned wd, port,

inb and inw read the byte ch and word respectively, fromthe indicated port.

outb and outw wrte the byte ch and word wd, respectively, ofdata out to the indicated port.

inb and inw - return the byte or word read. There are no errorvalues or codes.

** read comm port

'define MCR (port + 'define LSR (port + 5)tdefine MSR (port +

tdefine DSR ' Ox20tdefine RDY OxOl

agetc (port)int port;

outb(l, MCR); /* set DTR */while (

! (

inb (MSR) & DSR))/* wait for data set ready *

while (

! (

inb (LSR) & RDY))/* wait for data *

return _inb (port); /* read data * /

10.151

Page 340: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

NOTE:

The CSTDIO Libra

Imove(small case model)

void _1move (num, sp, sseg, tp, tseg)char *sp, *tp;unsigned num, sseg, tseg;

lmove moves num bytes from the 8088 physical address atsseg:sp to tseg:tp For example, to move the color display framebuffer at addrss OxB800: 0 to a local buffer showds providesthe C progra data segment - DS)

lmove(4000, 0, OxB800, buffer, _showds());

/move returns no value.

move ( )

/move taes advantage of the 8088 intrctions for a fast datamove. It handles overlapping moves correctly so that

lmove (3920, 0, OxB800, ' 80, OxB800)

wil move OxB800: 3919 to OxB800: 3999, OxB800: 3918 toOxB 8 0 0 : 3998 etc. rather than propagatig OxB80 0 : O.

11\

Page 341: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

memqry(small case model)

char * _memory () ;

memory returns a pointer to the firt free byte beyond theunitialized data area in the small case model.

See the Memory Management discussion of the memoryallocation area.

malloc ()

** get the size of the malloc area

struct char stat;unsigned size;char data(l);

maxMem (stack)int stack; /* size of stack expansion area */

char *mp, * memory

();

freeall (stack) mp = _memory () ;return mp- size;

10.153

Page 342: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

NOTE:

The CSTDIO Libra

movevoid _move (numer, sourcePtr, targetptr);unsigned numer;char * sourcePtr, *targetptr;

move moves number bytes from sourcePtr to targetPtr .

nwve returns no value.

lmove ()

-,nove taes advantage of the 8088 intrctions for a fast datamove. It handles overlapping moves correctly so that

char buffer (80) ;

move (79, buffer, &buffer (1)) ;

wil move buffer (78) to buffer (79), buffer (77) tobuffer (78) etc. rather th propagate buffer (0). Use

setmem to fill a range of memory with a value.

10. 154

Page 343: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURS:

SEE ALSO:

EXAMPLE:

The CSTDIO Libra

char _os (inum, arg)

char inumiunsigned argi

os provides an elementa interface to the BIOS.

inwn goes into AH arg into :QX, and an int 21H is executed.

os returns the value returned from the interrpt in the 808X ALregister.

doint ()

** use DOS function 09H to print a string

main () (os(9, " Hello World! !$"

10 1

Page 344: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Libra

peek

, _

pokechar -peek (sp, sseg);char *sp;unsigned Bseg;

void -poke (ch, tp, tseg);char ch, *tp;unsigned tS8g;

yeek is used to retreve a byte ch from the 8088 physical addressat sseg:sp .

yoke is used to store the byte ch of data to the 8088 physicaladdress at tseg:tp .

RETURS: yeek return the byte yoke returns no value.

EXAMPLE:** get environment strings - small case** assumes environ is lower in memory than PSP

extern unsigned -pcb; /* PSP address */

getEStrO funs igned memory (), env, size;

env = -peek (Ox2D, _pcb); /*high-order byte* /env = (env 8) I -peek (Ox2C,-pcb);size = ( pcb - env) 16;

I move (size, 0, env, _memory(), _showds ());

ret urn _memory () ;

10.156

Page 345: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

SEE ALSO:

EXAMPLE:

The CSIDIO Libra

setmvoid _setmem(dst, numer, ch);,char *dst, ch;unsigned numer;

setmem sets number bytes of memory staring at dst to the bytevalUe ch .

setmem returns no value.

strset(), _move()

** zero an array - use instead of

**

for (i=O; i SIZE; i++) data (i) = 0;

ide fine zArray (a) _setmem (a, sizeof (a), 0),

double test (1024);

zArray (test) ;

10.157

Page 346: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

RETURNS:

NOTE:

The CSTDIO Libra

setspvoid _setsp (sp)char *sp;

setsp sets the stack pointer (the SP register) to sp .

setsp returns no value.

In small case, sp can rage from 0 to OxF. In large case, therage is 0 to the size of the stak - 1.

10 1 "R

Page 347: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

The CSTDIO Librar

showcs

, _

showds, _showspunsigned _showcs () ;unsigned _showds ();unsigned _showsp();

RETURS: showcs returns the pargraph address of the code segment (the CSregister).

showds returns the pargraph address of both the data and stacksegment (the DS and SS regis ers) in small case and the data segmentin large case.

showsp retu the contents of the SP register in small case andSS:SP in large case.

10.159

Page 348: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 349: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A

Messages

ASM88 Assembler MessagesBaner and Tennination MessagesASM88 Fatal Error MessagesASM88 Error Messages

BIN MessagesBaner and Termination MessagesBIND Fatal Error MessagesBIN Warng Messages

C88 Compiler MessagesBanner and Termination MessagesC88 Fatal Error MessagesC88 Error MessagesC88 Warnng MessagesASM88 Messages from C88

CLIST MessagesBanner and Termination MessagesCLIST Fatal Error Messages

D88 Messages

LIB88 MessagesBanner and Termination MessagesLIB88 Fatal Error MessagesLlB88 Waring Messages

SEE MessagesBaner and Termination MessagesSEE Error arid Status Messages

A.1A.2A.2

A.9

A.18-

18-18-

A.21

A.22

A.23A.23

Page 350: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 351: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

ASM88 Messages

.Banner andJenninatlon Messages

ASM88 8088 Assembler V1. (c) Mark DeSmet, 1982-86

(varous error messages)

end of ASM88 0016 code 0000 data 1% utilization

The 'code ' number is in hex and tells how many bytes of code were produced. Thedata' number is similar and tells how many bytes of data were produced. Theutilzation percentage shows how full the symbol table was.

Sample of list output:

00 5A001 580023C61

00 3C7B

ASM88 Assembler BLIP.1 ;TOUPA convert a charte to upper case

3 CSEO4 PULIC TOUPPE

6 ; charcte = toupper(harcter)

15 TO OONE:16 -

TOupPE: popPOP

SUBMOV

AL,'aTO OONEAL;zTO OONEAL;aAH,

;R ADDRESS;CHCf;IF LOWER TH ';D N01G;OR IF ABOVE ';D NOTIG;E ADJUST;RETU AN !N;RETU

006 2C20008 B400OOA FF2

ASM88 prits two categories of messages: fatal errors and errors. As with C88, thefatal errors are caused by I/O errors or similar. Errors are simply syntax errors inusing the language. When a fatal error is detected, ASM88 prints a message andstops. An error does not stop the assembler, but it stops writing the object moduleto l1n faster. If errors are detected, the object module is never good.

Page A.

Page 352: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

ASM88 Fatal Errors

cannot close oefie the fie could not be closed. An I/O error occurred.

cannot create oefie the named fie could not be created. The name is atemporar name or the name of the object or list fie. This message usuallymeans the drive is full (see ' T option).

cannot open oefie the named soure or include me could not be found.

cannot read oefie the named fie could not be read. Usually means an 110error was detected.

cannot unlink oefie the tempora fie could not be deleted. An I/O erroroccurred.

cannot write oefle the named fie could not be wrtten. An I/O error wasdetected. Usualy means the disk drve is out of space. '

internal error in jump optimization the assembler became confusedoptiizing branches.

no input fie - no fiename followed the ASM88 when invoked.

too many labels only 1000 labels are allowed.

too many symbols the assembler ran out of symbol space. The sourceprogra should be broken into smaller modules.

Error messages have the fonn:

44 mov #44,error: illegal mnemonic

Page A.2

Page 353: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

, if the error was found in an include fie:

44 mov #44,file: 2: SCREEN. A error: illegal mnemonic

The messages are:

address must be in DSEG address constats can only be in DSEG becauseconstats in CSEG are not fixed up at run time.

bad DS value - a constat expression must follow the DS.

bad include the COrrect form for an include statement is:include " filename

bad LIN value the line statement should be follo ed by a constant.

cannot label PUBLIC - a 'public' statement canot have a label.

data offset must be an unsigned - an attempt was made to use an offset in abyte or long c6nstat.

DS must have label- storage canot be reserved without a n

DS must be in DSEG storage can only ,be reserved in DSEG.

duplicate label- the label on the line was defined previously.

equate too deep - an 'equ' may reference a prior one, but only to a depth offour.

ilegal expression - the expression had an ilegal operator or is somehowinvalid.

ilegal operand - an operad had a tye that was not legal in that context.

ilegal reserved word - a reserved word was found in the wrong context.

ilegal ST value the index to a floatig point stack element must be in therage 0 to

Page A.3

Page 354: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

incorrect type only 'byte

, '

word'

, '

dword' , and ' tbyte , are allowed followingthe colon to tye a public.

impossible arithmetic - an arthetic operation has operads incompatiblewith the 8086 architecture, for example:

add word (bx), word(si)

in wrong segment - a varable or label is being defmed in a segment other thanthe segment of its 'public ' statement. Remember that 'public statements mustbe in the correct segment, following ' dseg' or 'cseg ' as appropriate.

invalid BYTE constant- a byte constat was needed, but something else wasfound.

invalid constant the instrction needed a constant and something else wasfound.

invalid DD constant the value of a DD' must be a constant expression.

invalid DW constant the value of a ' must be a constat expression or avarable name. In the latter case, offset is assumed. The statement:

offset zip

is ilegal since offset is already implied. Just use:

zip

invalid offset - an offset of the expression canot be taen.

line too long the maximum input line to ASM88 is 110 characters.

mismatched types the tyes of the two operads must agree.

example:

addaddadd

chrax, blchr, axword chr, ax

illegalillegal

; legal

Page A.4

Page 355: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

misplaced reserved word - a reserved word was found in an expression.

missing: the '7' operator was missing the colon par.

missing) mismatched parentheses.

missing) mismatched braces in an address expression.

missing

' -

labels to instructions must ,be followed by a colon. This messagealso prits when a mnemonic is misspelled. The assembler thins that the badmnemonic is a label without a colon.

missing EQU name - an equate statement lacks a name.

missing type the memory reference needs a type. In the case of 'publicdefmed elsewhere, the type can be supplied by ' :byte' or ' :word' on the publicstatement. In the case of anonymous references, the 'byte ' or 'word' keywordmust be used, for example:

publicinc ainc byte ainc es: (bx)inc es :word(bx)

a:byte; illegal; legal; illegal; legal

need constant something other than a constat expression followed a ret'.

need label- a jump relative was made to something other than a label. 'jmpmay be indirect but 1z s etc. can only jump to a label.

nested include - an included fie may not include another.

not a label - omy names can be public.

RB must have label- an 'RB' statement must have a label.

RB must be in DS - RB' s must follow a DSEG directive as they can only be inthe data segment. 'DB' s can be in the code segment.

RW must be in DS as above.

Page A.5

Page 356: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

too many arguments - the' instrction had more operads than allowed or thelast operand contains an ilegal op-code.

undefined variable c:name;: the name is referred to but not defined or listedas public.

unknown mnemonic the mnemonic is ilegal.

Page

Page 357: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

BIND Messages

Banner andJennination Messages

Binder for C88 and ASM88 V2 .end of BIND 9% utilization (c) Mark DeSmet, 1982-87

BIND Fatal Error Messages

BIN prits the message, prits ' BIN abandoned' and quits.

bad argument - an argument is ilegal.

bad object mec:name:: the object or libra fie contais an ilegal record.

bad stack option - the S' option should be followed by one to four hex digits.

cannot close c:e:: I/O errr occured.

cannot create c:e 110 errr or disk out of room. On MS-DOS 2.0 andlater, make sure that the CONFG.SYS fie contains a FIES=20 command.

cannot open c:me:: the object fie could not be found. On MS-DOS 2.0 andlater, make sure that the CONFG.SYS fie contains a FIES=20 command.

cannot read c:Ie:: - 110 error occurred.

cannot seek c:IDe:: - 110 error occurred.

cannot write c:e:: I/O error or disk out of room.

different segments for. c:name:: the public is declared in differentsegments in different modules probably both as a function and as a varable.

ilegal overlay number in the overlay options -VIi and -Mnn, the value nnmust be between 1 and 39 in ascending consecutive order.

multiply defied c:name:: the same public appears in two modules.

Page A. 7

Page 358: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

over 100 arguments - BIN only allows 100 arguments, including argumentsin -F fies.

over 64Kcode - a Small Case progra has over 64K of code. See thedescription of BIN overlay support.

over 64K data - a Small Case program has over 64K of data. This is notsupported. You wil have to move some data to locals or use overlays.

over 300 modules only 300 modules can be linked together. The suppliedlibrar only contains about 60 modules.

too many fienames there are only 2000 bytes reserved for all fienames.

too many labels in c:name:: - a module in the named fie had over 1000 labels.

too many total PUBLICS in c:name:: symbol table has overfowed. Thenamed fie was being read when the overfow occurred.

BIND Warning- Messages

undefined PUBLIC - c:name:: .. the name is referenced, but not defmed in anymodule. BIN wil complete and the resultig .EXE module may execute aslong as the undefined PUBLICs are not referenced. If they are referenced,then the result is undefmed.

Page A.

Page 359: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

C88 Messages

Banner and Termination Messages

)-C88 Compilerend of C68

V3. Copyright Mark DeSmet 1982- 1988001A code 0012 data 1% utilization

)-C88 Compiler V3.(various error messages)

Copyright Mark DeSmet 1982-1988

Number of Warnings = 2 Numb r of Errors = 5

The first form of termination means the compilation was successful. The ' codenumber is in hex and tells how many bytes of code were produced. The 'datanumber is similar and tells how many bytes of data were produced. The utilzationpercentage is the worst case of a number of compiler limits. If it nears 100% itusually mea,ns that the largest procedure should be broken into smaller procedures.

The second form means the compilation failed. Error messages are explained in thefollowing section. If any errors were detected, the compiler wil stop trying togenerate code and wil stop as soon as all the source has been read. This syntaxcheck' mode is fast and allows the programmer to correct the program with aminimum of delay. If only warnings are detected, but no errors , the compilationwil end normally and produce a .0 fie.

C88 produces four categories of messages: fatal errors, errors, warings and errorsdetected by the assembler. Fatal errors are usually caused by IIO errors butcompiler errors are also in this category. When a fatal error is detected, thecompiler wil print a message and quit. ErrQrs are caused by syntax errors. If C88is invoked from SEE, it returns to SEE upon the first error, otherwise it reports allsuch errors and then quits. Warnings are produced by correctable errors and thecompiler continues. Since the compiler only uses ASM88 as pass 3 if the -a optionor the #asm option is used, assembler detected errors are possible but rare. Whenthey occur, the object module wil not be usable.

It is easy to tell the category of an error. After a fatal error, the compiler stopswithout printing a termination message. Errors and warnings have a distinctiveformat which includes the word 'error' or 'waring . Assembler errors print theassembler line that was found offensive.

Page

Page 360: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

C88 Fatal Error Messages

The pass 2 fatal errors like 'bad expression' are compiler errors, but the error is

usually caused by missing the problem in pass 1 and printing a reasonable message.

If you get one of these errors, please send your program to C Ware, but you canprobably find and eliminate the statement that caused the problem. Don t be

frightened by seeing these errors listed; you wil probably never see any of them.

bad expression this indicates a compiler error. Printed by pass 2.

bad GOTO target attempt to goto something other than a label.

breaklcase/continue/default not in switch - a case or default statement mustbe within a switch. A break statement must be in a while, do...while, for, or

switch. A continue statement must be in a while, do...while, or for statement.

cannot address ilegal use of ' &' operator. Printed in pass 2.

cannot close ..fie:: the file could not be closed; An 110 error occurred.

cannot create ..fie:: the named fie could not be created. The name is a

temporary name or the name of the object or assembler file. This messageusually means the drive is full (see ' T' option).

cannot open ..fie:: the named source or include fie could not be found.

cannot read dUe:: the named fie could not be read. Usually means an 110error was detected.

cannot unlink dile:: the temporary could not be deleted. An I/O erroroccurred.

cannot write .cile:: the named fie could not be written. An 110 error was

detected. Usually means the disk drive is out of space.

error in register allocation compiler error in pass 2.

divide by zero - a constant expression evaluated to a divide by zero. Should

never happen.

Page A.

Page 361: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

E option not valid from SEE - You have specified the E option on the C88command line from SEE. Either remove the option, or exit SEE and run C88from the command line prompt.

function too big - a function is too big for the compiler. The 'Utilzationnumber reflects this limit so there is normally plenty of waring. The solutionis to break large procedures into smaller ones.

ilegal initialization for c:name:: only constant expressions and addressesplus or minus constant expressions can be used in initialization and theinitialization must make sense. For example

int a=b+2;

this error is fatal because it is not discovered until pass 2.

no cases - a switch must have at least one case.

no input fie - You must specify the name of the source fie.

out of memory the compiler ran out of symbol space. The 'utilzationnumbers war when a program is about to exceed this or any other compilerlimit. The compiler can use up to lOOK, so adding memory may be a solution.If not, the only remedy is the painful surgery required to red ce the totalnumber of externals and locals defined at one time.

pushed :- compiler error in pass 2 code generation. It can be eliminated bysimplifying the expression. stdin not a device - you have specified ' ' as the fiename , but stdin is not a

fie (isatty () is true). You must either redirect stdin, or use a pipe.

stuck c:register:: - same as 'pushed'

too many cases currently, a switch statement can only contain 128 casestatements.

too many externals the compiler currently has a limit of 500 static' s orexterns.

too many fors/too many whiles - whiles, do-whiles, switches and forstatements can only be nested 10 deep.

Page A.11

Page 362: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

C88 Eaor Messages

Errors are printed with the following format:

23 if (i , 99 $$ error :Need ()

, if the error was detected in an include fie:

23 if (i , 99 $$ file: ,include file error :Need ()

The number preceding the source line is the line number. To find the line, edit thefie and issue the command 'nnnJ' where nnn is the number of the reported line.

The '$$' shows how far into the line the compiler was before the error was detected.For example, the '$$' wil print imrnediately BEFORE an undefined variable.

If you get a lot of errors on a compile, don t panic. A trivial error probably causedthe compiler to become confused. Correct the first few errors and re-compile.

## can t be first the macro concatenation operator must occur between tokens.

#(#) can t be last - macro text must follow both the concatenation and strngifyoperators.

#asm option not on - a #asm directive is found without the extended keywordswitch on. Use the command line option px, or #pragma ex

#undef identifier not defined the identifier has not been # de fin e ' d.

bad control- the directive following the # is unknown.

bad declaration the declaration of a variable was ilegal.

bad include the #include must be followed by "name" or ,name , or a macrothat evaluates irito one of the previous two forms.

bad label- a colon is not preceded by a label name.

Page

Page 363: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

bad member declare the declaration of a member is ilegal.

bad member storage - an attempt was made to declare a member static orexternal. Members have the 1;torage type of their structor union.

bad parameter declare - an ilegal peclaratiQn of an argument or the name ofthe argument was spelled differently in the procedure heading and in thedeclaration.

bad statement ilegal statement.

bad STRUCT declare - an error has occurred in a struct declaration.

cannot initialize extern - extern variables are defined, and possiblyinitialized, elsewhere. You can have both an extern declaration anddefinition of a varable in the same source fie.

cannot #Undef predefined macros the predefined macro namesFILE

, _

LINE

, ...

) canot be undefined.

cannot redefne predetinedmacros the predefined macro names cannot beredefined.

case range option not on - a case cexpr

..

cexpr was, found and the extendedkeywords option is off. Use the px command line option or #pragma ex.

defines too deep #define may reference another, but there is a limit. When#defines are expanded, the number of active #defines cannot exceed 32.

duplicate argument - an attempt was made to declare an argument twice.

duplicate enum - enum s names must be unique.

duplicate label- two labels have the same name.

EOF within comment beginning at line nnnn - end of fie was found insidea comment which began at line nnnn. '*1' is missing.

EOF in macro argument -end-of-fiewas found while evaluating a macroargument. An unterminated comment or strng is the most likely reason.

Page A.13

Page 364: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

field needs constant the size of a bit field must be a constant expression with avalue of 1 to 16.

ilegal address attempt to use the '&' (take address of) operator on somethingthat is not an lvalue. '&44' wil generate this error. An address can only betaken of a variable, procedure, string or label.

ilegal arithmetic the requested pointer arithetic doesn t make sense.

ilegal assignment only a pointer, long, or constant can be assigned to a LargeCase pointer. Note: this is a pass 2 error the -c (checkout option) must beused to get the line number of the error.

ilegal define - a #define has unmatched parentheses or the #define parametersare ilegally specified.

ilegal double constant - a double or a float was specified usinghexadecimal notation and the result is not 8 or 4 bytes long.

ilegal external declaration caused both by an ilegal data or proceduredeclartion and improperly nested braces. If the line is supposed to be part ofa procedure (e.g. i=O;), the latter is the case. Verify that every T outside of acomment or quoted string has a matching T. Note: a prior error may havecaused the compiler to lose track of a '

ilegal index - a pointer canot be used as an aray index

ilegal indirection- something other than a pointer has been used as a pointer.

include nesting tOQ deep includes can only be nested 20 deep

ilegal structure assignment the two operands of an assignment operator arenot the same structure, or the same size.

ilegal type - an invalid type specifier combination has be n found.

ilegal use of FLOAT floating point numbers cannot be used as pointers.

invalid digit-sequence in #line the symbol following the # 1 in e directivedoesn t evaluate to a number.

Page A.

Page 365: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

invalid identifer in #ifdef/#ifndef the symbol following the #i fdef

#ifndef is not a vaild name (doesn t begin with a letter or underscore).

invalid identifier in #Undef the symbol following the #undef is not a vaildname.

invalid identifer in definedO operator the symbol following thedefined operator is not a vaild name.

invalid parameter - a parameter of a macro is not a valid name.

invalid string-literal in #line the symbol following the digit-sequence in the#line directive doesn t evaluate to a string literal.

line must be constant - a #line control must be followed by a decimal constant.

line too long the maximum line length is 509 bytes.

macro buffer overflow - more than 1024 bytes of argument text, or more than32 arguments were found.

member not in structure the varable following a ' .' or '

.:;

' operator is not amember of the struct or union that preceeded the operator.

missing "

, " , " , " , " , " , " , " , "

I" - the indicated '"' characteris needed at this point. A multitude of errors can cause these messages. Theerror might be fixed by inserting the indicated character where the '$$' printsbut the item following the '$$' could be ilegal.

missing - a character constant (e.

g. '

,'Ol' ) can only contain one or twocharacters.

missing argument fewer arguments are supplied in a function call than werespecified in the function prototype, or the argument list of a call had twoadjacent commas.

missing arguments - a #define was defined with arguments but used withoutarguments.

missing dimension - an array dimension was missing in an expression orstatement. Either int x()J; or x(J= l;.

Page A.15

Page 366: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

missing end of #asm - an #asm block was not ended with a #.

missing expression - an expression is needed here. An example of a missingexpression is i=;.

missing operand - an operator without an operand was found. An example of amissing operand is ++;

missing while - a 'do ... while' is missing the ending 'while

must have constant - C syntax requires a constant value at this point.

must return float in a function declared as returning a double or a float,the last statement is not a return floating-type

must return structure in a function declared as retuming a structurestructure- type either the last statement is not a return structure- type or a

return of something other than structure- type is found.

need 0 the expression following an 'if or 'switch' or 'while ' was not

surrounded by parentheses.

need'( for STRUCT initialization the initial values used to initialize astructure must be surrounded by braces.

need closing parenthesis - a macro parameter definition does not end in '

need constant - a 'case' prefix must be followed by an integer constantexpressIOn.

need label - a goto must reference a label.

need lval- an lvalue is needed here. An Ivalue is , roughly, something that can bechanged with an assignment. The statement: 2=4; wil produce this error.

need member the ' .' or '

-:;

' operators were followed by something other than amember name.

need structure in id member or id

-;:

member id is not a struct or

union, or a pointer to one.

Page A.16

Page 367: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

AppendixA: Messages

not enough #include buffer space - DOS cannot allocate space for an ,

# in c 1 u de fie buffer. Reduce RAM-disk size or remove TSR's to increaseavailable RA.

not enough arguments fewer arguments are supplied in a function call thanwere specified in the function prototype.

only STATIC and EXTERN allowed at this level- an attempt was made todeclare an 'auto ' outside of a procedure.

parameter must follow # the macro strngify operator must be followed by amacro parameter.

return lacks argument if a function is declared as returning a value, thenreturn;" is ilegal. Use "return 0;" if the value is unimportant.

sizeof operator not allowed in #if/#elif sorry, this is an ANSIrequirement.

sorry, must have dimension for locals the compiler does not accept chara(J=t1, 3)-; and similar for auto variables. Declare the variable static orinclude an explicit dimension.

sorry, no string initialization of AUTO the compiler canot accept chara()= abc ; and similar for auto variables. Declare the variable static ifpossible, otherwise use _move.

string too long - a string cannot exceed 255 characters. Usually means that ais missing. Use the strng concatenation feature to create long strings.

too many arguments - more arguments are specified in a function call thanwere specified in the function prototype.

undefined structure - a strcture is referenced without being defined.

undefined variable - an unknown id was found as an argument to a functioncall.

unknown control- the word following a '#' is not a control word. '#whilewould cause this error.

' '

Page A.17

Page 368: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

unmatched tI either the end of line or end of fie was found in a string. Thisusually means that a " is missing. If your string is too long for one line,continue with a \ (backslash) at the end of a line and continue in column one ofthe next. If you want a new line in a string, use \n.

wrong number of arguments - a macro was used was used with the wrongnumber of arguments.

C88 Warning Messages

Warnings indicate a change in syntax (as in the case of strctures), or suspiciouscode that is probably OK.

argument type conversion - a function argument doesn t agree with the type ofthe corresponding argument prototype. The argument is cast to the prototype.This waring is usually supressed. Use the pw command line option or#pragma w

conflcting types - an external or static was declared twice with different types.Usually caused by an include file declaring a variable incorrectly or by aprogram such as:

main () char ch;

charchar

ch=zipit

() ;

zipit (ch)

ch; t

return ch;

the call of zipit implicitly declares it to be a function returning an integer.The line 'char zipit(ch)' would be flagged as an error. The fix is to include:

char zipit

() ;

above the call so the function is declared correctly before use.

Page A.18 '

Page 369: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

member not in structure the member identified by struct.member or byptr-;:member is not a member of the specified structure. A ' (void *)pointer wil select any member of an anonymous structure.

must return float - a float or double functio:n must end with a return statementthat returns a value.

Note: The following functions ends with an if statement

double x() if (1) return 1. ;J.

returns structure the current function has been declared as returning astructure. This is to war you that the entire strcture, and not a pointer to itis being returned. This warning is usually supressed. Usethepw commandline option or #pragma w

structure assignment the strcture named as a parameter wil be pushed onthe stack rather than a pointer to the strcture, as was the case in previousreleases. This warning is usually supressed. Use the pw command line optionor #pragma w

undefined variable the variable has not been defined. It is assumed to be anauto into

C88 ASM88 Errors

In theory, any ASM88 error message can be produced by a C88 compile gonebonkers but I have only seen the ' cannot write o:name;: ' errors caused by lack ofdisk space.

Page 18-

, \

Page 370: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

CLIST Messages

Banner and Termination Messages

CLIST Vl. end of CLIST

(c) Mark DeSmet, 1982, 83,

CLIST Fatal ErrorMessages

All messages indicate fatal errors. ' CLIST prints the message, prints ' CLIST

abandoned' and quits.

cannot close fie;: I/O error occurred.

cannot creat fie;: I/O error or disk out of room.

cannot open fie;: the source fie could not be found.

cannot read fie;: I/O error occurred.

cannot write fie;: - 110 error or disk out of room.

no input fie - no list of fies followed CLIST on the invocation line.

out of memory - CLIST ran out of room. Break the list of fies in two.

Page A.18-

Page 371: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

D88 Messages

'" Control C '" - The user typed control-C or control-break. If control-C istyped while a user program is executing, the progra cannot be restarted.

cannot open c:fiename:: - Canot open the named fie for the List ofQuit-Intialize command.

cannot open xyzzy - The module containig the main () function was notcompiled with the .c switch. '

cannot read dilename:: - The named fie could not be read. Probably an 110erro

cannot repeat Again can only follow Again, Display, List or Unassemblecommands.

ilegal address - The & operator was applied to something not in memory, e.&1.

ilegal assignment - An attempt to assign an expression to a constant was made.Only memory references and register can be changed.

ilegal command - The cpmmand letter is not vaild.

ilegal operand - Ths is a catch-all error; it just means that the expressioncould not be pared corrctly.

ilegal value - The break numbers ar 1, 2, or 3.

invalid symbol- The name is not in the symbol table. Probably a typo ormissing 0 before a hex constant.

line not found - The line is unkown. Only executable lines have numberrecords. Other lines canot be referenced by number. The fie may not havebeen compiled with the -C option.

missing) missing J missing " missing Unmatched bracketingcharcter.

need a number - A line number contained something other than a digit. Noexpressions are allowed.

Page A.19

Page 372: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix. A: Messages

normal end - The program being debugged executed an exi t () call.

not in a C procedure - The Proc-step command can only be executed when thedebugger knows which procedure is being debugged. The Step command canbe used.

some symbols lost - The .CHK is greater than 55K bytes. Recompile thosemodules you don t wish to debug without the -c switch and rebind to reducethe size of the .CHK me.

Page A.20

Page 373: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

LIB88 Messages

Banner andJermination Messages:

Librarian for C88 and ASM88-TOUPPER-ISDIGIT-ISALPHAISALNISPUNCT-TOLOWERend of LIS88

V2. (e) Mark DeSmet 1982, 83, 84,

ISUPPERISASCII

ISLOWERISCNTRL

ISSPACEISPRINT

12' utilization

The list of code publics is only prited if the -P option is employed. A minus sign incolumn one indicates the sta of a new module.

LIB88 Fatal Error Messages

LIB88 prits the message, prits ' LIB88 abandoned' and quits.

bad argument c:argumenb the option is ilegal.

bad object fiec:name:- the object or libra fie contains an ilegal record.

cannot close c:fie:- I/O error occurred.

cannot creat c:lle:- I/O error or disk out of room.

cannot open c:fie:- the object fie could not be found.

cannot read c:fie:- I/O error occurred. '

cannot write c:fie:- I/O error or disk out of room.

no input fie - no list of fies followed LIB88 on the invocation line.

over 100 arguments - LIB88 only allows 100 arguments, including argumentsin - F fies.

over 300 modules only 300 modules can be linked together. The suppliedlibrar only contains about 60 modules.

Page A.21

Page 374: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

too many dependencies in -:name:: there is a total of over 1500dependencies between modules.

too many total PUBLICS in -:name:: symbol table has overfowed. Thenamed fie was being read when the overfow occurred.

LIB88 Waring Messages

warning: circular dependencies - two modules reference each other; this isOK if the first is always included whenever the second one is. The -N (need)option wil kil ths message.

Page A.

Page 375: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

SEE Messages

Banner and Termination Messages

When the SEE editor reads in a fie to edit, the menu line is replaced by the banermessage:

SEE (TM): Screen Editor V3. 0: Copyright 1982-1987 Michael Ouye

When the editor is exited, the message lie prints the message:

bye! -:filename

SEE Error and Status Messages

As commands ar executed, the editor wil display a number of status messages onthe message lie:

##

characters - Ths message is displayed whenever a fie is edited and whenthe Quit command is invoked. It shows the number of charcters contained bythe fie.

bad command.. Ths message is prited when there is no command thatcorresponds with the charcter tyed.

bad tag name - Ths message is displayed when a letter besides A C, or D wastyped for a tag name. can t fid " -:string:: - Ths message is displayed when a request to fmd the

strg fails. can t wrte to me mename:: try again? (y/n) - An errc occurred while

attempting to write the fie out to the disk. Type ' Y' to tr to write the fie the same fiename. Type ' N' to abort the attempt and use the Quit-Writecommand to wrte the buffer out to a different fie. .

hit a key to continue This message is displayed during the List comtnand toindicate that the next screenfll of text should be displayed.

Page

Page 376: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix A: Messages

ignore the changes? (yln) This message is 'prited when the memory bufferhas been modified and not saved to disk and the buffer is about to bereinitialized with the Quit-Initialize command or the editor is about to beexited with the Quit-Exit command. Type 'Y to continue the command, or 'N'

to abort the command.

no input fie - Ths message is prited when the Update or BAKup commandsare executed but no me was specifed on the command line. Use theQuit-Write command to write the buffer out to the disk.

reading fie: c:fiename:: no This message appear whenever a fie is readinto memory. The completion status of the read operation is appended to theend of the message. If everything goes well, the word "completed" wil beappended to the end of the message. Otherwise, the editor wil append thestrig "can t read fie" if an error occured while attempting to read the fie.

recording Macro F#, use Macro key to fmish recording - Ths messageis contiualy displayed as long as a Macro is being recorded. To end theMacro and the message, reinyoke the Macro command by typing the letter

Page A.24

Page 377: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B

The ASM88 Assembly Language

Identifiers

Constats

Expressions

RegistersGeneral RegistersByte RegistersSegment Registers

Addressing Modes B.3

086 Flags B.4

Address Expressions

Address Typing B.5

Comments

Assembler Direectives

Reserving Storage

Diferences between ASM86 and ASM88

8086 Instrctions

Elements of Instrctions

Instrctions

8087Control WoedStatus WordTag WordCondition Codes

8087 Instrctions

Page 378: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The
Page 379: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

Identifiers

Identifiers must star with a letter (A-Z, a-z, -., may contain digits, and havemaximum length of 31 characters. Upper and lower case letters are distinct soABC, abc and Abc ar thee distinct identifiers.

Constants

Constants are binar, octal, decimal, hex, floating point, or strng.

Binar constat: ddddb or ddddB where is 0 or 1.

Octal constat: ddddo or ddddO or ddddq or ddddQ where is between 0and 7.

Decimal constat: (- J ddddd where is between 0 and 9.

Hex constat: ddddh or ddddH where is 0 to 9, a to f, or A to F.

Floatig constant: (-) ddd ( . ddd) ( (+ (- J Edd) where is between 0 and 9.

Strg constat: . dddd' where is \n or \N for LF, \ t or \ T for TAB, " forthe single quote, \000 where the 000 must be octal digits andthe result is the corrsponding charcter, or any othercharcter.

After a DD (derme double-word) mnemonic, constats that conta a period or 'exponent ar single precision floatig point. Other constants are signed four byteintegers. After a DQ (derme quad-word) mnemonic, constants are doubleprecision floating point. A strg constat after DB may have up to 80 characters.In any other place, constat expressions are allowed and the result has a range of 0to 65535. There is no warg on overfow.

Page B.l

Page 380: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

Expressions

All expressions operate on unsigned 16 bit constats. There is no waring whenoverfow occurs. Caution: multiplying or dividing negative constants wil not givethe expected results. 3/- is not 3.

The operators are listed in order of precedence.

Registers

== !=

binar and.

equalty test and equality test Result is 0 (false) orI (hUe).

plus and minus.multiply and divide.(& and offset are the same). plus minus not exc1usive-or.

+ -* /

& offset +

! -

The 8086 has eight faily genera purose registers and four segment registers. Allregisters ar 16 bits wide.

General Re isters

The following registers can be used in arthetic or whatever but all have somespecialized use. Some intIctions have shorter forms using AX so AX is usually heavilyused as an accumulator. MO and DIY require AX. IN and out use AX.Used for addressing or for genera purposes.Used by LOOP and JCXZ. Also used to contain a shift count.Used by MU and DIY. Also used for varable port IN and OUT.Used for addressing and strg instrctions.Used for addressing and strg instrctions.

ed as a stack pointer to cess locals and arguents.Caution: C programs require BP to be preseIVed across calls.

The stack pointer.Used by CALL and RET. Be very careful when manipulating SP.

Page B.

Page 381: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Byte Re isters

Appendix B: The ASM88 Assembly Language

Each byte in the first four general registers can be addressed separately.

AH is the high byte of AX AL is the low byte. BX, ex, and DX are similar.The byte registers are: AH, AL, BH, BL, CH, CL, DH and DL.

Segment Registers

Points to the data segment. The intialization code makes DS address thedata in DSEG. All memory references that are not relative to BP and thatdo not include an explicit segment register overrde, refer to the segmentaddrssed by DS. 'Points to additional data segment C only uses ES when doing a move.The strg instrctions (movsb,cmpsb etc.) implicitly reference ES:(DI)for the taget. ES may be changed by any routie and is generally used toaddress data outside of DSEG and CSEG.Points to stack segment. C intialzation sets SS to DS. This equivalence isimportt for C progras so that they can create pointers to arguments orloca which ar on the stack. When it is necessar to change SS, a load ofSP must imediately follow.The code segment CS is set to CSEG by intialzation.

Addressing Modes

Only certin registers can be used to reference memory. The following are thepermissible combinations.

(BX+SI+displacement)(BX+DI+displacement)(BP+SI +displacement)(BP+DI+displacement)(SI+displacement)(DI+displacement)(BP+displacement)(BX+displacement)(displacement)

Names can be included in an address, e.g. blap (BX). The offset of the name issimply added to the displacement.

Page B.3

Page 382: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

Address s that include BP are assumed to be SS relative. Other addresses areassumed to be in DSEG, addressed by DS. To overrde this assumption, prefix anaddress with 'DS:

, '

ES: SS: or CS: The assembler automatically provides theprefix necessar for varables declared in CSEG.

Sample Addresses

hellosaveagain:

db . Hello 'dw mov save, mov hellot3,mov bx,mov hello (bx) , . ! Imov ax, offset againmov , mov ' ax, 0mov es, axmov ax, es: (bx+4)

8086 Flags

;moves 99 to save; changes ' Hello I to . Helpo I;sets bx to 4; changes ' Helpo I to I Help! .;moves offset of again to ax;moves ax to save; sets ax to zero; sets es to ax which is zero;moves word at 0: 8 to ax.offset of NMI interrupt.

The flags are set 1) directly, 2) as side effects of arthetic intrctions, and 3) byPOPF (pop flags) and IRET (interrpt return). If you do a PUSHF (push flags)followed by a POP, they wil appear as a word with the following format:

--------------------------------------------------------------

I X I X I X I X I OFI DFI IF TF SFI ZF X I AFI X I PFI X I CFI

----------------------------------------------------------------

car flag. Set by arthetic instrctions to indicate unsigned overfow.The car flag is not set by INC and DEC. Can be set with STC and turnedoff with CLC.party flag. Set by arthetic instrctions to indicate party. On for zeroparty which means an even number of bits are on in the result.auxilar car flag. Used in BCD arthetic.zero flag. Set to 1 or tre if the result of arthetic instrction is zero.- sign flag. Set by arthetic instrctions if the sign (highest) bit is on.trp flag. Set by debuggers to cause single stepping. Can only be set byIRT.

Page B.4

Page 383: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

interrpt enable flag. Set by STI, turned off by CLI ard interrpt.direction flag. Determines direction of strng instrctions. Set off, whichmean increasing SI and DI, by CLD. Set on by STD.overfow flag. Indicates signed overfow. True if the high order (sign) bitwas changed by overfow.

Address Expressions

Address expressions follow normal 8086/88 rules. For example:

(234)DS: (0)(BP+98)variablevariable+22variable (22)variable (BP+22)ES :variable (BP) +22

Address Typing

If an instruction includes a register, the tye of the register determines the type ofthe operation. If no register is present, the type of a varable is used. If neither ispresent or the tye of the varable is incorrect, the key-words BYTE, WORDDWORD, QWORD or TBYT must be used. BYT means the operad has alength of one byte, WORD mean two bytes, DWORD mean four bytes, QWORDmeans eight bytes and TBYT mean ten bytes.

Examples:

MOV

MOV

INCFMUL

(44) ,FOO, 1WORD ES: (BXJQWORD (BP+22)

Comments

A non-quoted semi-colon causes the rest of a line to be ignored.

Page B.5

Page 384: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

Assembler Directives

Directives may be in either upper or lower case.

Cseg:Dseg:Eseg:

End:

Equate:

Even:

CSEGDSEGESEG

, The DSEG directive indicates that Small Case data or Large Case staticdata follows, the CSEG. directive indicates that code follows, and theESEG directive indicates that Large Case ary or strcture datafollow. The default is DSEG. DSEG and CSEG directives may be placedanywhere but all code must follow a CSEG and al data must follow aDSEG or an ESEG.

END

The END statement is optional and does nothg.

,.-

identifier EQU expression

Equates are not evaluated until used so they may contain any sort ofexpression or mnemonic.

LF equ OaHPORT equ 201H

EVEN

Even forces even alignment by insertg a zero byte if required.Words should be on even boundares on the 8086 for improvedperfon,ance. On the 8088 it does not make any difference.

Page B.6

Page 385: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

IT:Else:Endlf:

Include:

Offset:

Public:

Seg:

Appendix B: The ASM88 Assembly Language

IF expressionELSEEND IF

The control directives IF , ELSE, and ENDIF have been added tosupport conditional assembly. Any symbolic name set by an EQUdirective - can be used. For example:

IF LARGE CASEmov ax, (bp+6)

ELSEmov ax, (bp+4)

ENDIF

INCLUDE " filename

The indicated fie is included in the source.

OFFSET identifier

OFFSET generates the offset of the varable.

PUBLIC identifier (:BYTE I WORD etc.

) (,...

Public declares that the listed varables are public. If an identifer is notdermed in the fie, it is assued to be external. Ths allows the samefie contag PUBLIC declartions to be included in all of the modulesof a system.

An identifier may be followed by a colon and the keyword BYTEWORD, DWORD, QWORD, or TBYTE. Ths allows a type to be associatedwith an external varable. The placement of PUBLIC statements isimportt They must be in the same segment (DSEG or CSEG) as thesymbbls they name. In addition, the PUBLIC for a symbol must notfollow its definition.

SEG identifier

SEG is a Lage Case directive which is similar to OFFSET except that itgenerates the segment of the varable rather than the offset.

Page B.

Page 386: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

Reserving Storage

Bytes, words, double-words and quad-words are declared with the DB , DW, DDand DQ directives.

(label(:)J DB I DW I DD I DQ value (, value)...

Values are trcated to bytes within DB , words with DW and double-wordswithin DD. The exception is the form

DB ' string of any length' , 0

DD values may be binar (without a period or 'E' exponent), single precisionfloating point, or a Large Case pointer. DQ values are always floating point.

Storage can be reserved with RB and RW.

(label ( : J J RB or RW expression

Reserves the indicated number of bytes or words. They are initialized to zero at runtime. Caution: RB's and RW's ar moved to high memory so they wil not beadjacent to the DB's, DW's, DD' s, and DQ's they are declared next to.

The Large Case operator creates a long (4 byte) pointer in DSEG and returns itsoffset. is normally used with LES to load a long (4 byte) pointer to a varable.

Differences Between MASM86 and ASM88.

Code Macros, MPL, SEGMENT etc. are missing.The public label MAIN must be declared somewhere in a program. identifies the initial entr point.Jump optimization is performed. TIs means that the assembler assemblesJM as a two bytejump when possible and that jump relative to an addressover 128 bytes away is turned into a jump around a jump.For example, a JZ toa label more than 128 bytes away would become a JNZ around a JM.DQ' s values are always floating point.Eight byte binar is not supported. 'The word 'POINTR' (or 'PT' ) is not used. An anonymous varable isWORD (BX)' instead if 'WORD PT (BX)' . The mnemonics LCALL, LIMP

, and LRET are used for the long forms of CALL, IMP and RET.

Page B.

Page 387: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

8086 Instructions

Elements of Instrctions

The following is a description of the varous types of operads:

regbregwregsegreg

regrmconstatlabel

Instructions

AAM

AAS

ADC

Any genera or byte register can be used.Any byte register. Any genera register.Any segment register.A memory reference. ' Any genera register or memory reference.A constat expression.The label of a statement.

ASCII Adjust forAddition changes the contents of AL to validunpacked decimal number; the high-order nybble is zero. Updates AFand CF. OF, PF, SF, and ZF are undefined after execution.

ASCII Adjust for Division - AH is multiplied by 10 and added to AL.Updates PF, SF, and ZF. AF, CF, and OF are undefmed afterexecution.

ASCII Adjust for Multiply - AL is divided by 10. The result goes in AH and the remaider into AL. Updates PF, SF, and ZF. AF, CF, andOF are undefmed after execution.

ASCII Adjust for Subtrction. Repair AL when AL is the result ofASCII subtrction. Updates AF and CF. OF, PF, SF, and ZF areundefmed after execution.

Adds the right operad and the car bit to the left operand. Updates allthe flags.

ADC AX I AL,constatADC regrm reg I constatADC reg,regrm

Page B.

Page 388: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

ADD

CALL

CBW

CLC

CLD

Appendix B: The ASM88 Assembly Language

adcadcadcadc

ax, axaI, harry (bp+55 Jword (bp+5), 0ax, ax

Adds the right operand to the left operad. Updates AF, CF, OF, PFSF and ZF.

ADD AX I AL COJ;statADD regrm,reg I constantADD reg,regrm

add ' . ax, axadd aI, harry (bp+55)add word (bp+5 J ,

Logically "and"s the right operad to the left operad. Updates CF, PF, SF, and ZF. AF is undefined after execution.

AN AX I AL,constatAN regrm,reg I constantAND reg,regrm

andandand

ax, dxaI, harry (bp+55 Jword (bp+5 J , OFH

Pushes the address of. the next instrction and jmps to the indicatedaddress. Call's can be direct to a label or indirect though a wordregister or a word in memory. No ,flags are affected.

CALL label I regrm

call labacall bxcall word es: (bx)

sign extend AL into AX. No flags are affected.

clear car flag.

clear direction flag.

Page B.1O

Page 389: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

CLI

CMC

CMP

CMPSBCMPSW

CWD

DAA

DAS

DEC

DIV

Appendix B: The ASM88 Assembly Language

clear interrpt enable flag. Disables interrpts.

complement car flag.

Compares operands. All flags are affected.

CMP AX I AL,constatCMP reg,regrm

empempemp

ax, axaI, harry (bp+55)word (bp+5 J , a

compare byte at DS:SI TO ES:DI. Increment SI and DI.compare word at DS:SI to ES:DI. Add 2 to SI and DI.

If the direction flag is on, registers are decremented instead incremented. These intrctions are usually used with a REP, REPZ orREPNZ prefIx. All flags are afected.

sign extend AX into DX:AX. No flags are affected.

Decimal Adjust for Addition. , Adjusts AL after packed addition.Updates AF, CF, PF, SF, and ZF. OF is undefmed after execution.

Decimal Adjust for Subtrction. Adjusts AL after packed subtrction.Updates AF, CF, PF, SF, and ZF. OF is undefmed after execution.

Decrements the operand. Updates AF, OF, PF, SF, andZF.

DEC wreg I regrm

deedeedee ehr

Divide AX by byte operaCi with result in AL and remainder in AH ordivide DX:AX by word operad with result in AX and remainder inDX. AF, CF, OF, PF, SF, and ZF are undefIned after execution.

DIY regrm

div

Page B.11

Page 390: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Ese

HLT

IDIV

IMUL

INC

INT

Appendix B: The ASM88 Assembly Language

trgge the 8087. If there is no 8087, this instrction should not beused. The constat/8 is, added to the esc instrction. The constant mod 8is the middle 3 bits of the rim. No flags are affected.

ESC constant,

stops the processor. The processor stops until an external interrptoccurs. No flags are affected.

Integer divide AX by byte operad with result in AL and remainder inAH or integer divide DX:AX by word operad with result in AX andremaidedn DX. AF, CF OF, PF, SF, and ZF are undefined afterexecution.

IDlY regrm

Integer multiply AL by byte operad with result in AX or integermultiply AX by word operad with result in DX:AX. Updates CF andOF. AF, PF, SF, and ZF ar undefmed after execution.

IMUL regrm

input from a port into AL or AX. A constat port must be in the rageo to 255. The use of DX for port allows addressing all 65535 ports. Noflags are afected.

IN AL I AX constatIN AL I AX

al, 44

ax, dx

Increment the operad. Updates AF, OF, PF, SF, and ZF.

INC wreg I regrm

incinc chr

cause a software interrpt. The int instruction causes the execution ofthe associated interrpt routine. Interrpts are the usual way to call theoperating system from the assembler. An interrpt pushes the flagspushes es, pushes IP disables interrpts and UMP's to the address at0: interrpt number times 4. The constat must be in the rage 0 to 255.

Page B.12

Page 391: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

INTO

mET

JAiNBEJAE/NBJBINAEJBEINA

JCXZJE/ZJGINLEJGE/NLJLINGEJLE/NG

JNCJNEINZJNOJNSJN/PO

JPIPE

Appendix B: The ASM88 Assembly Language

Interrpt 3 generates a one byte instrction. Debuggers use interrpt 3for breakpoints. A progra run under DEBUG can use an ' int 3' tocall the debugger. Updates IF and TF.

!N constat

intint

OC1H

interrpt on overfow. Cause an interrpt 4 if the overfow bit is set.No flags are afected.

return from an interrpt. Flags are restored from stack.

jump on abovelnot below or equal.jump on above or equalnot below.jump on belowlnot above or equal.jump on below or equalnot above.

jump on car.jump if ex is not equal to zero.jump on equalzero.jump on grater/not less than or equal.jump on grater than or equalnot less.jump on less/not greater than or equal.jump on less or equal to/not greater.jump unconditionally.jump on not car.jump on not equalnot zerojump on not overfow.jump on not sign (positive).jump on not party/party odd.jump on overfow.jump on party/party equal.jump on sign (negative).

The words 'above' and 'below ' refer to unsigned comparisons. The words 'greaterand 'less' refer to signed comparsons.

ASM88 wil turn a jump relative into the five byte equivalent if the target is outofrage. No flags are afected.

Page B.l3

Page 392: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

App,endix B:The ASM88 Assembly Language

Jmp s to a label wil generate either the two or three byte formdepending upon the distace of the label. Jmp s can be direct to a labelor indirect though a word register or a word in memory.

JMP label I regrm

jmpjmpjmpjmp

laba

word es: (bx)laba (bx)

LAHF load AH from flags. No flags are afected. The format of AH is:

LCALL long call. LCALL pushes the CS, pushes the instrction pointer, anddoes a long jump indirect though memory. The memory mustconta two words: the new intrction pointer and the new CS.

flags ar afected.

LCAL

lcall laba (bx)

LDS loads a register (usualy' an index register - BX, SI or DI) and DS. It isused to form a long pointer so that data outside of DSEG and CSEGcan be addressed. No flags are affected.

LDS wreg,regrm

ids bx, vara

LEA loads the offset of the referenced memory location into a register. Noflags are affected. LEA wreg,

lealeamov

ax, (si+di+44)ax, varaax, offset vara : same effect as above

Page B.l4

Page 393: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

LES

LJMP

LOCK

LODSBLODSW

Appendix B: The ASM88 Assembly Language

loads a register (usually an index register - BX SI or DI) and ES. It isused to form a long pointer so that data outside of DSEG and CSEGcan be addressed. No flags are affected.

LES wreg,regrm

les di, vara

long jump. Ljmp s can only be indirect though memory. Thememory must conta two words: the new instruction pointer and thenew CS. No flags are afected.

UMP label

Lock the bus. LOCK demands a bus lock for the followinginstrction. Usually used with XCHG to implement semaphores. Noflags are affected.

LOCK instrction

mov al,lock xchg laba, al

load byte at DS:SI into AL. Increment SI.load word at DS:SI into AX. Add 2 to SI.

If the direction flag is on, registers are decremented instead ofincremented. These instrctions are usually used with a REP, REPZor REPNZ prefIx. No flags are afected.

lodsbrep lodsw

Page B.15

Page 394: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

LOOP decrement ex and jump if ex not equal to zero.LOOPE!ZZ decrement ex and jump if ex not zero and the zero flag is set.LOOPNE/Z decrement ex and jump if ex not zero and the zero flag is cleared.

LOOP, LOOPZ all decrement ex, check it for zero and if not zero,do the jump. LOOPZ and LOOPNZ also .check the zero flag. Noflags are affected.

LOOP labelLOOPE/Z labelLOOPNE/Z label

LRET , perform a long return. Assumes the procedure was .called with anLCALL. Both the intrction pointer and the new CS must be on the

. stack. The optional constat is added to SP after the return address isremoved. Languages other than C use ths to remove parametersfrom the stack. C has the caller remove pareters so that a varablenumber of pareters can be supported. No flags are affected. '

LRET I .constat

MOV The contents of the right operad are moved to the left operand. Noflags are affected.

MaV segreg,regrmMaV regrm,segreg I regMaV reg,constat I regrmMaV ml,constant

movmovmovmovmovmov

ax, bxex, dses, exvara, axsi, varabi, varb (si+di)

Page B.16

Page 395: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

MOVSBMOVSW

MUL

NEG

NOP

NOT

Appendix B: The ASM88 Assembly Language

move byte from DS:SI to ES:DI. Increment/decrement SI and DI.move word from DS:SI to ES:DI. Add/subtract 2 tolfrom SI and 01.

If the direction flag is on, registers are decremented instead ofincremented. These instrctions are usually used with a REP, REPZor REPNZ prefix. No flags are affected.

repmovsbmovsw

Multiply AL by byte operad with result in AX or multiply AX byword operad with result in DX:AX. Updates CF and OF. AF

, and ZF are undefmed after execution.

MUL regrm

mulmul vara

Negate the operad. Updates AF , OF, PF, SF, and ZF.

NEG regrm

neg neg vara

do nothg in tQee cycles. No flags ar affected.

Invert the bits of the operad. No flags are affected.

NOT regrm

not

logical or of the operads. Updates CF, OF, PF, SF, and ZF. AF isundefined after execution.

OR AX I AL,constat 'OR regrm,constat I regOR reg,regrm

ax, axaI, harry (bp+S5)

Page B.17

Page 396: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

OUT

POP

POPF

PUSH

PUSHF

RCL

RCR

Appendix B: The ASM88 Assembly Language

Output a byte or word to a port. A constant port must be in the rangeo to 255. The use of DX for port allows addressing all 65535 ports.No flags are affected.

OUT constat AL I AXOUT DX AL I AX

outout

dx, ax33, al

The word contents of SS:SP are moved to the operad and the stackpointer is incremented by 2. CS canot be popped as this would kilthe system. No flags are afected.

pop wreg I regrm I segreg

poppoppop

total word es: (bx)

The flags ar popped off of the stack.

Two is subtrcted from SP and the word operad is moved to SS:SP.No flags are afected.

PUSH wreg I regrm I segreg

push axpush total

The flags ar pushed onto the stack. No flags are afected.

rotate left through car. The car bit ends up as the new low bitand the high bit becomes the car bit. Updates CPand OF.

RCL regrm, 11 CL

rotate right through car. The car bit ends up as the new high bitand the low bit becomes the car bit. Updates CF and OF.

RCR regrm, 1 I CL

Page B.18

Page 397: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

REPREPZ

REPNZ

RET

ROL

ROR

SAHF

Appendix B: The ASM88 Assembly Language

decrement ex on each iteration and continue while not zero.decrement ex on each iteration and continue while CX is not zeroand the zero flag is on.decrement ex on each iteration and continue while CX is not zeroand the zero flag is off.

These prefIxes can only be used with the string instrctions; theycause the strng instrction to be repeated. No flags are affected.

REP instrctionREPZ instrctionREPNZ intrction

rep movsbrepz stosw

Retu from a call. Only the instrction pointer is on the stack. Theoptional constat is added to SP after the return address is removed.Languages other thanC use ths to remove parameters from the stack.C bas the caller remove pareters so that a varable number ofpareters can be supported. No flags ar affected.

RE I constat

retret

rotate left. The high bit ends up in car and as the new low bit.Updates CF and OF.

ROL regrm, 11 CL

rotate right. The low bit ends up in car and as the new high bit.Updates CF and OF.

ROR regrm, 11 CL

New flags ar loaded from AH. Updates AF, CF, PF, SF, and ZF.The format of AH is:

Page B.19

Page 398: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

SAL

SHL

SAR

SBB

SCASBSCASW

SHR

Appendix B: The ASM88 Assembly L guage

shift arthetic left. The high bit goes to car and the new low bitbecomes zero. shift left. The high bit goes to car and the new low bit becomes zero.

Updates CF, OF, PF, SF, and ZF. AF is undefmed after execution.

SAL regrm, 11 CLSHL regrm ll CL

shift arthetic right. The low bit becomes the car bit, the high bit isleft alone (Le. the sign remains the same). Updates CF, OF, PF, SF, andZF. AF is undefined after execution.

SAR regrm, 1 I CL

Subtract the right operand and the car bit from the left operand.Updates AF, CF, OF, PF, SF, and ZF.

SBB AX I AL,constatSBB regrm constat I regSBB reg,regrm:;::nl.

sbbsbbsbbsbb

ax, axal, harry (bp+55)word (bp+5), ax, ax

compare AL to byte at ES:DI. Increment DI.compar AX to word at ES:DI. Add, 2 to DI. .

If the direction flag is on, registers are decremented instead ofincremented. These instrctions are usually used with a REP, REPZ orREPNZ prefix. Updates AF, CF, OF, PF, SF, and ZF.

shift right. The low bit goes to car, the new high bit is zero. Updates, CF, OF, PF, SF, and ZF.

SHR regrm 11 CL

shrmovshr

al,el,vara, el

Page B 20

Page 399: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

STC

STD

STI

STOSBSTOSW

SUB

TEST

WAIT

Appendix B: The ASM88 Assembly Language

set the car flag.

set the direction flag.

set interrpts enabled.

store AL at ES:DI. Increment DI.store AX at ES:DI. Add 2 to DI.

If the direction flag is on, registers are decremented instead ofincremented. These instrctions are usually used with a REP, REPZ orREPNZ prefix. No flags are affected.

Subtracts the right operad from the left operad. Updates AF, CFOF, PF, SF and ZF.

SUB AX I AL,constatSUB regrm reg I constatSUB reg,regrm

subsubsub

ax, axaI, harry (bp+SS Jword (bp+S J ,

logicaly ands the operads. The operands are unchanged. Updates CF,OF, PF, SF, and ZF. AF is undefined after execution.

TEST reg,constat I regrmTEST ax,constatTEST regrm,constat I reg

test al,test ax, 80htest chr, 44htest ax, varatest vara,

halts the processor until the 8087 is ready for an instrction. No flagsare afected.

Page B21

Page 400: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

XCHG

Appendix B: The ASM88 Assembly Language

The contents of the two operads are exchanged. XCHG is often usedto implement semaphores. No flags are affected.

XCHG AX,regXCHG reg,regrmXCHG regnn reg

xchg ax, xchg al, ahxchg vara,

XLAT Move the contents of the byte at BX+AL into AL. No flags areaffected.

XLAT

XOR Logically "exclusive or s the right operad to the left operand.Updates CF, OF, PF, SF, XOR ZF. AF is u defined after execution.

XOR AX I AL constatXOR regnn reg I constatXOR reg,regrm

xorxorxor

ax, dxal, harry (bp+55)word (bp+5), OFH

Page B22

Page 401: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

8087

The 8087 is the numerics co-processor for the 8086 and 8088. . It extends the 8086 'architecture by adding instrctions for fast and accurate floating point operations.Adding an 8087 to an IBM PC or other 8088 or 8086 based computer that hasprovision for an 8087 is usually as simple as purchasing the chip and plugging it in.

The 8087 contains an eight element stack. The stack top is referred to as 'ST'.Other elements are referred to as 'ST(i)' where i is between 0 and 7 and is the indexof the element. ST(O) is the same as ST. The usual use of the floatig point stack to push two elements and then do a bin operation on them but there are severalvarations on instrction types. Each element of the stack is maintained as an 80 bitextended precision value. The extr precision minizes round off errors.

The 8087 context includes both the floatig point stack and thee status registers.The entir context, as saved by FSA VE and restored by FRSTOR is:

control wordstatus word

tag wordbits 0 to 15 of IP

IP 19-16 lolopcodebits 0 to 15 of

OP 19-16 I zeros

bits 0 to 15 of ST

bits 16 to 31 of ST

bits 32 to 47 of ST

bits 48 to 63 of ST

S I exponent of ST

ST( 1), same as ST

I ST(7), same as ST

Page B23

Page 402: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

IF stands for instruction pointer and is the 20 bit address of the last instrction. OPis the 20 bit address of the last operad referenced. S is the sign bit.

The portion of the state other than the eight stack elements, is called the environmentand can be loaded with FLDENV and stored with FSTENV.

Control Word

The control word can be loaded with FLDCW and stored with FSTCW and has thefollowing format:

reserved.

infinity control. 0 is projective which is default. 1 is affme.

rounding control. 0 is round to even (default). 1 is round down. 2 is roundup. 3 is trncate.

precision control. 0 is single precision, 1 is double precision and 2 is fullprecision which is default.

IEM intenupts enable mask. 0 means disabled which is default.

precision exception mask. All masks are default 1 which mean apply thechip default action. A zero mean the exception should trgger a, user writtenexception handler procedure.

underfow exception mask.

overfow exception mask.

zero exception mask.

denormalized exception mask.

invalid operation exception mask.

Page B24

Page 403: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

Status Word

The status word has the following format:

busy. One if 8087 is executing an instrction.

C3,C2,C1,CO are the completion codes. These are discussed below.

index of stack top element.

interrpt request. On if an 8087 interrpt is pending.

precision exception.

underfow exception.

overfow exception.

zero divide exception.

denormalized exception.

invalid operation exception.

Tag Word

The tag word has the following format:

Itag(7) Itag(6)ltag(S)ltag( 4 )ltag(3)ltag(2) Itag( l' l!tag(O)1

tag = 00 if valid01 if zero,10 if not a number, infmity or unnormal, or11 if empty.

Page B25

Page 404: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

Condition Codes

Following an FCOM (compare), the condition codes are:C3C2CO

ST :; source.ST .: source.ST == source.the relationship is unown.

The status word is arged so the following code sequence may be used.

FSTSW STATFWAITMOV

SAHFAH, BYTE STAT+l

; store the 8087 status word;wait for the store; load hi byte of status into AH.; load flags from AH.

The FX instrction shows if the stack top is aninmity or unnormal.C3 C2 Cl co

JB.. .JBE.. .JA.. .JAE.. .JE.. .JNE. . .

; jump; jump; jump; jump; jump; jump

if ST -( sourceif ST -(= sourceif ST :; sourceif ST :;= sourceif ST == sourceif ST

! =

source.

+ unnormal.

+ not a number.- unnormal.

- NAN.+ normal.

+ infmity.- normal.

infmity.+ zero.

empty.- zero.

empty.

+ '

denormalized.empty.

- denormalized.

empty.

'''

Page B26

Page 405: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

8087 Instructions

w stands for 16 bit word, d stands for 32 bit short, q stands for 64 bit quad word andi stands for an index in the rage of 0 to

F2XMl

FABS

FADO

FAODP

FBLO

FBSTP

FCHS

FCLEXFNCLEX

ST = 2**ST-

f2xml

ST = absolute value(ST)

fabs

add real.

faddfadd ST, ST(i)fadd ST (i), STfadd dfadd q

; ST (1) =ST (1) +ST. pop stack.

add real and pop the stack.

faddp,;S1;Ci) ' ST ,

push a BCD operad onto the stack.

fbld q

store and pop a BCD value.

fbstp q

change the sign of the stack top

fchs

clear 8087 exceptions. The 'N' form has no WAIT.

felexfnclex

Page B.

Page 406: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

Appendix B: The ASM88 Assembly Language

FCOM compare reals.

fcom ; compare ST to ST (1)fcom ST(i) ; compare ST to ST (i)

fcom d ; compare ST to floatfcom q ; compare ST to double

FCOMP compare real and pop stack.

fcomp ; compare ST to ST (1)fcomp ST (i) ; compare ST to ST (i)

fcomp ; compare ST to floatfcomp ; compare ST to double

FCOMPP compare real and pop stack twice.

fcompp ; compare ST : ST (1). pop both.

FDECSTP increment stack top pointer.

fdecstp

FDISIFNDISI

disable interrpts. The 'N' form does not WAIT

.;" , :

fdisifndisi

FDIV real divide.

fdivfdivfdivfdiv

, fdiv

; ST ( 1) =ST ( 1) / ST.ST, ST(i)ST ( i) , ST

pop stack.

FDIVP real divide and pop the stack.

. .

fdivp ST (i) ,

Page B.

Page 407: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

FDIVR

FDIVR

FENIFNNI

FFREE

FID

FICOM

FICOMP

FIIV

Appendix B: The ASM88 Assembly Language

real reverse divide.

fdi vrfdivrfdivrfdi vrfdivr q

ST, ST ( i)ST ( i) , ST

;ST(l)=ST/ST(l) .

real reverse divide and pop the stack.

fdivrp ST(i),

enable 8087 interrpts. The 'N' form does not WAIT.

fenifneni

free an 8087 stack element.

ffree ST (i)

add an integer to the top as stack

. ; add' an ffo 86fiadd wwordfiadd d ; add a long

compar integer to top of stack.

ficom wficom d

;compare to 8086 word; compare to a long

compar integer to top of stack and pop.

ficomp wficomp d

; compare to 8086 word; compare to a long

divide top of stack by integer..

fidiv wfidi v d

;divide by 8086 word; divide by a long

Page B.29

Page 408: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

FIDIVR

FILD

FIMUL

FICSTP

FITFNT

FIST

FISTP

FISUB

Appendix B: The ASM88 Assembly Language

ST = integer ST.

fidivr wfidivr d

;divide 8086 word by ST;divide a long by ST

push an integer.

fild wfild dfild q

; load an 8086 word; load a long; load an 8 byte integer

multiply ST by an integer.

fimul wfimul d

;multiply by an 8086 word.;multiply by a long

increment the stack pointer.

fincstp

intialize the 8087. TIs instrction should precede any other 8087intrction in a progra. The 'N' form does not WAIT.

fin it

fninit

. ' ). . , ! ,': , '. .

store an integer.. 1 ' .

' :''" ': ::,

fist wfist d

; store an 8086 word.; store a long

store an integer and pop the stack. ':: J

fistp wfistp d

; store an 8086 word.; store a long

. .

1 "

:. ; . ; , ~~~

subtrct an integer from top of stack.

fisub wfisub d

; subtract 8086 word; subtract ' long

\'

Page B.30

Page 409: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

FISUBR

FLD

FLDCW

FLDENV

FLDLG2

l' .

FLDLN2

FLDL2E

FLDL2T

FLDPI

FLDZ

Appendix B: The ASM88 Assembly Language

ST = integer - ST.

fisubr wfisubr d

;subtract ST from 8086 word; subtract ST from long

push a floating point value.

fld ST(i)fld dfld qfld tbyte tload processor control word

f Idcw

load 8087 environment from memory.

fldenv env

load log base 10 of 2.

fld;Lg2

load log base e of 2.

" ' . .

fldln2

load log base 2 of e.. i

Ud12e '

load log base 2 of 10.

fld12t,

load PI.:L i;:!. /..1.'

'" ,

fldpi

load zero.

fldz

Page B.31

:: .. ."... . :.

Page 410: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

FLDI

FMUL

FMULP

FNOP

FPATAN

FPREM

FPT AN

FRNDINT

FRSTOR '

Appendix B: The ASM88 Assembly Language

load one.

fldlreal multiply.

fmulfmul ST, ST (i)fmul ST(i),fmul dfmul q

iST(l)=ST(l)*ST. pop stack.

multiply real and pop the stack.

fmulp ST (i) ,

no operation. .

fnop

parial arctagent.

fpatan

ainder.

fprem

parial tagent

fptan

round to integer.

frndint

restore 8087 state

frstor state

. " ,-'

" :;.n:

: . :' :.:j) .",. " .

Page B.32

\;.

.' .. i"O:'j f. . I '

. . ;. .' )" .: ;;... ,.

,I .

;\ . . ..: . ' .

/,::ij

. /'' ,. + : . ., .

Page 411: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

FSA VEFNSA VE

FSCALE

FSQRT

FST

FSTCWFNSTCW

FSTENVFNSTENV

FSTP

Appendix B: The ASM88 Assembly Language

save entire 8087 state. The 'N' form does not WAIT.

fsave statefnsave state

binar scale ST by ST(1).

fscale

tae squar root of ST.

f s qrt

store real.

fstfstfst

ST ( i)

store control word. The 'N' form does not WAIT.

fstcw wfnstcw w

-,

i: j

, "

store the 8087 environment. The' N' form does not WAIT.; : 1

;. .

fstenv envfnstenv env

i. -. .

",;',.

store real and pop.. I

,;'

fstp ST (i)fstp dfstp qfstp tbyte t

'\ : , . ; . . "

:s

" r

" ,

Page B.33

;; . , ';' .

l '

.:

Page 412: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

FSTSWFNSTSW

FSUB

FSUBP

FSUBR '

FSUBRP

FIST

FW

FXAM

Appendix B: The ASM88 Assembly Language

store status word. The ' N' form does not WAIT.

fstsw wfnstsw w

subtract real.

fsubfsub ST, ST(i)fsub ST(i),fsub df s ub

;ST(l)=ST(l)-ST. pop stack.

real subtrct and pop the stack.

fsubp ST(i),

real reverse subtract.

fsubrfsubrfsubrfsubrfsubr

;ST(l)=ST-ST(1) .ST, ST(i)ST(i),

real reverse subtract and pop the stack.

fsubrp ST(i),

compar ST to zero.

ftstwait for 8087. Same as WAIT.

fwait

set condition codes from top of stack.

fxam

,; , Page B.34

Page 413: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The

FXCH

Appendix B: The ASM88 Assembly Language

exchange stack elements.

fxchfxch ST (i)

; exchange ST and ST (1)

FXTRACT decompose into exponent and significand.

FYL2X

FY2XPI

fxtract

ST(l) = ST(1) * log 2 ST.

fy12x

ST(l) = ST(1) * log (ST+l).

fy12xpl

; -:., . ,,, " '": -

. I ::

. \

r ,

; ,

. J t .

- .;:- " .: . - " :.

, r;. , 1

. ' :; ,

. t

: .,; r: f' ...

. , , ;

Jr:.

, , ,\ - ,

Page B.35

. . j. " .. :;,? . ;. .. '" "

'J,

1 '"

:.!; ,

Page 414: Published and Distributed by - DeSmet C · architecture and the instruction set of the 8086/8088 family of ... Static varables combined within a single data-segment to speed ... The