C All-in-One Desk Reference For Dummies®
Published by
Wiley Publishing, Inc.
111 River St.
Hoboken, NJ 07030-5774
www.wiley.com
Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, 201-748-6011, fax 201-748-6008, or online at http://www.wiley.com/go/permissions.
Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Website is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Website may provide or recommendations it may make. Further, readers should be aware that Internet Websites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
Library of Congress Control Number: 2004102339
ISBN: 978-0-7645-7069-8
Manufactured in the United States of America
10 9 8 7 6 5 4
1O/RX/QY/QU/IN
Dan Gookin has been writing about technology for 20 years. He has contributed articles to numerous high-tech magazines and written more than 90 books about personal computing technology, many of them accurate.
He combines his love of writing with his interest in technology to create books that are informative and entertaining, but not boring. Having sold more than 14 million titles translated into more than 30 languages, Dan can attest that his method of crafting computer tomes does seem to work.
Perhaps Dan’s most famous title is the original DOS For Dummies, published in 1991. It became the world’s fastest-selling computer book, at one time moving more copies per week than the New York Times number-one best seller (although, because it’s a reference book, it could not be listed on the NYT best seller list). That book spawned the entire line of For Dummies books, which remains a publishing phenomenon to this day.
Dan’s most recent titles include PCs For Dummies, 9th Edition; Buying a Computer For Dummies, 2005 Edition; Troubleshooting Your PC For Dummies; Dan Gookin’s Naked Windows XP; and Dan Gookin’s Naked Office. He publishes a free weekly computer newsletter, “Weekly Wambooli Salad,” and also maintains the vast and helpful Web site www.wambooli.com.
Dan holds a degree in communications and visual arts from the University of California, San Diego. He lives in the Pacific Northwest, where he enjoys spending time with his four boys in the gentle woods of Idaho.
We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/.
Some of the people who helped bring this book to market include the following:
Acquisitions, Editorial, and Media Development
Project Editor: Rebecca Whitney
Acquisitions Editor: Greg Croy
Technical Editor: Greg Guntle
Editorial Manager: Carol Sheehan
Editorial Assistant: Amanda M. Foxworth
Cartoons: Rich Tennant, www.the5thwave.com
Composition
Project Coordinator: Maridee Ennis
Layout and Graphics: Karl Brandt, Denny Hager, Joyce Haughey, Stephanie D. Jumper, Michael Kruzil, Melanee Prendergast, Jacque Roth, Julie Trippetti, Mary Gillot Virgin
Proofreaders: Arielle Carole Mennelle, Dwight Ramsey, Brian H. Walls
Indexer: Infodex Indexing Services Inc.
Publishing and Editorial for Technology Dummies
Richard Swadley, Vice President and Executive Group Publisher
Andy Cummings, Vice President and Publisher
Mary Bednarek, Executive Editorial Director
Mary C. Corder, Editorial Director
Publishing for Consumer Dummies
Diane Graves Steele, Vice President and Publisher
Joyce Pepple, Acquisitions Director
Composition Services
Gerry Fahey, Vice President of Production Services
Debbie Stailey, Director of Composition Services
Title
Introduction
Why Bother with C When C++ Is Obviously Blah-Blah-Blah?
About This Here Dummies Approach
How This Book Works
Icons Used in This Book
Final Thots
Book I : Hello, C
Chapter 1: Your Basic C Program
The Section Where the Author Cannot Resist Describing the History of C
Time to Program!
The C Skeleton
Chapter 2: How It All Works
Your Computer Programming Bag of Tools
The C Programming Language
Putting It Together in the Editor
Making a Program
Chapter 3: More Basics, Comments, and Errors
Simple “Hello” Programs
Adding Comments, Remarks, and Suggestions
Debugging
Chapter 4: Introducing Numbers and Variables
Going Numb with Numbers
Introduction to Variables
The Official Introduction to Basic Math Operators
Chapter 5: More Variables and Basic I/O
The Good Ol’ char Variable
Getting Input from the Keyboard
Summary of Basic Text I/O Functions
Chapter 6: Decision Time
Making Decisions with if
else , the Anti- if Statement
Or Else!
Making Multiple Decisions
Chapter 7: Looping
Presenting the for Loop
Endless Loops
Nesting Loops
The 17,576 Names of God
Multiple for Conditions
Chapter 8: Using Constants
Are Constants Necessary?
Constants: The Anti-Variable!
Other Things You Can #define
Chapter 9: Mysterious Math
Math Review
The Sacred Order of Precedence
Say It Out Loud: Unary Operators!
Incrementing and Decrementing and Loving It
Other Cryptic Math Shortcuts
Chapter 10: It’s Only Logical
Comparisons from Hell
Here Are Your Logical Operators, Mr. Spock!
Multiple Madness with Logical Operators
Book II : Middle C
Chapter 1: Variables from Beyond Infinity
Review of C Language Variable Types
Signed, Unsigned, Soap, No Soap, Radio
Fair and Unfair Variables
Typecasting and Other Acting Problems
C Language Variable Reference
Chapter 2: The Madness of Printf()
Going Numb with Numbering Systems
Putting Printf() to the Test
Chapter 3: Maniacal Math Functions
The Symbols That C Forgot
Trigonometric Functions
Other Handy Math Functions
Chapter 4: Not Truly Random
Introducing the random() Function
The Diabolical Dr. Modulus
Chapter 5: While Going Loopy
The while Loop
The do-while Loop
Messing with Loops
Chapter 6: More Decision Making
The Old Switch Case Trick
The Weird and Creepy ?: Construct
Bonus Program!
Chapter 7: The Goto Chapter
What Now? Go To!
The Basic goto Thing
Where goto Is Perhaps Needed
Book III : Above C Level
Chapter 1: Asking for Arrays
Beyond Normal Variables
Sorting an Array
Arrays from Beyond the First Dimension!
Bonus Program!
Chapter 2: I Sing of Strings
The Strings Review
The Truth about Strings
Lovely and Handy String Functions
The Boggling Concept of Arrays of Strings
Chapter 3: Messing with Characters
Introducing the CTYPE Functions
Characters That Tell the Truth
Just a Trivial Program Example
Altering Text
Chapter 4: Stinkin’ Structures
Life without Structures
Multivariables!
Arrays of Structures
Structures for the Birds (Nested Structures)
Chapter 5: Creating Your Own Functions
Your Typical Function
Functions That Don’t Func
Using Variables in Functions
Functions That Eat Values
Functions That Return a Value
Functions That Do Both
The Land of No Prototyping
Chapter 6: Quitting Before You’re Done
Abruptly Leaving the main() Function
A Most Graceful Exit
Chapter 7: More Variable Nonsense
The Joys of Hungarian Notation
Beware the typedef Statement!
Other Funky Variable Things
The State of the union
Book IV : Advanced C
Chapter 1: Introduction to Evil Pointers
Basic Boring Computer Memory Stuff
Some Pointers
The Insanity of Pointer Arithmetic
Chapter 2: Getting to the *Point
Pointer Review
And Now, the Asterisk, Please
Using * pointers to Modify Variables
Chapter 3: Binary Bits
Say Hello to Mr. Bit
Basic Bit Twiddling
The Utter Inanity of Binary Logic
Displaying Binary Values
Two Stragglers: ^ and ~
Chapter 4: The Myth of the Array
Pointers and Arrays
Death to the Array!
The Weird Relationship between Pointers and Array Brackets
Arrays and Pointers Summary
Chapter 5: Pointers and Strings
Using Pointers to Display Strings
Distinguishing Strings from Chars
Declaring a String by Using a Char Pointer
Chapter 6: Crazy Arrays of Pointers
Introducing the Pointer Array
Saving Some Space with String Pointer Arrays
Finding Characters in a Pointer String Array
Sorting Strings with Pointers
Chapter 7: Functions and Pointers
Passing a Pointer to a Function
Arrays to and from Functions
Strings, Functions, and Pointers
Chapter 8: Structures, Pointers, and the Malloc Deity
Making Sacrifices to Malloc
Malloc’s More Useful Relatives
Using Pointers and Malloc to Make New Structures
Chapter 9: Does Anyone Have the Time?
No, Seriously: What Time Is It, Really?
Getting the Time
Getting at the Individual Time-and-Date Pieces’ Parts
Just a Sec!
Chapter 10: Building Big Programs
Making Programs with Multiple Modules
The Tiny, Silly Examples
The Big Lotto Program
Chapter 11: Help!
Debugging
Helpful Utilities
Book V : Disk Drive C
Chapter 1: Just Your Standard I/O
Programming without Any I/O
But, What Is Standard I/O?
A Demonstration of Standard I/O
Writing Filters
Chapter 2: Interacting with the Command Line
Reading the Command Line
Running Another Program with system()
Dealing with the Exit Status
Chapter 3: Hello, Disk!
Fopen the Ffile, Fplease
Would You Like Binary or Text with That?
Chapter 4: More Formal File Writing and Reading
Formatted File Input and Output
Reading and Writing File Chunks
Chapter 5: Random Access Files
The Random Access Demonstration
Building a Disk-Based Database
Chapter 6: Folder Folderol
Who Knows What Lurks on Disk?
Grabbing Information about a File with stat()
Reading a Directory
Directories Hither, Thither, and Yon
The Art of Recursion
Chapter 7: Under New File Management
Renaming a File
Deleting a File
Copying or Duplicating a File
Moving a File (The Secret)
Book VI : The Joy of Linked Lists
Chapter 1: Why Linked Lists?
A Review of Database Programming in C
How Linked Lists Work
Chapter 2: Dawn of the Database
The Ubiquitous Bank Account Program
Removing Records from a Linked List
Chapter 3: Storing a Linked List on Disk
From Memory to Disk and Back Again
The Final Code Listing for BANK.C
Chapter 4: The Nightmare of the Double-Linked List
The Theory of the Double-Linked List
An Example of a Double-Linked List
Deleting an Item from a Double-Linked List
Book VII : Appendixes
Appendix A: The Stuff You Need to Know before Reading Everything Else in This Book
Setting Things Up
Making Programs
Appendix B: ASCII Table
Appendix C: Answers to Exercises
Book I: Hello, C
Book II: Middle C
Book III: Above C Level
Book IV: Advanced C
Book V: Disk Drive C
Book VI: The Joy of Linked Lists
Appendix D: C Language Keywords and Operators
Appendix E: C Language Variable Types
Appendix F: Escape Sequences
Appendix G: Conversion Characters
C ongratulations on your purchase of C All-in-One Desk Reference For Dummies — a tome that not only sits fat and looks impressive on your computer bookshelf, but also teaches you a heck of a lot about the C programming language.
Because few people read book introductions, I have decided to fill the following six pages with filthy limericks, most of which are patronizing to immigrants and women.
Seriously, now that I have your attention, I thought that I would ramble on briefly about this book and what you can expect from its contents.
This book provides a solid overview of the C programming language, from the basics on up through advanced concepts and topics that third-year university students would pay real money to have someone else suffer through.
Despite the For Dummies text on the cover, this book takes a swifter approach to learning the C language than my book C For Dummies, 2nd Edition. This massive work assumes, for example, that you may have a wee bit of programming experience or are just more eager to find out more about the C language or perhaps need that extra training in those advanced topics that are skimpily covered in other programming books. If that’s you, you have found your book! If that’s not you, you should still buy this book because three of my kids need braces badly.
Above all, the bottom line in this book is about having fun. I take things easy, introducing the C language one tidbit at a time. Rare is the long, involved program in this book. Short, punchy (and often silly) programs make finding out about C quick and easy. After all, you need only a few lines of text to see how a function or concept in C works. And, everything is peppered with a modicum of irreverence and a dash of humor. Or, could it be the other way around? Anyway, you get the idea.
The C programming language is like the Latin of the computer world. As with Latin, if you know C, learning other programming languages is a snap. Each of the following programming languages (and many more) has its base in C:
F C++
F Perl
F Java
F Python
When you know C, learning any of these languages is simple and painless.
Unlike Latin, however, the C language is far from dead. As one of the older computer languages, C has a rich history and a full library of routines, programs, documentation, help, and other whatnot — a rich treasure of resources for you to draw on. Rare is the program that cannot be written using simple C programming. From graphics to games and from networking to building new operating systems, you have no limitation on what you can do in C.
Most of my C language students use my books as a foundation for leaping into C++ programming — mostly because many C++ books lack the gentle hand-holding approach that my books have. In fact, if you read this book from cover to cover, I promise you that any C++ (or other programming language) book will be that much easier for you to grasp. It may not be written with my dynamic wit, but the concepts will be easier to understand.
The bottom line, of course, is programming. Becoming a programmer means that you have ultimate control over your computer. You are finally in charge, telling the dang thing exactly what to do with itself. And, like the fast idiot it is, the computer dutifully obeys your every whim.
Plus, programming gives you instant feedback. Some folks find that benefit so addicting that they end up growing beards; wearing sandals and Hawaiian shirts; consuming coffee, stale doughnuts and Doritos; and never leaving the confines of their house. And that’s just the women!
Don’t you hate buying a programming book and having to read through 50 pages of this and that, background information, trivia, why the author thinks he’s important, and all that other crap, only to discover that the first program in the book is five pages long and really (honestly) doesn’t teach you one single thing about programming?
Yeah! I hate that too!
You know what else I hate? Those burr stickers that get into your socks and you can’t pull them out because they poke into your fingertips. And, how about stockbrokers?
Unlike other programming books, this one starts out right away with something to do, something to type, something to learn. You want to get started right away. I can’t blame you. Right away, this book has you doing things — right there on Page 11, you’re typing something and finding out how to program.
Also unlike other books, this book keeps programs small and tidy. The best way to learn about something is one piece at a time. Baby steps! Therefore, you won’t find me cramming several topics into one program or putting things into the demo programs that I don’t discuss until “later.”
Small program. Easy to type. Quick feedback. Instant response. That’s the best way to figure out how to program. This book tells you how.
To keep you on your toes, I give you various exercises. Some chapters have many exercises, and some chapters have few or none. The idea is to see whether you can go off on your own and use your programming skills to solve a puzzle or come up with something new. Answers or suggested solutions are all offered in the back of this book — in Appendix C. I think.
This book covers the C programming language, which is an activity that is, for the most part, independent of your computer’s operating system. Therefore, this book covers both Windows and Unix computers.
Whether you have Linux (any flavor), FreeBSD (or any *BSD), Mac OS X, or any other flavor of Unix, I refer to it as Unix in this book.
Note that I do not cover Sun’s Solaris here. That’s because Sun has never sent me a free computer despite years of my never having asked for one.
The most important thing you need to do to work the examples in this book is read Appendix A. It covers the details on how you need to set up your computer for programming, selecting and using a text editor, and then fixing up the compiler.
Note that information on choosing a compiler is available on this book’s companion Web page: www.c-for-dummies.com.
Generally speaking, stuff in this book that appears on the screen looks like this :
I am text on the screen. La-di-da.
This is how text appears in a program listing:
Remove soiled diaper.
Clean baby.
Apply clean diaper.
Line numbers aren’t specified or used in C. Your editor should have a line number command or let you jump to line numbers, however. (It depends on the editor.) That way, when I refer to line 36 in the text, for example, you can use your editor to find and view that specific line.
Because this book is only so wide, some lines in a program may wrap. They look like this:
This is an example of a very long line that was painfully split in two by this book’s cruel typesetters.
When you see that, don’t type two lines. Just keep typing, and everything will fit on one line in your editor.
Elements of a program or source code may appear in a special monospaced font. I use it so that you understand that a, for example, is a part of the program and not a rogue article my editor ignored after imbibing too much wine.
If you need to press a certain key combination on your keyboard, it’s listed like this: Press Ctrl+C. Ctrl is the name of the control key on your keyboard. C is the C key. A + (plus sign) means to press both keys together. Note that Ctrl+C and Ctrl+Shift+C are two different key combinations.
Source code files are available from this book’s companion Web site, www.c-for-dummies.com. Go there to download all the source code files at one time or individually. The files are organized by “books,” just as this entire volume is organized into books.
Note that many programs are updated throughout this book. Although you will update the same source code, I keep each source code file separate. For example, the OZ.C series of source files starts with OZ.C in this book. But, in the source code file reference on the Web, you find OZ1.C for the first update, OZ2.C for the second, OZ3.C for the third, and so on. This file-naming scheme is used in Appendix C too.
Noli nothis permittere te terere.
Learning C is a journey. Enjoy it! Discover new things. Try new ways of doing things. Give yourself a challenge. Remember: If you can imagine it happening on your computer screen, you can program it. It may not run as fast as you imagine, but it will work!
Above all, keep on trying! You can explore so many different pockets of programming, from graphics to operating systems to networking to games — the variety is endless.
Occasionally, in your quest for knowledge, you may meet some arrogant member of what I call the Programmer Priesthood. Its members are people who are knowledgeable, but unwilling to help — almost to the point of cruelty. If you find people like that, in real life or on the Internet, quickly pass them by and seek out someone else for help. Not everyone who holds the keys is a jerk.
For myself, I can offer you this book’s companion Web page:
www.c-for-dummies.com
This Web page has more information about programming, some excellent books I recommend, plus bonus programs and materials from myself as well as feedback from other readers. Check it out when you have time.
I make myself available to answer questions via e-mail. I view this as part of my duty to you as a reader of my books. My e-mail address is
dan@c-for-dummies.com
I’m willing to help with some programming stuff, but I won’t write your programs for you, and I cannot help you with university assignments (especially stacks or binary trees) or C++ programming. But I am willing to return your message and say “Hello!”
Good luck with your C programming!