Advanced C 1992 Free ebook download
Advanced C
C C C C C C C C C C C C C C C C C C
C
Introduction
Advanced C
Peter D. Hipson A Division of Prentice Hall Computer Publishing 201 W. 103rd St., Indianapolis, Indiana 46290 USA
Advanced C
© 1992 by Sams Publishing
All rights reserved. Printed in the United States of America. No part of this book may be used or reproduced in any form or by any means, or stored in a database or retrieval system, without prior written permission of the publisher except in the case of brief quotations embodied in critical articles and reviews. Making copies of any part of this book for any purpose other than your own personal use is a violation of United States copyright laws. For information, address Sams Publishing, 201 W. 103rd St., Indianapolis, IN 46290 International Standard Book Number: 0-672-30168-7 Library of Congress Catalog Card Number: 92-061304 96 95 94 93 92 8 7 6 5 4 3 Interpretation of the printing code: the rightmost double-digit number is the year of the book’s printing; the rightmost single-digit number, the number of the book’s printing. For example, a printing code of 92-1 shows that the first printing of the book occurred in 1992.
Composed in AGaramond and MCPdigital by Prentice Hall Computer Publishing. Screen reproductions in this book were created by means of the program Collage Plus, from Inner Media, Inc., Hollis, NH.
Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.
C C
C
Introduction
C C C C C C C
Publisher Production Analyst
Richard K. Swadley Mary Beth Wakefield
Acquisitions Manager Book Design
Jordan Gold Michele Laseau
Managing Editor Cover Art
Neweleen A. Trebnik Tim Amrhein
Acquisitions Editor Graphic Images Specialist
Stacy Hiquet Dennis Sheehan
Production Editor Production
Mary Corder Katy Bodenmiller Christine Cook Technical Reviewer Lisa Daugherty
Denny Hager Timothy C. Moore Carla Hall-Batton John Kane
Editorial Assistants
Roger Morgan Rosemarie Graham Juli Pavey Lori Kelley
Angela Pozdol Linda Quigley
Formatter
Michele Self Pat Whitmer Susan Shepard Greg Simsic
Production Director
Alyssa Yesh Jeff Valler
Index Production Manager
Hilary Adams Corinne Walls
Imprint Manager
Matthew Morrill Proofreading/Indexing Coordinator
Joelynn Gifford
Advanced C
About the Author
and his wife live and work in New Hampshire. He has worked with
Peter Hipson
computers since 1972, in hardware design and software development. He has developed numerous software programs for both PCs and larger systems. He holds patents in the field of CPU design and has been involved with microcomputers since their inception. Peter is the developer of the Windows applications ST ARmanager and ST ARmanager A/E. You can contact Peter Hipson at P.O. Box 88, West Peterborough, NH, 03468. Enclosing an SASE greatly enhances the likelihood of a reply.
To Bianca, who has shown me what great fun it is having a granddaughter.
C C
C
Introduction
C C C C C C C
Overview
Advanced C
C C C C C C C C C
C
Introduction
Contents
A Brief History of C and the Standard ............................................ 3 A Programming Style .................................................................... 11 Memory Models............................................................................ 17 Summary....................................................................................... 18
Data T ypes.................................................................................... 19 Constants ...................................................................................... 25 Definitions versus Declarations ..................................................... 29 Declarations .............................................................................. 30
Definitions................................................................................ 33 Variables ....................................................................................... 35 Variable T ypes and Initializing Variables .................................. 35 Scope (Or I Can See You) ......................................................... 37 Life Span (Or How Long Is It Going T o Be Here?) .................. 39 T ype Casting ............................................................................ 41
Arrays............................................................................................ 46 Declaration of Arrays ................................................................ 46 Definition of an Array............................................................... 47 Array Indexing .......................................................................... 48 Using Array Names as Pointers ................................................. 55 Strings: Character Arrays........................................................... 56 Using Arrays of Pointers ........................................................... 58 Summary....................................................................................... 62
Advanced C
Pointers, Indirection, and Arrays ................................................... 65 Pointers ......................................................................................... 66 Indirection .................................................................................... 69 An Example of Pointers, Indirection, and Arrays ................................................................................... 69 Character Arrays and Strings ......................................................... 74
Indirection to Access Character Strings ......................................... 79 Protecting Strings in Memory ....................................................... 90 Ragged-Right String Arrays ........................................................... 92 Summary....................................................................................... 98
Command Line Arguments ........................................................... 99 Function Pointers........................................................................ 114 Menus and Pointers..................................................................... 120 State Machines ............................................................................ 135 Summary..................................................................................... 137
Decimal....................................................................................... 139 Binary ......................................................................................... 141 Hex ............................................................................................. 142 Octal ........................................................................................... 144 Looking at a File ......................................................................... 146 Bit Operators .............................................................................. 154 Bit Fields ..................................................................................... 155 Summary..................................................................................... 158
Compiling and Linking Multiple Source Files ............................. 162 Compiling Multifile Programs .................................................... 164 Linking Multifile Programs ......................................................... 164 Using #include ............................................................................ 166 External Variables........................................................................ 171 Using an Object Library Manager ............................................... 181 Using MAKE Files ...................................................................... 182 Summary..................................................................................... 186
C C
C
Table of Contents Introduction
C C C C C C C
Using the struct Keyword ............................................................ 191 Arrays of Structures ..................................................................... 195 Structures of Arrays ..................................................................... 200 Structures of Structures ............................................................... 203 Bit Fields in Structures ................................................................ 206 Using the typedef Keyword ......................................................... 208 Using the offsetof() Macro .......................................................... 213 Pointers to Structures .................................................................. 216 Understanding unions ................................................................. 219 Summary..................................................................................... 226
Using the malloc( ) Function....................................................... 228 Using the calloc( ) Function ........................................................ 232 Using the free( ) Function ........................................................... 235 Using the realloc( ) Function ....................................................... 237 Allocating Arrays ......................................................................... 244 Global Memory versus Local Memory......................................... 247 Summary..................................................................................... 248
File I/O Basics............................................................................. 250 T ext Files and Binary Files .......................................................... 251 Creating and Using T emporary Work Files ................................. 256 Stream Files and Default File Handles......................................... 268
T he stdin File.......................................................................... 271 T he stdout File ....................................................................... 272 T he stderr File ........................................................................ 272 T he stdaux File ....................................................................... 273 T he stdprn File ....................................................................... 274 Low-Level I/O and File Handles ................................................. 278
Standard Low-Level File Handles ................................................ 280 Console and Port I/O .................................................................. 280 Direct Port I/O ........................................................................... 288
Advanced C
T he PC Printer Ports................................................................... 289 T he PC Communications Ports .................................................. 296 Summary..................................................................................... 318
Sorting ........................................................................................ 322 Merging ...................................................................................... 329 Purging ....................................................................................... 336 Sorting, Merging, and Purging All in One................................... 343 Linked Lists................................................................................. 344 Using Dynamic Memory ........................................................ 345
Disk-Based Lists...................................................................... 346 Double Linked Lists................................................................ 346 Indexing ...................................................................................... 367 Fixed-field Disk Files................................................................... 392 B-trees ......................................................................................... 392 Summary..................................................................................... 430
Other Languages ......................................................................... 436 Assembly................................................................................. 438
FORT RAN ............................................................................. 441 Pascal ...................................................................................... 442 BASIC .................................................................................... 443 Calling Other Languages from C ................................................. 443 Calling Assembly from C ........................................................ 447 Calling FORT RAN and Pascal from C ................................... 449
Calling C Functions from Other Languages ................................ 450 Calling C from Assembly ........................................................ 451 Calling C from FORT RAN and Pascal ................................... 462 All the T hings that Can Go Wrong ............................................. 462 Looking at Data ...................................................................... 463 Names and Limits................................................................... 465
Summary..................................................................................... 465
C C
C
Table of Contents Introduction
C C C C C C C
Interfacing with dBASE-Compatible Programs ........................... 468 Using dBASE Files Directly......................................................... 468
Reading dBASE and dBASE-Compatible Files........................ 474
Creating dBASE and dBASE-Compatible Files ....................... 484
Updating dBASE and dBASE-Compatible Files...................... 494
Summary..................................................................................... 494Function Prototypes .................................................................... 497 T he ANSI C Header Files ........................................................... 500 T he assert.h File (ANSI) .............................................................. 501 T he ctype.h File (ANSI) .............................................................. 502 T he errno.h File (ANSI) .............................................................. 504 T he float.h File (ANSI) ............................................................... 506 T he io.h File................................................................................ 508 T he limits.h File (ANSI) ............................................................. 508 T he locale.h File (ANSI) ............................................................. 509 T he malloc.h File ........................................................................ 510 T he math.h File (ANSI) .............................................................. 510 T he memory.h File...................................................................... 511 T he search.h File ......................................................................... 511 T he setjmp.h File (ANSI) ............................................................ 512 T he signal.h File (ANSI) ............................................................. 512 T he stdarg.h File (ANSI) ............................................................. 513 T he stddef.h File (ANSI) ............................................................. 515 T he stdio.h File (ANSI) ............................................................... 515 T he stdlib.h File (ANSI) ............................................................. 516
String Conversion ................................................................... 516
Memory Allocation ................................................................. 516
Random Numbers .................................................................. 516
Communications with the Operating System.......................... 516
Search Functions..................................................................... 517
Integer Math ........................................................................... 517
Multibyte Characters .............................................................. 517
T he string.h File (ANSI) ............................................................. 517 T he time.h File (ANSI) ............................................................... 518 T he varargs.h File ........................................................................ 518 Summary..................................................................................... 518
Advanced C
Functions .................................................................................... 522 abort() ..................................................................................... 522 abs() ........................................................................................ 522 acos() ...................................................................................... 523 asctime() ................................................................................. 523 asin() ....................................................................................... 524 assert() .................................................................................... 524 atan() ...................................................................................... 524 atan2() .................................................................................... 525 atexit() .................................................................................... 525 atof() ....................................................................................... 526 atoi() ....................................................................................... 526 atol() ....................................................................................... 526 bsearch() ................................................................................. 527 calloc() .................................................................................... 528 ceil() ........................................................................................ 528 clearerr() ................................................................................. 528 clock() ..................................................................................... 529 cos() ........................................................................................ 529 cosh() ...................................................................................... 530 ctime() .................................................................................... 530 difftime() ................................................................................ 531 div() ........................................................................................ 531 exit() ....................................................................................... 532 exp() ....................................................................................... 532 fabs() ....................................................................................... 533 fclose() .................................................................................... 533 feof() ....................................................................................... 533 ferror() .................................................................................... 534 fflush() .................................................................................... 534 fgetc() ..................................................................................... 535 fgetpos() .................................................................................. 535 fgets() ...................................................................................... 536 floor() ..................................................................................... 536
C C
C
Table of Contents Introduction
C C C C C C C
fmod() .................................................................................... 537 fopen() .................................................................................... 537 fprintf() ................................................................................... 538 fputc() ..................................................................................... 538 fputs() ..................................................................................... 539 fread() ..................................................................................... 539 free() ....................................................................................... 540 freopen() ................................................................................. 540 frexp() ..................................................................................... 541 fscanf() .................................................................................... 542 fseek() ..................................................................................... 542 fsetpos() .................................................................................. 543 ftell() ....................................................................................... 544 fwrite() .................................................................................... 544 getc() ....................................................................................... 545 getchar().................................................................................. 545 gets() ....................................................................................... 546 gmtime() ................................................................................. 546 isalnum() ................................................................................ 547 isalpha() .................................................................................. 547 iscntrl() ................................................................................... 547 isdigit() ................................................................................... 548 isgraph() .................................................................................. 548 islower() .................................................................................. 549 isprint() ................................................................................... 549 ispunct() ................................................................................. 549 isspace() .................................................................................. 550 isupper() ................................................................................. 551 isxdigit() .................................................................................. 551 labs() ....................................................................................... 551 ldexp() .................................................................................... 552 ldiv() ....................................................................................... 552 localeconv() ............................................................................. 553 localtime() ............................................................................... 553 log() ........................................................................................ 554 log10() .................................................................................... 554 longjmp() ................................................................................ 554 malloc() .................................................................................. 556
Advanced C
mblen() ................................................................................... 556 mbstowcs() .............................................................................. 557 mbtowc() ................................................................................ 557 memchr() ................................................................................ 558 memcmp() .............................................................................. 558 memcpy() ............................................................................... 559 memmove() ............................................................................ 560 memset() ................................................................................. 561 mktime() ................................................................................. 561 modf() .................................................................................... 562 offsetof() ................................................................................. 562 perror() ................................................................................... 563 pow() ...................................................................................... 564 printf() .................................................................................... 564 putc() ...................................................................................... 564 putchar() ................................................................................. 565 puts() ...................................................................................... 565 qsort() ..................................................................................... 566 raise() ...................................................................................... 566 rand() ...................................................................................... 567 realloc() ................................................................................... 567 remove() ................................................................................. 568 rename() ................................................................................. 568 rewind() .................................................................................. 568 scanf() ..................................................................................... 569 setbuf() ................................................................................... 569 setjmp() .................................................................................. 570 setlocale() ................................................................................ 571 setvbuf() .................................................................................. 572 signal() .................................................................................... 573 sin() ........................................................................................ 574 sinh() ...................................................................................... 575 sprintf() ................................................................................... 575 sqrt() ....................................................................................... 576 srand() .................................................................................... 576 sscanf() .................................................................................... 576 strcat() .................................................................................... 577 strchr() .................................................................................... 577
C C
C
Table of Contents Introduction
C C C C C C C
strcmp() .................................................................................. 578 strcoll( ) .................................................................................. 579 strcpy( ) .................................................................................. 580 strcspn( ) ................................................................................. 580 strerror( ) ................................................................................ 581 strftime( ) ................................................................................ 581 strlen() .................................................................................... 583 strncat() .................................................................................. 584 strncmp() ................................................................................ 584 strncpy() ................................................................................. 585 strpbrk() .................................................................................. 586 strrchr() ................................................................................... 586 strspn() ................................................................................... 587 strstr() ..................................................................................... 588 strtod() .................................................................................... 588 strtok() .................................................................................... 589 strtol() ..................................................................................... 590 strtoul() ................................................................................... 591 strxfrm().................................................................................. 592 system() .................................................................................. 593 tan() ........................................................................................ 594 tanh() ...................................................................................... 594 time() ...................................................................................... 595 tmpfile() .................................................................................. 596 tmpnam() ............................................................................... 596 tolower() ................................................................................. 597 toupper() ................................................................................. 597 ungetc() .................................................................................. 597 va_arg() ................................................................................... 598 va_end() .................................................................................. 600 va_start() ................................................................................. 601 vfprintf() ................................................................................. 601 vprintf() .................................................................................. 602 vsprintf() ................................................................................. 604 wcstombs() .............................................................................. 605 wctomb() ................................................................................ 606 printf() Format Codes ................................................................. 606 c .............................................................................................. 607
Advanced C
e and E .................................................................................... 608 f .............................................................................................. 609 g and G ................................................................................... 610 n ............................................................................................. 610 o ............................................................................................. 610 p and P ................................................................................... 611 s .............................................................................................. 612 u ............................................................................................. 612 x and X ................................................................................... 613 scanf() format codes .................................................................... 614 c .............................................................................................. 615 d ............................................................................................. 615 o ............................................................................................. 615 x.............................................................................................. 616 i .............................................................................................. 616 u ............................................................................................. 617 e, f, and g ................................................................................ 617 n ............................................................................................. 618 p ............................................................................................. 618 s .............................................................................................. 618 [...] .......................................................................................... 619 Summary..................................................................................... 619
T he Macro Continuation Operator (\) ........................................ 622 T he Stringize Operator (#) .......................................................... 622 T he Characterize Operator (#@) ................................................. 623 T he T oken Paste Operator (##) .................................................. 624 T he Defined Identifier Operator (defined()) ............................... 624 T he #define Directive.................................................................. 625 T he #error Directive.................................................................... 628 T he #include Directive ................................................................ 629 T he #if Directive ......................................................................... 629 T he #ifdef Directive .................................................................... 630 T he #ifndef Directive .................................................................. 631 T he #else Directive...................................................................... 632 T he #elif Directive ...................................................................... 633 T he #endif Directive ................................................................... 633
C C
C
Table of Contents Introduction
C C C C C C C
T he #line Directive ..................................................................... 634
T he #pragma Directive................................................................ 635
T he message Pragma ............................................................... 635
T he pack Pragma .................................................................... 636
T he #undef Directive .................................................................. 637
Predefined Macros....................................................................... 637
T he _ _DAT E_ _Macro ......................................................... 637
T he _ _T IME_ _Macro .......................................................... 637
T he_ _FILE_ _Macro ............................................................. 638
T he_ _LINE_ _Macro ............................................................ 638
T he_ _ST DC_ _Macro .......................................................... 638
NULL ..................................................................................... 638
T he offsetof() Macro ............................................................... 638
Summary..................................................................................... 639
Debugging .................................................................................. 641
Common Bugs........................................................................ 642
Rules for Debugging ............................................................... 649
Using the assert() Macro ......................................................... 650
Debug Strings and Messages ................................................... 652
Debuggers............................................................................... 655
Efficiency .................................................................................... 657
32-Bit Programs...................................................................... 658
Compiler Optimization .......................................................... 660
Direct Video I/O .................................................................... 667
Floating-Point Optimization ................................................... 667
Inline Assembly....................................................................... 669
Linking for Performance ......................................................... 670
Pascal and cdecl Calling Conventions ..................................... 671
Precompiled Headers .............................................................. 671
Using 80286/80386/80486 Instruction Sets ........................... 671
Using a Source Profiler ........................................................... 672
Using Intrinsic Functions........................................................ 672
Using Memory Models ........................................................... 673
Summary..................................................................................... 675
Advanced C
Borland’s C++ 3.1 ....................................................................... 682 Microsoft .................................................................................... 686 C/C++ 7.0 .............................................................................. 686 QuickC for Windows 1.0 ....................................................... 690
Watcom C/386 9.01 ................................................................... 692
Object-Oriented Programming (OOP) ....................................... 696 Abstraction ............................................................................. 696 Encapsulation ......................................................................... 696 Hierarchies.............................................................................. 697
Learning C++ .............................................................................. 697 Overloading Functions ................................................................ 701 Declaring Variables When Needed .............................................. 704 Default Function Argument Values............................................. 706 References ................................................................................... 710 References as Return Values ........................................................ 711 Classes......................................................................................... 714
C C
C
Introduction
C C C C C C C
Acknowledgments
I would like to offer my thanks to the following organizations and people for their
support, help, guidance, and enthusiasm.T he Sams editorial and production staff, especially Gregory Croy, Stacy Hiquet, Susan
Pink, Mary Corder, and Rebecca Whitney, all who put enormous effort into making
this a good book. I would also like to thank T imothy C. Moore, who did the technical
editing.Borland International Inc., Microsoft Corporation, and Watcom Products, Inc., have
provided valuable support and assistance.T hanks to William Colley, III, and the C User’s Group, for the Highly Portable
Utilities (CUG-236) files that are included on the sample source diskette.Eric Jackson (“Eric in the Evening”) and public radio station WGBH for providing all
the jazz. T hank you all.Advanced C
C C
C
Introduction
C C C C C C C
Introduction
C has become one of the most frequently used computer languages. T he first C
language was developed by Dennis Ritchie at Bell Laboratories in 1972 and ran on a
DEC PDP-11. T he ANSI standard for C, which replaced the standard written by
Kernighan and Ritchie in 1978, is only a few years old.C’s structure is similar to PL/I (a popular language used on IBM’s mainframe
computers), FORT RAN, Pascal, and BASIC. C is a simple language. It has only a
small group of keywords and no support for I/O or advanced math. T he power
of C comes from its simplicity and its use of a standard library of functions.Who Should Read This Book?
Advanced C is for the programmer who has some experience writing applications in C
or a similar language, such as PL/I or Pascal. Regardless of whether you are an
intermediate or experienced programmer, this book is intended to improve your skills
as easily as possible.What Is in This Book?
T his book has several purposes. First, it introduces advanced parts of the C language.
It also describes changes in the ANSI standard, which is the only true definition of the
C language. In addition, the book contains much of what I have learned (often the
hard way) about C programming.Advanced C is divided into five parts, and each part can be used by itself. Part I
gets you started and lays the groundwork for the rest of the book. In Part II, you learn
how to manage data and files when programming in C. Part III introduces integrating
C with other languages and interfacing with other environments such as database
programs. Part IV is a reference section that covers the header files, the intrinsic
functions, the preprocessor, and some performance and debugging techniques. Part V
Advanced C
Introduction
(the appendixes) contains an ASCII table, information about different compilers, an introduction to C++, and a cross-reference of functions and their header files.
Many chapters contain example programs. In some chapters, a single example program is used to demonstrate several topics in the chapter. For a platform to develop C software, I recommend at least a 386/25, and preferably a 386/33 or 486. A 286 will do, but most linkers and some compilers are noticeably slower when you do not have a fast CPU. I suggest that you have at least a 100M hard disk. T he compiler I use most frequently is QuickC for Windows. It is powerful and easy to use (because it has an integrated debugging environment), and supports both ANSI C and Microsoft’s extensions.
Conventions Used in This Book
I used the following conventions in the book:
monospac e • All program listings and code fragments are in . monospac e • All function names are in . monospac e • ANSI C keywords are in .
- All function names appearing in text (not in the code) are followed by an
 
spr i nt f ( ) empty set of parentheses, for example, .
- Something that must be substituted (such as a filename or a value) is in
 
monospac e i t al i c .
- When a listing title shows a filename in uppercase, that file is usually found on the sample diskette. If a filename is not given or it is in lowercase, then it is not a separate source file on the diskette, but probably part of another file on the sample diskette. T he text usually indicates which file the code fragment is from.
 
A Note on Practicing C You can read, attend lectures, or discuss a subject, but as the saying goes, “practice makes perfect.”
C C
C
Introduction
C C C C C C C
Do not be afraid to practice with the programs in this book. But practice does