The C Library 
The C Library

Next:  Introduction 




Main Menu

This help file is based on Edition 0.10, last updated 2001-07-06, of The GNU C Library Reference Manual, for Version 2.2.x of the GNU C Library.

·  Introduction : Purpose of the C Library.
·  Error Reporting : How library functions report errors.
·  Memory : Allocating virtual memory and controlling paging.
·  Character Handling : Character testing and conversion functions.
·  String and Array Utilities : Utilities for copying and comparing strings and arrays.
·  Character Set Handling : Support for extended character sets.
·  Locales : The country and language can affect the behavior of library functions.
·  Searching and Sorting : General searching and sorting functions.
·  I/O Overview : Introduction to the I/O facilities.
·  I/O on Streams : High-level, portable I/O facilities.
·  Low-Level I/O : Low-level, less portable I/O.
·  File System Interface : Functions for manipulating files.
·  Mathematics : Math functions, useful constants, random numbers.
·  Arithmetic : Low level arithmetic functions.
·  Date and Time : Functions for getting the date and time and formatting them nicely.
·  Non-Local Exits : Jumping out of nested function calls.
·  Signal Handling : How to send, block, and handle signals.
·  Program Basics : Writing the beginning and end of your program.

Appendices

·  Language Features : C language features provided by the library.
·  Free Manuals : Free Software Needs Free Documentation.
·  Copying : The GNU Lesser General Public License says how you can copy and share the C Library.
·  Documentation License : This manual is under the GNU Free Documentation License.

Indices


--- The Detailed Node Listing ---

Introduction

·  Getting Started : What this manual is for and how to use it.
·  Roadmap to the Manual : Overview of the remaining chapters in this manual.

Standards and Portability

·  ISO C : The international standard for the C programming language.

Using the Library

·  Header Files : How to include the header files in your programs.
·  Macro Definitions : Some functions in the library may really be implemented as macros.
·  Reserved Names : The C standard reserves some names for the library, and some for users.

Error Reporting

·  Checking for Errors : How errors are reported by library functions.
·  Error Codes : Error code macros; all of these expand into integer constant values.
·  Error Messages : Mapping error codes onto error messages.

Memory

·  Memory Allocation : Allocating storage for your program data

Memory Allocation

·  Memory Allocation and C : How to get different kinds of allocation in C.
·  Unconstrained Allocation : The malloc facility allows fully general dynamic allocation.
·  Variable Size Automatic : Allocation of variable-sized blocks of automatic storage that are freed when the calling function returns.

Unconstrained Allocation

·  Basic Allocation : Simple use of malloc.
·  Malloc Examples : Examples of malloc. xmalloc.
·  Freeing after Malloc : Use free to free a block you got with malloc.
·  Changing Block Size : Use realloc to make a block bigger or smaller.
·  Allocating Cleared Space : Use calloc to allocate a block and clear it.

Variable Size Automatic

·  Alloca Example : Example of using alloca.
·  Advantages of Alloca : Reasons to use alloca.
·  Disadvantages of Alloca : Reasons to avoid alloca.
·  Variable-Size Arrays : Here is an alternative method of allocating dynamically and freeing automatically.

Character Handling

·  Classification of Characters : Testing whether characters are letters, digits, punctuation, etc.
·  Case Conversion : Case mapping, and the like.
·  Classification of Wide Characters : Character class determination for wide characters.
·  Using Wide Char Classes : Notes on using the wide character classes.
·  Wide Character Case Conversion : Mapping of wide characters.

String and Array Utilities

·  Representation of Strings : Introduction to basic concepts.
·  String/Array Conventions : Whether to use a string function or an arbitrary array function.
·  String Length : Determining the length of a string.
·  Copying and Concatenation : Functions to copy the contents of strings and arrays.
·  String/Array Comparison : Functions for byte-wise and character-wise comparison.
·  Collation Functions : Functions for collating strings.
·  Search Functions : Searching for a specific element or substring.
·  Finding Tokens in a String : Splitting a string into tokens by looking for delimiters.

Character Set Handling

·  Extended Char Intro : Introduction to Extended Characters.
·  Charset Function Overview : Overview about Character Handling Functions.
·  Restartable multibyte conversion : Restartable multibyte conversion Functions.
·  Non-reentrant Conversion : Non-reentrant Conversion Function.

Restartable multibyte conversion

·  Selecting the Conversion : Selecting the conversion and its properties.
·  Keeping the state : Representing the state of the conversion.
·  Converting a Character : Converting Single Characters.
·  Converting Strings : Converting Multibyte and Wide Character Strings.
·  Multibyte Conversion Example : A Complete Multibyte Conversion Example.

Non-reentrant Conversion

·  Non-reentrant Character Conversion : Non-reentrant Conversion of Single Characters.
·  Shift State : States in Non-reentrant Functions.

Locales

·  Effects of Locale : Actions affected by the choice of locale.
·  Choosing Locale : How the user specifies a locale.
·  Locale Categories : Different purposes for which you can select a locale.
·  Setting the Locale : How a program specifies the locale with library functions.
·  Standard Locales : Locale names available on all systems.
·  Locale Information : How to access the information for the locale.
·  Yes-or-No Questions : Check a Response against the locale.

Locale Information

·  The Lame Way to Locale Data : ISO C's localeconv.

The Lame Way to Locale Data

·  General Numeric : Parameters for formatting numbers and currency amounts.
·  Currency Symbol : How to print the symbol that identifies an amount of money (e.g. `$').
·  Sign of Money Amount : How to print the (positive or negative) sign for a monetary amount, if one exists.

Searching and Sorting

·  Comparison Functions : Defining how to compare two objects. Since the sort and search facilities are general, you have to specify the ordering.
·  Array Search Function : The bsearch function.
·  Array Sort Function : The qsort function.
·  Search/Sort Example : An example program.

I/O Overview

·  I/O Concepts : Some basic information and terminology.
·  File Names : How to refer to a file.

I/O Concepts

·  Streams and File Descriptors : The GNU Library provides two ways to access the contents of files.
·  File Position : The number of bytes from the beginning of the file.

File Names

·  Directories : Directories contain entries for files.
·  File Name Resolution : A file name specifies how to look up a file.
·  File Name Errors : Error conditions relating to file names.

I/O on Streams

·  Streams : About the data type representing a stream.
·  Standard Streams : Streams to the standard input and output devices are created for you.
·  Opening Streams : How to create a stream to talk to a file.
·  Closing Streams : Close a stream when you are finished with it.
·  Streams and I18N : Streams in internationalized applications.
·  Simple Output : Unformatted output by characters and lines.
·  Character Input : Unformatted input by characters and words.
·  Line Input : Reading a line or a record from a stream.
·  Unreading : Peeking ahead/pushing back input just read.
·  Block Input/Output : Input and output operations on blocks of data.
·  Formatted Output : printf and related functions.
·  Formatted Input : scanf and related functions.
·  EOF and Errors : How you can tell if an I/O error happens.
·  Error Recovery : What you can do about errors.
·  Binary Streams : Some systems distinguish between text files and binary files.
·  File Positioning : About random-access streams.
·  Portable Positioning : Random access on peculiar ISO C systems.
·  Stream Buffering : How to control buffering of streams.

Unreading

·  Unreading Idea : An explanation of unreading with pictures.
·  How Unread : How to call ungetc to do unreading.

Formatted Output

·  Formatted Output Basics : Some examples to get you started.
·  Output Conversion Syntax : General syntax of conversion specifications.
·  Table of Output Conversions : Summary of output conversions and what they do.
·  Integer Conversions : Details about formatting of integers.
·  Floating-Point Conversions : Details about formatting of floating-point numbers.
·  Other Output Conversions : Details about formatting of strings, characters, pointers, and the like.
·  Formatted Output Functions : Descriptions of the actual functions.
·  Variable Arguments Output : vprintf and friends.

Formatted Input

·  Formatted Input Basics : Some basics to get you started.
·  Input Conversion Syntax : Syntax of conversion specifications.
·  Table of Input Conversions : Summary of input conversions and what they do.
·  Numeric Input Conversions : Details of conversions for reading numbers.
·  String Input Conversions : Details of conversions for reading strings.
·  Other Input Conversions : Details of miscellaneous other conversions.
·  Formatted Input Functions : Descriptions of the actual functions.
·  Variable Arguments Input : vscanf and friends.

Stream Buffering

·  Buffering Concepts : Terminology is defined here.
·  Flushing Buffers : How to ensure that output buffers are flushed.
·  Controlling Buffering : How to specify what kind of buffering to use.

Low-Level I/O

·  Opening and Closing Files : How to open and close file descriptors.
·  I/O Primitives : Reading and writing data.
·  File Position Primitive : Setting a descriptor's file position.
·  Descriptors and Streams : Converting descriptor to stream or vice-versa.
·  Duplicating Descriptors : Fcntl commands for duplicating file descriptors.
·  File Status Flags : Fcntl commands for manipulating flags associated with open files.

File Status Flags

·  Access Modes : Whether the descriptor can read or write.
·  Open-time Flags : Details of open.
·  Operating Modes : Special modes to control I/O operations.

File System Interface

·  Working Directory : This is used to resolve relative file names.
·  Deleting Files : How to delete a file, and what that means.
·  Renaming Files : Changing a file's name.
·  Creating Directories : A system call just for creating a directory.
·  Temporary Files : Naming and creating temporary files.

File Attributes

·  Attribute Meanings : The names of the file attributes, and what their values mean.
·  Reading Attributes : How to read the attributes of a file.
·  File Size : Manually changing the size of a file.

Mathematics

·  Mathematical Constants : Precise numeric values for often-used constants.
·  Trig Functions : Sine, cosine, tangent, and friends.
·  Inverse Trig Functions : Arcsine, arccosine, etc.
·  Exponents and Logarithms : Also pow and sqrt.
·  Hyperbolic Functions : sinh, cosh, tanh, etc.
·  Special Functions : Bessel, gamma, erf.
·  Pseudo-Random Numbers : Functions for generating pseudo-random numbers.

Pseudo-Random Numbers

·  ISO Random : rand and friends.

Arithmetic

·  Integers : Basic integer types and concepts
·  Integer Division : Integer division with guaranteed rounding.
·  Floating Point Numbers : Basic concepts. IEEE 754.
·  Floating Point Classes : The five kinds of floating-point number.
·  Floating Point Errors : When something goes wrong in a calculation.
·  Rounding : Controlling how results are rounded.
·  Control Functions : Saving and restoring the FPU's state.
·  Arithmetic Functions : Fundamental operations provided by the library.
·  Complex Numbers : The types. Writing complex constants.
·  Operations on Complex : Projection, conjugation, decomposition.
·  Parsing of Numbers : Converting strings to numbers.

Floating Point Errors

·  FP Exceptions : IEEE 754 math exceptions and how to detect them.
·  Infinity and NaN : Special values returned by calculations.
·  Status bit operations : Checking for exceptions after the fact.
·  Math Error Reporting : How the math functions report errors.

Arithmetic Functions

·  Absolute Value : Absolute values of integers and floats.
·  Normalization Functions : Extracting exponents and putting them back.
·  Rounding Functions : Rounding floats to integers.
·  Remainder Functions : Remainders on division, precisely defined.
·  FP Bit Twiddling : Sign bit adjustment. Adding epsilon.
·  FP Comparison Functions : Comparisons without risk of exceptions.
·  Misc FP Arithmetic : Max, min, positive difference, multiply-add.

Parsing of Numbers

·  Parsing of Integers : Functions for conversion of integer values.
·  Parsing of Floats : Functions for conversion of floating-point values.

Date and Time

·  Time Basics : Concepts and definitions.
·  Elapsed Time : Data types to represent elapsed times
·  CPU Time : The clock function.
·  Calendar Time : Manipulation of ``real'' dates and times.
·  Sleeping : Waiting for a period of time.

Calendar Time

·  Simple Calendar Time : Facilities for manipulating calendar time.
·  Broken-down Time : Facilities for manipulating local time.
·  Formatting Calendar Time : Converting times to strings.
·  TZ Variable : How users specify the time zone.
·  Time Zone Functions : Functions to examine or specify the time zone.
·  Time Functions Example : An example program showing use of some of the time functions.

Non-Local Exits

·  Intro : When and how to use these facilities.
·  Details : Functions for non-local exits.

Signal Handling

·  Concepts of Signals : Introduction to the signal facilities.
·  Standard Signals : Particular kinds of signals with standard names and meanings.
·  Signal Actions : Specifying what happens when a particular signal is delivered.
·  Defining Handlers : How to write a signal handler function.
·  Generating Signals : How to send a signal to a process.

Concepts of Signals

·  Kinds of Signals : Some examples of what can cause a signal.
·  Signal Generation : Concepts of why and how signals occur.

Standard Signals

·  Program Error Signals : Used to report serious program errors.

Signal Actions

·  Basic Signal Handling : The simple signal function.

Defining Handlers

·  Handler Returns : Handlers that return normally, and what this means.
·  Termination in Handler : How handler functions terminate a program.
·  Longjmp in Handler : Nonlocal transfer of control out of a signal handler.
·  Signals in Handler : What happens when signals arrive while the handler is already occupied.
·  Nonreentrancy : Do not call any functions unless you know they are reentrant with respect to signals.
·  Atomic Data Access : A single handler can run in the middle of reading or writing a single object.

Atomic Data Access

·  Non-atomic Example : A program illustrating interrupted access.
·  Types : Data types that guarantee no interruption.
·  Usage : Proving that interruption is harmless.

Generating Signals

·  Signaling Yourself : A process can send a signal to itself.

Program Basics

·  Program Arguments : Parsing your program's command-line arguments.
·  Environment Variables : Less direct parameters affecting your program
·  Program Termination : Telling the system you're done; return status

Environment Variables

·  Environment Access : How to get and set the values of environment variables.

Program Termination

·  Normal Termination : If a program calls exit, a process terminates normally.
·  Exit Status : The exit status provides information about why the process terminated.
·  Cleanups on Exit : A process can run its own cleanup functions upon normal termination.
·  Aborting a Program : The abort function causes abnormal program termination.

Processes

·  Running a Command : The easy way to run another program.
·  Executing a File : How to make a process execute another program.

Language Features

·  Consistency Checking : Using assert to abort if something ``impossible'' happens.
·  Variadic Functions : Defining functions with varying numbers of args.
·  Null Pointer Constant : The macro NULL.
·  Important Data Types : Data types for object sizes.
·  Data Type Measurements : Parameters of data type representations.

Variadic Functions

·  Why Variadic : Reasons for making functions take variable arguments.
·  How Variadic : How to define and call variadic functions.
·  Variadic Example : A complete example.

How Variadic

·  Variadic Prototypes : How to make a prototype for a function with variable arguments.
·  Receiving Arguments : Steps you must follow to access the optional argument values.
·  How Many Arguments : How to decide whether there are more arguments.
·  Calling Variadics : Things you need to know about calling variable arguments functions.
·  Argument Macros : Detailed specification of the macros for accessing variable arguments.

Data Type Measurements

·  Width of Type : How many bits does an integer type hold?
·  Range of Type : What are the largest and smallest values that an integer type can hold?
·  Floating Type Macros : Parameters that measure the floating point types.
·  Structure Measurement : Getting measurements on structure types.

Floating Type Macros

·  Floating Point Concepts : Definitions of terminology.
·  Floating Point Parameters : Details of specific macros.
·  IEEE Floating Point : The measurements for one common representation.


Aborting a Program 
Previous:  Cleanups on Exit , Up:  Program Termination 




Aborting a Program

You can abort your program using the abort function. The prototype for this function is in stdlib.h.

-- Function: void abort (void)

The abort function causes abnormal program termination. This does not execute cleanup functions registered with atexit. 

This function actually terminates the process by raising a SIGABRT signal, and your program can include a handler to intercept this signal; see  Signal Handling .

 
Future Change Warning: Proposed Federal censorship regulations may prohibit us from giving you information about the possibility of calling this function. We would be required to say that this is not an acceptable way of terminating a program.	 

Absolute Value 
Next:  Normalization Functions , Up:  Arithmetic Functions 




Absolute Value

These functions are provided for obtaining the absolute value (or magnitude) of a number. The absolute value of a real number x is x if x is positive, -x if x is negative. For a complex number z, whose real part is x and whose imaginary part is y, the absolute value is sqrt (x*x + y*y). 

Prototypes for abs, labs and llabs are in stdlib.h; imaxabs is declared in inttypes.h; fabs, fabsf and fabsl are declared in math.h. cabs, cabsf and cabsl are declared in complex.h.

-- Function: int abs (int number)

-- Function: long int labs (long int number)

-- Function: long long int llabs (long long int number)

-- Function: intmax_t imaxabs (intmax_t number)

These functions return the absolute value of number. 

Most computers use a two's complement integer representation, in which the absolute value of INT_MIN (the smallest possible int) cannot be represented; thus, abs (INT_MIN) is not defined. 

llabs and imaxdiv are new to ISO C99. 

See  Integers  for a description of the intmax_t type.

-- Function: double fabs (double number)

-- Function: float fabsf (float number)

-- Function: long double fabsl (long double number)

This function returns the absolute value of the floating-point number number.

-- Function: double cabs (complex double z)

-- Function: float cabsf (complex float z)

-- Function: long double cabsl (complex long double z)

These functions return the absolute value of the complex number z (see  Complex Numbers ). The absolute value of a complex number is: 

          sqrt (creal (z) * creal (z) + cimag (z) * cimag (z))
     
This function should always be used instead of the direct formula because it takes special care to avoid losing precision. It may also take advantage of hardware support for this operation. See hypot in  Exponents and Logarithms .

Access Modes 
Next:  Open-time Flags , Up:  File Status Flags 




File Access Modes

The file access modes allow a file descriptor to be used for reading, writing, or both.  The access modes are chosen when the file is opened, and never change.

-- Macro: int O_RDONLY

Open the file for read access.

-- Macro: int O_WRONLY

Open the file for write access.

-- Macro: int O_RDWR

Open the file for both reading and writing.

-- Macro: int O_ACCMODE

This macro stands for a mask that can be bitwise-ANDed with the file status flag value to produce a value representing the file access mode. The mode will be O_RDONLY, O_WRONLY, or O_RDWR.

Advantages of Alloca 
Next:  Disadvantages of Alloca , Previous:  Alloca Example , Up:  Variable Size Automatic 




Advantages of alloca

Here are the reasons why alloca may be preferable to malloc:

· Using alloca wastes very little space and is very fast. (It is open-coded by the C compiler.) 
· Since alloca does not have separate pools for different sizes of block, space used for any size block can be reused for any other size. alloca does not cause memory fragmentation. 
· Nonlocal exits done with longjmp (see  Non-Local Exits ) automatically free the space allocated with alloca when they exit through the function that called alloca. This is the most important reason to use alloca. 

To illustrate this, suppose you have a function open_or_report_error which returns a descriptor, like open, if it succeeds, but does not return to its caller if it fails. If the file cannot be opened, it prints an error message and jumps out to the command level of your program using longjmp. Let's change open2 (see  Alloca Example ) to use this subroutine: 

          int
          open2 (char *str1, char *str2, int flags, int mode)
          {
            char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
            stpcpy (stpcpy (name, str1), str2);
            return open_or_report_error (name, flags, mode);
          }
     
Because of the way alloca works, the memory it allocates is freed even when an error occurs, with no special effort required. 

By contrast, the previous definition of open2 (which uses malloc and free) would develop a memory leak if it were changed in this way. Even if you are willing to make more changes to fix it, there is no easy way to do so.

Alloca Example 
Next:  Advantages of Alloca , Up:  Variable Size Automatic 




alloca Example

As an example of the use of alloca, here is a function that opens a file name made from concatenating two argument strings, and returns a file descriptor or minus one signifying failure:

     int
     open2 (char *str1, char *str2, int flags, int mode)
     {
       char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
       stpcpy (stpcpy (name, str1), str2);
       return open (name, flags, mode);
     }

Here is how you would get the same results with malloc and free:

     int
     open2 (char *str1, char *str2, int flags, int mode)
     {
       char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
       int desc;
       if (name == 0)
         fatal ("virtual memory exceeded");
       stpcpy (stpcpy (name, str1), str2);
       desc = open (name, flags, mode);
       free (name);
       return desc;
     }

As you can see, it is simpler with alloca. But alloca has other, more important advantages, and some disadvantages.

Allocating Cleared Space 
Previous:  Changing Block Size , Up:  Unconstrained Allocation 




Allocating Cleared Space

The function calloc allocates memory and clears it to zero. It is declared in stdlib.h.
-- Function: void * calloc (size_t count, size_t eltsize)

This function allocates a block long enough to contain a vector of count elements, each of size eltsize. Its contents are cleared to zero before calloc returns.

You could define calloc as follows:

     void *
     calloc (size_t count, size_t eltsize)
     {
       size_t size = count * eltsize;
       void *value = malloc (size);
       if (value != 0)
         memset (value, 0, size);
       return value;
     }

But in general, it is not guaranteed that calloc calls malloc internally. Therefore, if an application provides its own malloc/realloc/free outside the C library, it should always define calloc, too.

Argument Macros 
Previous:  Calling Variadics , Up:  How Variadic 




Argument Access Macros

Here are descriptions of the macros used to retrieve variable arguments. These macros are defined in the header file stdarg.h.

-- Data Type: va_list

The type va_list is used for argument pointer variables.

-- Macro: void va_start (va_list ap, last-required)

This macro initializes the argument pointer variable ap to point to the first of the optional arguments of the current function; last-required must be the last required argument to the function. 

-- Macro: type va_arg (va_list ap, type)

The va_arg macro returns the value of the next optional argument, and modifies the value of ap to point to the subsequent argument. Thus, successive uses of va_arg return successive optional arguments. 

The type of the value returned by va_arg is type as specified in the call. type must be a self-promoting type (not char or short int or float) that matches the type of the actual argument.

-- Macro: void va_end (va_list ap)

This ends the use of ap. After a va_end call, further va_arg calls with the same ap may not work. You should invoke va_end before returning from the function in which va_start was invoked with the same ap argument. 

In this C library, va_end does nothing, and you need not ever use it except for reasons of portability.

Sometimes it is necessary to parse the list of parameters more than once or one wants to remember a certain position in the parameter list. To do this, one will have to make a copy of the current value of the argument. But va_list is an opaque type and one cannot necessarily assign the value of one variable of type va_list to another variable of the same type.

-- Macro: void __va_copy (va_list dest, va_list src)

The va_copy macro allows copying of objects of type va_list even if this is not an integral type. The argument pointer in dest is initialized to point to the same argument as the pointer in src. 

If you want to use va_copy you should always be prepared for the possibility that this macro will not be available. On architectures where a simple assignment is invalid, hopefully va_copy will be available, so one should always write something like this:

     {
       va_list ap, save;
       ...
     #ifdef va_copy
       va_copy (save, ap);
     #else
       save = ap;
     #endif
       ...
     }

Arithmetic Functions 
Next:  Complex Numbers , Previous:  Control Functions , Up:  Arithmetic 




Arithmetic Functions

The C library provides functions to do basic operations on floating-point numbers. These include absolute value, maximum and minimum, normalization, bit twiddling, rounding, and a few others.

·  Absolute Value : Absolute values of integers and floats.
·  Normalization Functions : Extracting exponents and putting them back.
·  Rounding Functions : Rounding floats to integers.
·  Remainder Functions : Remainders on division, precisely defined.
·  FP Bit Twiddling : Sign bit adjustment. Adding epsilon.
·  FP Comparison Functions : Comparisons without risk of exceptions.
·  Misc FP Arithmetic : Max, min, positive difference, multiply-add.

 Arithmetic
Next:  Date and Time , Previous:  Mathematics , Up:  Top 




Arithmetic

This chapter contains information about functions for doing basic arithmetic operations, such as splitting a float into its integer and fractional parts or retrieving the imaginary part of a complex value. These functions are declared in the header files math.h and complex.h.

·  Integers : Basic integer types and concepts
·  Integer Division : Integer division with guaranteed rounding.
·  Floating Point Numbers : Basic concepts. IEEE 754.
·  Floating Point Classes : The five kinds of floating-point number.
·  Floating Point Errors : When something goes wrong in a calculation.
·  Rounding : Controlling how results are rounded.
·  Control Functions : Saving and restoring the FPU's state.
·  Arithmetic Functions : Fundamental operations provided by the library.
·  Complex Numbers : The types. Writing complex constants.
·  Operations on Complex : Projection, conjugation, decomposition.
·  Parsing of Numbers : Converting strings to numbers.

Array Search Function 
Next:  Array Sort Function , Previous:  Comparison Functions , Up:  Searching and Sorting 




Array Search Function

Generally searching for a specific element in an array means that potentially all elements must be checked. The C library contains functions to perform linear search. The prototypes for the following two functions can be found in search.h.
-- Function: void * lfind (const void *key, void *base, size_t *nmemb, size_t size, comparison_fn_t compar)

The lfind function searches in the array with *nmemb elements of size bytes pointed to by base for an element which matches the one pointed to by key. The function pointed to by compar is used decide whether two elements match. 

The return value is a pointer to the matching element in the array starting at base if it is found. If no matching element is available NULL is returned. 

The mean runtime of this function is *nmemb/2. This function should only be used elements often get added to or deleted from the array in which case it might not be useful to sort the array before searching.

-- Function: void * lsearch (const void *key, void *base, size_t *nmemb, size_t size, comparison_fn_t compar)

The lsearch function is similar to the lfind function. It searches the given array for an element and returns it if found. The difference is that if no matching element is found the lsearch function adds the object pointed to by key (with a size of size bytes) at the end of the array and it increments the value of *nmemb to reflect this addition. 

This means for the caller that if it is not sure that the array contains the element one is searching for the memory allocated for the array starting at base must have room for at least size more bytes. If one is sure the element is in the array it is better to use lfind so having more room in the array is always necessary when calling lsearch.

To search a sorted array for an element matching the key, use the bsearch function. The prototype for this function is in the header file stdlib.h.
-- Function: void * bsearch (const void *key, const void *array, size_t count, size_t size, comparison_fn_t compare)

The bsearch function searches the sorted array array for an object that is equivalent to key. The array contains count elements, each of which is of size size bytes. 

The compare function is used to perform the comparison. This function is called with two pointer arguments and should return an integer less than, equal to, or greater than zero corresponding to whether its first argument is considered less than, equal to, or greater than its second argument. The elements of the array must already be sorted in ascending order according to this comparison function. 

The return value is a pointer to the matching array element, or a null pointer if no match is found. If the array contains more than one element that matches, the one that is returned is unspecified. 

This function derives its name from the fact that it is implemented using the binary search algorithm.

Array Sort Functionrray Sort Function 
Next:  Search/Sort Example , Previous:  Array Search Function , Up:  Searching and Sorting 




Array Sort Function

To sort an array using an arbitrary comparison function, use the qsort function. The prototype for this function is in stdlib.h.
-- Function: void qsort (void *array, size_t count, size_t size, comparison_fn_t compare)

The qsort function sorts the array array. The array contains count elements, each of which is of size size. 

The compare function is used to perform the comparison on the array elements. This function is called with two pointer arguments and should return an integer less than, equal to, or greater than zero corresponding to whether its first argument is considered less than, equal to, or greater than its second argument. 

Warning: If two objects compare as equal, their order after sorting is unpredictable. That is to say, the sorting is not stable. This can make a difference when the comparison considers only part of the elements. Two elements with the same sort key may differ in other respects. 

If you want the effect of a stable sort, you can get this result by writing the comparison function so that, lacking other reason distinguish between two elements, it compares them by their addresses. Note that doing this may make the sorting algorithm less efficient, so do it only if necessary. 

Here is a simple example of sorting an array of doubles in numerical order, using the comparison function defined above (see  Comparison Functions ): 

          {
            double *array;
            int size;
            ...
            qsort (array, size, sizeof (double), compare_doubles);
          }
     
The qsort function derives its name from the fact that it was originally implemented using the "quick sort" algorithm. 

The implementation of qsort in this library might not be an in-place sort and might thereby use an extra amount of memory to store the array.

Atomic Data Access 
Previous:  Nonreentrancy , Up:  Defining Handlers 




Atomic Data Access and Signal Handling

Whether the data in your application concerns atoms, or mere text, you have to be careful about the fact that access to a single datum is not necessarily atomic. This means that it can take more than one instruction to read or write a single object. In such cases, a signal handler might be invoked in the middle of reading or writing the object. 

There are two ways you can cope with this problem. You can use data types that are always accessed atomically; you can carefully arrange that nothing untoward happens if an access is interrupted.

·  Non-atomic Example : A program illustrating interrupted access.
·  Types : Data types that guarantee no interruption.
·  Usage : Proving that interruption is harmless.

Atomic Types 
Next:  Atomic Usage , Previous:  Non-atomic Example , Up:  Atomic Data Access 




Atomic Types

To avoid uncertainty about interrupting access to a variable, you can use a particular data type for which access is always atomic: sig_atomic_t. Reading and writing this data type is guaranteed to happen in a single instruction, so there's no way for a handler to run "in the middle" of an access. 

The type sig_atomic_t is always an integer data type, but which one it is, and how many bits it contains, may vary from machine to machine.

-- Data Type: sig_atomic_t

This is an integer data type. Objects of this type are always accessed atomically.

In practice, you can assume that int and other integer types no longer than int are atomic. You can also assume that pointer types are atomic; that is very convenient. Both of these assumptions are true on all of the machines that the C library supports and on all POSIX systems we know of.

Atomic Usage 
Previous:  Atomic Types , Up:  Atomic Data Access 




Atomic Usage Patterns

Certain patterns of access avoid any problem even if an access is interrupted. For example, a flag which is set by the handler, and tested and cleared by the main program from time to time, is always safe even if access actually requires two instructions. To show that this is so, we must consider each access that could be interrupted, and show that there is no problem if it is interrupted. 

An interrupt in the middle of testing the flag is safe because either it's recognized to be nonzero, in which case the precise value doesn't matter, or it will be seen to be nonzero the next time it's tested. 

An interrupt in the middle of clearing the flag is no problem because either the value ends up zero, which is what happens if a signal comes in just before the flag is cleared, or the value ends up nonzero, and subsequent events occur as if the signal had come in just after the flag was cleared. As long as the code handles both of these cases properly, it can also handle a signal in the middle of clearing the flag. (This is an example of the sort of reasoning you need to do to figure out whether non-atomic usage is safe.) 

Attribute Meanings 
Next:  Reading Attributes , Up:  File System Interface


The meaning of the File Attributes

When you read the attributes of a file, they come back in a structure called struct stat. This section describes the names of the attributes, their data types, and what they mean. For the functions to read the attributes of a file, see  Reading Attributes . 

The header file sys/stat.h declares all the symbols defined in this section
.
-- Data Type: struct stat

The stat structure type is used to return information about the attributes of a file. It contains at least the following members:

mode_t st_mode
           Specifies the mode of the file. This includes file type information  and the file permission bits 
ino_t st_ino
The file serial number, which distinguishes this file from all other files on the same device. 
dev_t st_dev
Identifies the device containing the file. The st_ino and st_dev, taken together, uniquely identify the file. The st_dev value is not necessarily consistent across reboots or system crashes, however. 
off_t st_size
This specifies the size of a regular file in bytes. For files that are really devices this field isn't usually meaningful. For symbolic links this specifies the length of the file name the link refers to. 
time_t st_atime
This is the last access time for the file.
time_t st_mtime
This is the time of the last modification to the contents of the file.
time_t st_ctime
This is the time of the last modification to the attributes of the file.

Some of the file attributes have special data type names which exist specifically for those attributes. (They are all aliases for well-known integer types that you know and love.) These typedef names are defined in the header file sys/types.h as well as in sys/stat.h. Here is a list of them.

-- Data Type: mode_t

This is an integer data type used to represent file modes. In the GNU system, this is equivalent to unsigned int.

-- Data Type: ino_t

This is an arithmetic data type used to represent file serial numbers. (In Unix jargon, these are sometimes called inode numbers.) In the GNU system, this type is equivalent to unsigned long int. 

If the source is compiled with _FILE_OFFSET_BITS == 64 this type is transparently replaced by ino64_t.
-- Data Type: dev_t

This is an arithmetic data type used to represent file device numbers. In the GNU system, this is equivalent to int.

Basic Allocation 
Next:  Malloc Examples , Up:  Unconstrained Allocation 




Basic Memory Allocation

To allocate a block of memory, call malloc. The prototype for this function is in stdlib.h.

-- Function: void * malloc (size_t size)

This function returns a pointer to a newly allocated block size bytes long, or a null pointer if the block could not be allocated.

The contents of the block are undefined; you must initialize it yourself (or use calloc instead; see  Allocating Cleared Space ). Normally you would cast the value as a pointer to the kind of object that you want to store in the block. Here we show an example of doing so, and of initializing the space with zeros using the library function memset (see  Copying and Concatenation ):

     struct foo *ptr;
     ...
     ptr = (struct foo *) malloc (sizeof (struct foo));
     if (ptr == 0) abort ();
     memset (ptr, 0, sizeof (struct foo));

You can store the result of malloc into any pointer variable without a cast, because ISO C automatically converts the type void * to another type of pointer when necessary. But the cast is necessary in contexts other than assignment operators or if you might want your code to run in traditional C. 

Remember that when allocating space for a string, the argument to malloc must be one plus the length of the string. This is because a string is terminated with a null character that doesn't count in the "length" of the string but does need space. For example:

     char *ptr;
     ...
     ptr = (char *) malloc (length + 1);

See  Representation of Strings , for more information about this.

Basic Signal Handling 
Up:  Signal Actions 




Basic Signal Handling

The signal function provides a simple interface for establishing an action for a particular signal. The function and associated macros are declared in the header file signal.h.

-- Data Type: sighandler_t

This is the type of signal handler functions. Signal handlers take one integer argument specifying the signal number, and have return type void. So, you should define handler functions like this: 

          void handler (int signum) { ... }
     
The name sighandler_t for this data type is a GNU extension.

-- Function: sighandler_t signal (int signum, sighandler_t action)

The signal function establishes action as the action for the signal signum. 

The first argument, signum, identifies the signal whose behavior you want to control, and should be a signal number. The proper way to specify a signal number is with one of the symbolic signal names (see  Standard Signals )--don't use an explicit number, because the numerical code for a given kind of signal may vary from operating system to operating system. 

The second argument, action, specifies the action to use for the signal signum. This can be one of the following:

SIG_DFL
SIG_DFL specifies the default action for the particular signal. The default actions for various kinds of signals are stated in  Standard Signals . 
SIG_IGN
SIG_IGN specifies that the signal should be ignored. 

Your program generally should not ignore signals that represent serious events or that are normally used to request termination. You cannot ignore the SIGKILL or SIGSTOP signals at all. You can ignore program error signals like SIGSEGV, but ignoring the error won't enable the program to continue executing meaningfully. Ignoring user requests such as SIGINT, SIGQUIT, and SIGTSTP is unfriendly. 

When you do not wish signals to be delivered during a certain part of the program, the thing to do is to block them, not ignore them. See  Blocking Signals . 
handler
Supply the address of a handler function in your program, to specify running this handler as the way to deliver the signal. 

For more information about defining signal handler functions, see  Defining Handlers .

If you set the action for a signal to SIG_IGN, or if you set it to SIG_DFL and the default action is to ignore that signal, then any pending signals of that type are discarded (even if they are blocked). Discarding the pending signals means that they will never be delivered, not even if you subsequently specify another action and unblock this kind of signal. 

The signal function returns the action that was previously in effect for the specified signum. You can save this value and restore it later by calling signal again. 

If signal can't honor the request, it returns SIG_ERR instead. The following errno error conditions are defined for this function:

EINVAL
You specified an invalid signum; or you tried to ignore or provide a handler for SIGKILL or SIGSTOP.

Compatibility Note: A problem encountered when working with the signal function is that it has different semantics on BSD and SVID systems. The difference is that on SVID systems the signal handler is deinstalled after signal delivery. On BSD systems the handler must be explicitly deinstalled. In this library we use the SVID version.

Here is a simple example of setting up a handler to delete temporary files when certain fatal signals happen:

     #include <signal.h>
     
     void
     termination_handler (int signum)
     {
       struct temp_file *p;
     
       for (p = temp_file_list; p; p = p->next)
         unlink (p->name);
     }
     
     int
     main (void)
     {
       ...
       if (signal (SIGINT, termination_handler) == SIG_IGN)
         signal (SIGINT, SIG_IGN);
       if (signal (SIGHUP, termination_handler) == SIG_IGN)
         signal (SIGHUP, SIG_IGN);
       if (signal (SIGTERM, termination_handler) == SIG_IGN)
         signal (SIGTERM, SIG_IGN);
       ...
     }

Note that if a given signal was previously set to be ignored, this code avoids altering that setting. This is because non-job-control shells often ignore certain signals when starting children, and it is important for the children to respect this. 

We do not handle SIGQUIT or the program error signals in this example because these are designed to provide information for debugging (a core dump), and the temporary files may give useful information.

-- Macro: sighandler_t SIG_ERR

The value of this macro is used as the return value from signal to indicate an error.

Binary Streams 
Next:  File Positioning , Previous:  Error Recovery , Up:  I/O on Streams 




Text and Binary Streams

POSIX-compatible operating systems organize all files as uniform sequences of characters. However, this system makes a subtle distinction between files containing text and files containing binary data, and the input and output facilities of ISO C provide for this distinction. 

When you open a stream, you can specify either a text stream or a binary stream. You indicate that you want a binary stream by specifying the `b' modifier in the opentype argument to fopen; see  Opening Streams . Without this option, fopen opens the file as a text stream. 

Text and binary streams differ in several ways:

· The data read from a text stream is divided into lines which are terminated by newline ('\n') characters, while a binary stream is simply a long series of characters. A text stream might on some systems fail to handle lines more than 254 characters long (including the terminating newline character).
· On some systems, text files can contain only printing characters, horizontal tab characters, and newlines, and so text streams may not support other characters. However, binary streams can handle any character value. 
· Space characters that are written immediately preceding a newline character in a text stream may disappear when the file is read in again. 
· More generally, there need not be a one-to-one mapping between characters that are read from or written to a text stream, and the characters in the actual file.

Since a binary stream is always more capable and more predictable than a text stream, you might wonder what purpose text streams serve. Why not simply always use binary streams? The answer is that on these operating systems, text and binary streams use different file formats, and the only way to read or write "an ordinary file of text" that can work with other text-oriented programs is through a text stream. 

In the GNU library, and on all POSIX systems, there is no difference between text streams and binary streams. When you open a stream, you get the same kind of stream regardless of whether you ask for binary. This stream can handle any file content, and has none of the restrictions that text streams sometimes have.

Block Input/Output 
Next:  Formatted Output , Previous: Line Input, Up:  I/O on Streams 




Block Input/Output

This section describes how to do input and output operations on blocks of data. You can use these functions to read and write binary data, as well as to read and write text in fixed-size blocks instead of by characters or lines. Binary files are typically used to read and write blocks of data in the same format as is used to represent the data in a running program. In other words, arbitrary blocks of memory--not just character or string objects--can be written to a binary file, and meaningfully read in again by the same program. 

Storing data in binary form is often considerably more efficient than using the formatted I/O functions. Also, for floating-point numbers, the binary form avoids possible loss of precision in the conversion process. On the other hand, binary files can't be examined or modified easily using many standard file utilities (such as text editors), and are not portable between different implementations of the language, or different kinds of computers. 

These functions are declared in stdio.h.

-- Function: size_t fread (void *data, size_t size, size_t count, FILE *stream)

This function reads up to count objects of size size into the array data, from the stream stream. It returns the number of objects actually read, which might be less than count if a read error occurs or the end of the file is reached. This function returns a value of zero (and doesn't read anything) if either size or count is zero. 

If fread encounters end of file in the middle of an object, it returns the number of complete objects read, and discards the partial object. Therefore, the stream remains at the actual end of the file.

-- Function: size_t fwrite (const void *data, size_t size, size_t count, FILE *stream)

This function writes up to count objects of size size from the array data, to the stream stream. The return value is normally count, if the call succeeds. Any other value indicates some sort of error, such as running out of space.

Broken-down Time 
Next:   Formatting Calendar Time ,Up:  Calendar Time 




Broken-down Time

Calendar time is represented by the usual C library functions as an elapsed time since a fixed base calendar time. This is convenient for computation, but has no relation to the way people normally think of calendar time. By contrast, broken-down time is a binary representation of calendar time separated into year, month, day, and so on. Broken-down time values are not useful for calculations, but they are useful for printing human readable time information. 

A broken-down time value is always relative to a choice of time zone.

The symbols in this section are declared in the header file time.h.
-- Data Type: struct tm

This is the data type used to represent a broken-down time. The structure contains at least the following members, which can appear in any order.

int tm_sec
This is the number of full seconds since the top of the minute (normally in the range 0 through 59, but the actual upper limit is 60, to allow for leap seconds if leap second support is available).
int tm_min
This is the number of full minutes since the top of the hour (in the range 0 through 59). 
int tm_hour
This is the number of full hours past midnight (in the range 0 through 23). 
int tm_mday
This is the ordinal day of the month (in the range 1 through 31). Watch out for this one! As the only ordinal number in the structure, it is inconsistent with the rest of the structure. 
int tm_mon
This is the number of full calendar months since the beginning of the year (in the range 0 through 11). Watch out for this one! People usually use ordinal numbers for month-of-year (where January = 1). 
int tm_year
This is the number of full calendar years since 1900. 
int tm_wday
This is the number of full days since Sunday (in the range 0 through 6). 
int tm_yday
This is the number of full days since the beginning of the year (in the range 0 through 365). 
int tm_isdst
This is a flag that indicates whether Daylight Saving Time is (or was, or will be) in effect at the time described. The value is positive if Daylight Saving Time is in effect, zero if it is not, and negative if the information is not available. 

-- Function: struct tm * localtime (const time_t *time)

The localtime function converts the simple time pointed to by time to broken-down time representation, expressed relative to the user's specified time zone. 

The return value is a pointer to a static broken-down time structure, which might be overwritten by subsequent calls to ctime, gmtime, or localtime. (But no other library function overwrites the contents of this object.) 

The return value is the null pointer if time cannot be represented as a broken-down time; typically this is because the year cannot fit into an int. 

Calling localtime has one other effect: it sets the variable tzname with information about the current time zone. See  Time Zone Functions .

-- Function: struct tm * gmtime (const time_t *time)

This function is similar to localtime, except that the broken-down time is expressed as Coordinated Universal Time (UTC) (formerly called Greenwich Mean Time (GMT)) rather than relative to a local time zone.

-- Function: time_t mktime (struct tm *brokentime)

The mktime function is used to convert a broken-down time structure to a simple time representation. It also "normalizes" the contents of the broken-down time structure, by filling in the day of week and day of year based on the other date and time components. 

The mktime function ignores the specified contents of the tm_wday and tm_yday members of the broken-down time structure. It uses the values of the other components to determine the calendar time; it's permissible for these components to have unnormalized values outside their normal ranges. The last thing that mktime does is adjust the components of the brokentime structure (including the tm_wday and tm_yday). 

If the specified broken-down time cannot be represented as a simple time, mktime returns a value of (time_t)(-1) and does not modify the contents of brokentime. 

Calling mktime also sets the variable tzname with information about the current time zone. See  Time Zone Functions .

Buffering Concepts 
Next:  Flushing Buffers , Up:  Stream Buffering 




Buffering Concepts

There are three different kinds of buffering strategies:

· Characters written to or read from an unbuffered stream are transmitted individually to or from the file as soon as possible.
· Characters written to a line buffered stream are transmitted to the file in blocks when a newline character is encountered.
· Characters written to or read from a fully buffered stream are transmitted to or from the file in blocks of arbitrary size.

Newly opened streams are normally fully buffered, with one exception: a stream connected to an interactive device such as a terminal is initially line buffered. See  Controlling Buffering , for information on how to select a different kind of buffering. Usually the automatic selection gives you the most convenient kind of buffering for the file or device you open. 

The use of line buffering for interactive devices implies that output messages ending in a newline will appear immediately--which is usually what you want. Output that doesn't end in a newline might or might not show up immediately, so if you want them to appear immediately, you should flush buffered output explicitly with fflush, as described in  Flushing Buffers .

Calendar Time 
Next:  Simple Calendar Time , Previous:  CPU Time,, Up:  Date and Time 




Calendar Time

This section describes facilities for keeping track of calendar time. See  Time Basics . 

The C library represents calendar time two ways:

· Simple time (the time_t data type) is a compact representation, typically giving the number of seconds of elapsed time since some implementation-specific base time.
· Local time or broken-down time (the struct tm data type) represents a calendar time as a set of components specifying the year, month, and so on in the Gregorian calendar, for a specific time zone. This calendar time representation is usually used only to communicate with people.

·  Simple Calendar Time : Facilities for manipulating calendar time.
·  Broken-down Time : Facilities for manipulating local time.
·  Formatting Calendar Time : Converting times to strings.
·  TZ Variable : How users specify the time zone.
·  Time Zone Functions : Functions to examine or specify the time zone.
·  Time Functions Example : An example program showing use of some of the time functions.

Calling Variadics 
Next:  Argument Macros , Previous:  How Many Arguments , Up:  How Variadic 




Calling Variadic Functions

You don't have to do anything special to call a variadic function. Just put the arguments (required arguments, followed by optional ones) inside parentheses, separated by commas, as usual. But you must declare the function with a prototype and know how the argument values are converted. 

In principle, functions that are defined to be variadic must also be declared to be variadic using a function prototype whenever you call them. (See  Variadic Prototypes , for how.) This is because some C compilers use a different calling convention to pass the same set of argument values to a function depending on whether that function takes variable arguments or fixed arguments. 

In practice, this C compiler always passes a given set of argument types in the same way regardless of whether they are optional or required. So, as long as the argument types are self-promoting, you can safely omit declaring them. Usually it is a good idea to declare the argument types for variadic functions, and indeed for all functions. But there are a few functions which it is extremely convenient not to have to declare as variadic--for example, open and printf. 

Since the prototype doesn't specify types for optional arguments, in a call to a variadic function the default argument promotions are performed on the optional argument values. This means the objects of type char or short int (whether signed or not) are promoted to either int or unsigned int, as appropriate; and that objects of type float are promoted to type double. So, if the caller passes a char as an optional argument, it is promoted to an int, and the function can access it with va_arg (ap, int). 

Conversion of the required arguments is controlled by the function prototype in the usual way: the argument expression is converted to the declared argument type as if it were being assigned to a variable of that type.

Case Conversion 
Next:  Classification of Wide Characters , Previous:  Classification of Characters , Up:  Character Handling 




Case Conversion

This section explains the library functions for performing conversions such as case mappings on characters. For example, toupper converts any character to upper case if possible. If the character can't be converted, toupper returns it unchanged. 

These functions take one argument of type int, which is the character to convert, and return the converted character as an int. If the conversion is not applicable to the argument given, the argument is returned unchanged. 

Compatibility Note: In pre-ISO C dialects, instead of returning the argument unchanged, these functions may fail when the argument is not suitable for the conversion. Thus for portability, you may need to write islower(c) ? toupper(c) : c rather than just toupper(c). 

These functions are declared in the header file ctype.h.

-- Function: int tolower (int c)

If c is an upper-case letter, tolower returns the corresponding lower-case letter. If c is not an upper-case letter, c is returned unchanged.

-- Function: int toupper (int c)

If c is a lower-case letter, toupper returns the corresponding upper-case letter. Otherwise c is returned unchanged.

-- Function: int toascii (int c)

This function converts c to a 7-bit unsigned char value that fits into the US/UK ASCII character set, by clearing the high-order bits. This function is a BSD extension and is also an SVID extension.

-- Function: int _tolower (int c)

This is identical to tolower, and is provided for compatibility with the SVID. See  SVID .

-- Function: int _toupper (int c)

This is identical to toupper, and is provided for compatibility with the SVID.

Changing Block Size 
Next:  Allocating Cleared Space , Previous:  Freeing after Malloc , Up:  Unconstrained Allocation 




Changing the Size of a Block

Often you do not know for certain how big a block you will ultimately need at the time you must begin to use the block. For example, the block might be a buffer that you use to hold a line being read from a file; no matter how long you make the buffer initially, you may encounter a line that is longer. 

You can make the block longer by calling realloc. This function is declared in stdlib.h.

-- Function: void * realloc (void *ptr, size_t newsize)

The realloc function changes the size of the block whose address is ptr to be newsize. 

Since the space after the end of the block may be in use, realloc may find it necessary to copy the block to a new address where more free space is available. The value of realloc is the new address of the block. If the block needs to be moved, realloc copies the old contents. 

If you pass a null pointer for ptr, realloc behaves just like `malloc (newsize)'. This can be convenient, but beware that older implementations (before ISO C) may not support this behavior, and will probably crash when realloc is passed a null pointer.

Like malloc, realloc may return a null pointer if no memory space is available to make the block bigger. When this happens, the original block is untouched; it has not been modified or relocated. 

In most cases it makes no difference what happens to the original block when realloc fails, because the application program cannot continue when it is out of memory, and the only thing to do is to give a fatal error message. Often it is convenient to write and use a subroutine, conventionally called xrealloc, that takes care of the error message as xmalloc does for malloc:

     void *
     xrealloc (void *ptr, size_t size)
     {
       register void *value = realloc (ptr, size);
       if (value == 0)
         fatal ("Virtual memory exhausted");
       return value;
     }

You can also use realloc to make a block smaller. The reason you would do this is to avoid tying up a lot of memory space when only a little is needed. In several allocation implementations, making a block smaller sometimes necessitates copying it, so it can fail if no other space is available. 

If the new size you specify is the same as the old size, realloc is guaranteed to change nothing and return the same address that you gave.

Character Handling
Next:  String and Array Utilities , Previous:  Memory , Up:  Top 




Character Handling

Programs that work with characters and strings often need to classify a character--is it alphabetic, is it a digit, is it whitespace, and so on--and perform case conversion operations on characters. The functions in the header file ctype.h are provided for this purpose. Since the choice of locale and character set can alter the classifications of particular character codes, all of these functions are affected by the current locale. (More precisely, they are affected by the locale currently selected for character classification--the LC_CTYPE category; see  Locale Categories .) 

The ISO C standard specifies two different sets of functions. The one set works on char type characters, the other one on wchar_t wide characters (see  Extended Char Intro ).

·  Classification of Characters : Testing whether characters are letters, digits, punctuation, etc.
·  Case Conversion : Case mapping, and the like.
·  Classification of Wide Characters : Character class determination for wide characters.
·  Using Wide Char Classes : Notes on using the wide character classes.
·  Wide Character Case Conversion : Mapping of wide characters.

Character Input 
Next:  Line Input , Previous:  Simple Output , Up:  I/O on Streams 




Character Input

This section describes functions for performing character-oriented input. These narrow streams functions are declared in the header file stdio.h and the wide character functions are declared in wchar.h. These functions return an int or wint_t value (for narrow and wide stream functions respectively) that is either a character of input, or the special value EOF/WEOF (usually -1). For the narrow stream functions it is important to store the result of these functions in a variable of type int instead of char, even when you plan to use it only as a character. Storing EOF in a char variable truncates its value to the size of a character, so that it is no longer distinguishable from the valid character `(char) -1'. So always use an int for the result of getc and friends, and check for EOF after the call; once you've verified that the result is not EOF, you can be sure that it will fit in a `char' variable without loss of information.

-- Function: int fgetc (FILE *stream)

This function reads the next character as an unsigned char from the stream stream and returns its value, converted to an int. If an end-of-file condition or read error occurs, EOF is returned instead.

-- Function: wint_t fgetwc (FILE *stream)

This function reads the next wide character from the stream stream and returns its value. If an end-of-file condition or read error occurs, WEOF is returned instead.

-- Function: int getc (FILE *stream)

This is just like fgetc, except that it is permissible (and typical) for it to be implemented as a macro that evaluates the stream argument more than once. getc is often highly optimized, so it is usually the best function to use to read a single character.

-- Function: wint_t getwc (FILE *stream)

This is just like fgetwc, except that it is permissible for it to be implemented as a macro that evaluates the stream argument more than once. getwc can be highly optimized, so it is usually the best function to use to read a single wide character.

-- Function: int getchar (void)

The getchar function is equivalent to getc with stdin as the value of the stream argument.

-- Function: wint_t getwchar (void)

The getwchar function is equivalent to getwc with stdin as the value of the stream argument.

Here is an example of a function that does input using fgetc. It would work just as well using getc instead, or using getchar () instead of fgetc (stdin). The code would also work the same for the wide character stream functions.

     int
     y_or_n_p (const char *question)
     {
       fputs (question, stdout);
       while (1)
         {
           int c, answer;
           /* Write a space to separate answer from question. */
           fputc (' ', stdout);
           /* Read the first character of the line.
              This should be the answer character, but might not be. */
           c = tolower (fgetc (stdin));
           answer = c;
           /* Discard rest of input line. */
           while (c != '\n' && c != EOF)
             c = fgetc (stdin);
           /* Obey the answer if it was valid. */
           if (answer == 'y')
             return 1;
           if (answer == 'n')
             return 0;
           /* Answer was invalid: ask for valid answer. */
           fputs ("Please answer y or n:", stdout);
         }
     }

Character Set Handling 
Next:  Locales , Previous:  String and Array Utilities , Up:  Top 




Character Set Handling

Character sets used in the early days of computing had only six, seven, or eight bits for each character: there was never a case where more than eight bits (one byte) were used to represent a single character. The limitations of this approach became more apparent as more people grappled with non-Roman character sets, where not all the characters that make up a language's character set can be represented by 2^8 choices. This chapter shows the functionality that was added to the C library to support multiple character sets.

·  Extended Char Intro : Introduction to Extended Characters.
·  Charset Function Overview : Overview about Character Handling Functions.
·  Restartable multibyte conversion : Restartable multibyte conversion Functions.
·  Non-reentrant Conversion : Non-reentrant Conversion Function.

Charset Function Overview 
Next:  Restartable multibyte conversion , Previous:  Extended Char Intro , Up:  Character Set Handling 




Overview about Character Handling Functions

A Unix C library contains three different sets of functions in two families to handle character set conversion. One of the function families (the most commonly used) is specified in the ISO C90 standard and, therefore, is portable even beyond the Unix world. Unfortunately this family is the least useful one. These functions should be avoided whenever possible, especially when developing libraries (as opposed to applications). 

The second family of functions got introduced in the early Unix standards (XPG2) and is still part of the latest and greatest Unix standard: Unix 98. It is also the most powerful and useful set of functions. But we will start with the functions defined in Amendment 1 to ISO C90.

Checking for Errors 
Next:  Error Codes , Up:  Error Reporting 




Checking for Errors

Most library functions return a special value to indicate that they have failed. The special value is typically -1, a null pointer, or a constant such as EOF that is defined for that purpose. But this return value tells you only that an error has occurred. To find out what kind of error it was, you need to look at the error code stored in the variable errno. This variable is declared in the header file errno.h.
-- Variable: volatile int errno

The variable errno contains the system error number. You can change the value of errno. 

Since errno is declared volatile, it might be changed asynchronously by a signal handler; see  Defining Handlers . However, a properly written signal handler saves and restores the value of errno, so you generally do not need to worry about this possibility except when writing signal handlers. 

The initial value of errno at program startup is zero. Many library functions are guaranteed to set it to certain nonzero values when they encounter certain kinds of errors. These error conditions are listed for each function. These functions do not change errno when they succeed; thus, the value of errno after a successful call is not necessarily zero, and you should not use errno to determine whether a call failed. The proper way to do that is documented for each function. If the call failed, you can examine errno. 

Many library functions can set errno to a nonzero value as a result of calling other library functions which might fail. You should assume that any library function might alter errno when the function returns an error. 

Portability Note: ISO C specifies errno as a "modifiable lvalue" rather than as a variable, permitting it to be implemented as a macro. For example, its expansion might involve a function call, like *_errno (). In fact, that is what happens on this system. 

There are a few library functions, like sqrt and atan, that return a perfectly legitimate value in case of an error, but also set errno. For these functions, if you want to check to see whether an error occurred, the recommended method is to set errno to zero before calling the function, and then check its value afterward.

All the error codes have symbolic names; they are macros defined in errno.h. The names start with `E' and an upper-case letter or digit; you should consider names of this form to be reserved names. See  Reserved Names . 

The error code values are all positive integers and are all distinct, with one exception: EWOULDBLOCK and EAGAIN are the same. Since the values are distinct, you can use them as labels in a switch statement; just don't use both EWOULDBLOCK and EAGAIN. Your program should not make any other assumptions about the specific values of these symbolic constants. 

The value of errno doesn't necessarily have to correspond to any of these macros, since some library functions might return other error codes of their own for other situations. The only values that are guaranteed to be meaningful for a particular library function are the ones that this manual lists for that function. 

On non-GNU systems, almost any system call can return EFAULT if it is given an invalid pointer as an argument. Since this could only happen as a result of a bug in your program, and since it will not happen in this system, we have saved space by not mentioning EFAULT in the descriptions of individual functions. 

Choosing Locale 
Next:  Locale Categories , Previous:  Effects of Locale , Up:  Locales 




Choosing a Locale

The simplest way for the user to choose a locale is to set the environment variable LANG. This specifies a single locale to use for all purposes. For example, a user could specify a hypothetical locale named `espana-castellano' to use the standard conventions of most of Spain. 

The set of locales supported depends on the operating system you are using, and so do their names. We can't make any promises about what locales will exist, except for one standard locale called `C' or `POSIX'. Later we will describe how to construct locales. 

A user also has the option of specifying different locales for different purposes--in effect, choosing a mixture of multiple locales. 

For example, the user might specify the locale `espana-castellano' for most purposes, but specify the locale `usa-english' for currency formatting. This might make sense if the user is a Spanish-speaking American, working in Spanish, but representing monetary amounts in US dollars. 

Note that both locales `espana-castellano' and `usa-english', like all locales, would include conventions for all of the purposes to which locales apply. However, the user can choose to use each locale for a particular subset of those purposes.

Classification of Characters
Next:  Case Conversion , Up:  Character Handling 




Classification of Characters

This section explains the library functions for classifying characters. For example, isalpha is the function to test for an alphabetic character. It takes one argument, the character to test, and returns a nonzero integer if the character is alphabetic, and zero otherwise. You would use it like this:

     if (isalpha (c))
       printf ("The character `%c' is alphabetic.\n", c);

Each of the functions in this section tests for membership in a particular class of characters; each has a name starting with `is'. Each of them takes one argument, which is a character to test, and returns an int which is treated as a boolean value. The character argument is passed as an int, and it may be the constant value EOF instead of a real character. 

The attributes of any given character can vary between locales. See  Locales , for more information on locales. 

These functions are declared in the header file ctype.h.

-- Function: int islower (int c)

Returns true if c is a lower-case letter. The letter need not be from the Latin alphabet, any alphabet representable is valid.

-- Function: int isupper (int c)

Returns true if c is an upper-case letter. The letter need not be from the Latin alphabet, any alphabet representable is valid.

-- Function: int isalpha (int c)

Returns true if c is an alphabetic character (a letter). If islower or isupper is true of a character, then isalpha is also true. 

In some locales, there may be additional characters for which isalpha is true--letters which are neither upper case nor lower case. But in the standard "C" locale, there are no such additional characters.

-- Function: int isdigit (int c)

Returns true if c is a decimal digit (`0' through `9').

-- Function: int isalnum (int c)

Returns true if c is an alphanumeric character (a letter or number); in other words, if either isalpha or isdigit is true of a character, then isalnum is also true.

-- Function: int isxdigit (int c)

Returns true if c is a hexadecimal digit. Hexadecimal digits include the normal decimal digits `0' through `9' and the letters `A' through `F' and `a' through `f'.

-- Function: int ispunct (int c)

Returns true if c is a punctuation character. This means any printing character that is not alphanumeric or a space character.

-- Function: int isspace (int c)

Returns true if c is a whitespace character. In the standard "C" locale, isspace returns true for only the standard whitespace characters:

' '
space 
'\f'
formfeed 
'\n'
newline 
'\r'
carriage return 
'\t'
horizontal tab 
'
vertical tab

-- Function: int isgraph (int c)

Returns true if c is a graphic character; that is, a character that has a glyph associated with it. The whitespace characters are not considered graphic.

-- Function: int isprint (int c)

Returns true if c is a printing character. Printing characters include all the graphic characters, plus the space (` ') character.

-- Function: int iscntrl (int c)

Returns true if c is a control character (that is, a character that is not a printing character).

Classification of Wide Characters 
Next:  Using Wide Char Classes , Previous:  Case Conversion , Up:  Character Handling 




Character class determination for wide characters

Amendment 1 to ISO C90 defines functions to classify wide characters. Although the original ISO C90 standard already defined the type wchar_t, no functions operating on them were defined. 

The general design of the classification functions for wide characters is more general. It allows extensions to the set of available classifications, beyond those which are always available.  These extensions are not used by this compiler

The character class functions are normally implemented with bitsets, with a bitset per character. For a given character, the appropriate bitset is read from a table and a test is performed as to whether a certain bit is set. Which bit is tested for is determined by the class. 

For the wide character classification functions this is made visible. There is a type classification type defined, a function to retrieve this value for a given class, and a function to test whether a given character is in this class, using the classification value. On top of this the normal character classification functions as used for char objects can be defined.

-- Data type: wctype_t

The wctype_t can hold a value which represents a character class. The only defined way to generate such a value is by using the wctype function. 

This type is defined in wctype.h.

-- Function: wctype_t wctype (const char *property)

The wctype returns a value representing a class of wide characters which is identified by the string property. Beside some standard properties each locale can define its own ones. In case no property with the given name is known for the current locale selected for the LC_CTYPE category, the function returns zero. 

The properties known in every locale are: 

 
	"alnum" 	"alpha" 	"cntrl" 	"digit"	   
	"graph" 	"lower" 	"print" 	"punct"	   
	"space" 	"upper" 	"xdigit"	 

This function is declared in wctype.h.

To test the membership of a character to one of the non-standard classes the ISO C standard defines a completely new function.

-- Function: int iswctype (wint_t wc, wctype_t desc)

This function returns a nonzero value if wc is in the character class specified by desc. desc must previously be returned by a successful call to wctype. 

This function is declared in wctype.h.

To make it easier to use the commonly-used classification functions, they are defined in the C library. There is no need to use wctype if the property string is one of the known character classes. In some situations it is desirable to construct the property strings, and then it is important that wctype can also handle the standard classes.

-- Function: int iswalnum (wint_t wc)

This function returns a nonzero value if wc is an alphanumeric character (a letter or number); in other words, if either iswalpha or iswdigit is true of a character, then iswalnum is also true. 

This function can be implemented using 

          iswctype (wc, wctype ("alnum"))
     
It is declared in wctype.h.

-- Function: int iswalpha (wint_t wc)

Returns true if wc is an alphabetic character (a letter). If iswlower or iswupper is true of a character, then iswalpha is also true. 

In some locales, there may be additional characters for which iswalpha is true--letters which are neither upper case nor lower case. But in the standard "C" locale, there are no such additional characters. 

This function can be implemented using 

          iswctype (wc, wctype ("alpha"))
     
It is declared in wctype.h.

-- Function: int iswcntrl (wint_t wc)

Returns true if wc is a control character (that is, a character that is not a printing character). 

This function can be implemented using 

          iswctype (wc, wctype ("cntrl"))
     
It is declared in wctype.h.

-- Function: int iswdigit (wint_t wc)

Returns true if wc is a digit (e.g., `0' through `9'). Please note that this function does not only return a nonzero value for decimal digits, but for all kinds of digits. A consequence is that code like the following will not work unconditionally for wide characters: 

          n = 0;
          while (iswdigit (*wc))
            {
              n *= 10;
              n += *wc++ - L'0';
            }
     
This function can be implemented using 

          iswctype (wc, wctype ("digit"))
     
It is declared in wctype.h.

-- Function: int iswgraph (wint_t wc)

Returns true if wc is a graphic character; that is, a character that has a glyph associated with it. The whitespace characters are not considered graphic. 

This function can be implemented using 

          iswctype (wc, wctype ("graph"))
     
It is declared in wctype.h.

-- Function: int iswlower (wint_t wc)

Returns true if wc is a lower-case letter. The letter need not be from the Latin alphabet, any alphabet representable is valid. 

This function can be implemented using 

          iswctype (wc, wctype ("lower"))
     
It is declared in wctype.h.

-- Function: int iswprint (wint_t wc)

Returns true if wc is a printing character. Printing characters include all the graphic characters, plus the space (` ') character. 

This function can be implemented using 

          iswctype (wc, wctype ("print"))
     
It is declared in wctype.h.

-- Function: int iswpunct (wint_t wc)

Returns true if wc is a punctuation character. This means any printing character that is not alphanumeric or a space character. 

This function can be implemented using 

          iswctype (wc, wctype ("punct"))
     
It is declared in wctype.h.

-- Function: int iswspace (wint_t wc)

Returns true if wc is a whitespace character. In the standard "C" locale, iswspace returns true for only the standard whitespace characters:

L' '
space 
L'\f'
formfeed 
L'\n'
newline 
L'\r'
carriage return 
L'\t'
horizontal tab 
L'
vertical tab

This function can be implemented using 

          iswctype (wc, wctype ("space"))
     
It is declared in wctype.h.

-- Function: int iswupper (wint_t wc)

Returns true if wc is an upper-case letter. The letter need not be from the Latin alphabet, any alphabet representable is valid. 

This function can be implemented using 

          iswctype (wc, wctype ("upper"))
     
It is declared in wctype.h.

-- Function: int iswxdigit (wint_t wc)

Returns true if wc is a hexadecimal digit. Hexadecimal digits include the normal decimal digits `0' through `9' and the letters `A' through `F' and `a' through `f'. 

This function can be implemented using 

          iswctype (wc, wctype ("xdigit"))
     
It is declared in wctype.h.

Cleanups on Exit 
Next:  Aborting a Program , Previous:  Exit Status , Up:  Program Termination 




Cleanups on Exit

Your program can arrange to run its own cleanup functions if normal termination happens. If you are writing a library for use in various application programs, then it is unreliable to insist that all applications call the library's cleanup functions explicitly before exiting. It is much more robust to make the cleanup invisible to the application, by setting up a cleanup function in the library itself using atexit .

-- Function: int atexit (void (*function) (void))

The atexit function registers the function function to be called at normal program termination. The function is called with no arguments. 

The return value from atexit is zero on success and nonzero if the function cannot be registered.

Here's a trivial program that illustrates the use of exit and atexit:

     #include <stdio.h>
     #include <stdlib.h>
     
     void
     bye (void)
     {
       puts ("Goodbye, cruel world....");
     }
     
     int
     main (void)
     {
       atexit (bye);
       exit (EXIT_SUCCESS);
     }

When this program is executed, it just prints the message and exits.

Closing Streams 
Next:  Streams and Threads , Previous:  Opening Streams , Up:  I/O on Streams 




Closing Streams

When a stream is closed with fclose, the connection between the stream and the file is canceled. After you have closed a stream, you cannot perform any additional operations on it.

-- Function: int fclose (FILE *stream)

This function causes stream to be closed and the connection to the corresponding file to be broken. Any buffered output is written and any buffered input is discarded. The fclose function returns a value of 0 if the file was closed successfully, and EOF if an error was detected. 

It is important to check for errors when you call fclose to close an output stream, because real, everyday errors can be detected at this time. For example, when fclose writes the remaining buffered output, it might get an error because the disk is full. Even if you know the buffer is empty, errors can still occur when closing a file if you are using NFS. 

The function fclose is declared in stdio.h.

To close all streams currently available the C Library provides another function.

-- Function: int fcloseall (void)

This function causes all open streams of the process to be closed and the connection to corresponding files to be broken. All buffered data is written and any buffered input is discarded. The fcloseall function returns a value of 0 if all the files were closed successfully, and EOF if an error was detected. 

This function should be used only in special situations, e.g., when an error occurred and the program must be aborted. Normally each single stream should be closed separately so that problems with individual streams can be identified. It is also problematic since the standard streams (see  Standard Streams ) will also be closed. 

The function fcloseall is declared in stdio.h.

If the main function to your program returns, or if you call the exit function (see  Normal Termination ), all open streams are automatically closed properly. If your program terminates in any other manner, such as by calling the abort function (see  Aborting a Program ) or from a fatal signal (see  Signal Handling ), open streams might not be closed properly. Buffered output might not be flushed and files may be incomplete. For more information on buffering of streams, see  Stream Buffering .

Collation Functions 
Next:  Search Functions , Previous:  String/Array Comparison , Up:  String and Array Utilities 




Collation Functions

In some locales, the conventions for lexicographic ordering differ from the strict numeric ordering of character codes. For example, in Spanish most glyphs with diacritical marks such as accents are not considered distinct letters for the purposes of collation. On the other hand, the two-character sequence `ll' is treated as a single letter that is collated immediately after `l'. 

You can use the functions strcoll and strxfrm (declared in the headers file string.h) and wcscoll and wcsxfrm (declared in the headers file wchar) to compare strings using a collation ordering appropriate for the current locale. The locale used by these functions in particular can be specified by setting the locale for the LC_COLLATE category; see  Locales . In the standard C locale, the collation sequence for strcoll is the same as that for strcmp. Similarly, wcscoll and wcscmp are the same in this situation. 

Effectively, the way these functions work is by applying a mapping to transform the characters in a string to a byte sequence that represents the string's position in the collating sequence of the current locale. Comparing two such byte sequences in a simple fashion is equivalent to comparing the strings with the locale's collating sequence. 

The functions strcoll and wcscoll perform this translation implicitly, in order to do one comparison. By contrast, strxfrm and wcsxfrm perform the mapping explicitly. If you are making multiple comparisons using the same string or set of strings, it is likely to be more efficient to use strxfrm or wcsxfrm to transform all the strings just once, and subsequently compare the transformed strings with strcmp or wcscmp.

-- Function: int strcoll (const char *s1, const char *s2)

The strcoll function is similar to strcmp but uses the collating sequence of the current locale for collation (the LC_COLLATE locale).

-- Function: int wcscoll (const wchar_t *ws1, const wchar_t *ws2)

The wcscoll function is similar to wcscmp but uses the collating sequence of the current locale for collation (the LC_COLLATE locale).

Here is an example of sorting an array of strings, using strcoll to compare them. The actual sort algorithm is not written here; it comes from qsort (see  Array Sort Function ). The job of the code shown here is to say how to compare the strings while sorting them. (Later on in this section, we will show a way to do this more efficiently using strxfrm.)

     /* This is the comparison function used with qsort. */
     
     int
     compare_elements (char **p1, char **p2)
     {
       return strcoll (*p1, *p2);
     }
     
     /* This is the entry point---the function to sort
        strings using the locale's collating sequence. */
     
     void
     sort_strings (char **array, int nstrings)
     {
       /* Sort temp_array by comparing the strings. */
       qsort (array, nstrings,
              sizeof (char *), compare_elements);
     }

-- Function: size_t strxfrm (char *restrict to, const char *restrict from, size_t size)

The function strxfrm transforms the string from using the collation transformation determined by the locale currently selected for collation, and stores the transformed string in the array to. Up to size characters (including a terminating null character) are stored. 

The behavior is undefined if the strings to and from overlap; see  Copying and Concatenation . 

The return value is the length of the entire transformed string. This value is not affected by the value of size, but if it is greater or equal than size, it means that the transformed string did not entirely fit in the array to. In this case, only as much of the string as actually fits was stored. To get the whole transformed string, call strxfrm again with a bigger output array. 

The transformed string may be longer than the original string, and it may also be shorter. 

If size is zero, no characters are stored in to. In this case, strxfrm simply returns the number of characters that would be the length of the transformed string. This is useful for determining what size the allocated array should be. It does not matter what to is if size is zero; to may even be a null pointer.

-- Function: size_t wcsxfrm (wchar_t *restrict wto, const wchar_t *wfrom, size_t size)

The function wcsxfrm transforms wide character string wfrom using the collation transformation determined by the locale currently selected for collation, and stores the transformed string in the array wto. Up to size wide characters (including a terminating null character) are stored. 

The behavior is undefined if the strings wto and wfrom overlap; see  Copying and Concatenation . 

The return value is the length of the entire transformed wide character string. This value is not affected by the value of size, but if it is greater or equal than size, it means that the transformed wide character string did not entirely fit in the array wto. In this case, only as much of the wide character string as actually fits was stored. To get the whole transformed wide character string, call wcsxfrm again with a bigger output array. 

The transformed wide character string may be longer than the original wide character string, and it may also be shorter. 

If size is zero, no characters are stored in to. In this case, wcsxfrm simply returns the number of wide characters that would be the length of the transformed wide character string. This is useful for determining what size the allocated array should be (remember to multiply with sizeof (wchar_t)). It does not matter what wto is if size is zero; wto may even be a null pointer.

Here is an example of how you can use strxfrm when you plan to do many comparisons. It does the same thing as the previous example, but much faster, because it has to transform each string only once, no matter how many times it is compared with other strings. Even the time needed to allocate and free storage is much less than the time we save, when there are many strings.

     struct sorter { char *input; char *transformed; };
     
     /* This is the comparison function used with qsort
        to sort an array of struct sorter. */
     
     int
     compare_elements (struct sorter *p1, struct sorter *p2)
     {
       return strcmp (p1->transformed, p2->transformed);
     }
     
     /* This is the entry point---the function to sort
        strings using the locale's collating sequence. */
     
     void
     sort_strings_fast (char **array, int nstrings)
     {
       struct sorter temp_array[nstrings];
       int i;
     
       /* Set up temp_array.  Each element contains
          one input string and its transformed string. */
       for (i = 0; i < nstrings; i++)
         {
           size_t length = strlen (array[i]) * 2;
           char *transformed;
           size_t transformed_length;
     
           temp_array[i].input = array[i];
     
           /* First try a buffer perhaps big enough.  */
           transformed = (char *) xmalloc (length);
     
           /* Transform array[i].  */
           transformed_length = strxfrm (transformed, array[i], length);
     
           /* If the buffer was not large enough, resize it
              and try again.  */
           if (transformed_length >= length)
             {
               /* Allocate the needed space. +1 for terminating
                  NUL character.  */
               transformed = (char *) xrealloc (transformed,
                                                transformed_length + 1);
     
               /* The return value is not interesting because we know
                  how long the transformed string is.  */
               (void) strxfrm (transformed, array[i],
                               transformed_length + 1);
             }
     
           temp_array[i].transformed = transformed;
         }
     
       /* Sort temp_array by comparing transformed strings. */
       qsort (temp_array, sizeof (struct sorter),
              nstrings, compare_elements);
     
       /* Put the elements back in the permanent array
          in their sorted order. */
       for (i = 0; i < nstrings; i++)
         array[i] = temp_array[i].input;
     
       /* Free the strings we allocated. */
       for (i = 0; i < nstrings; i++)
         free (temp_array[i].transformed);
     }

The interesting part of this code for the wide character version would look like this:

     void
     sort_strings_fast (wchar_t **array, int nstrings)
     {
       ...
           /* Transform array[i].  */
           transformed_length = wcsxfrm (transformed, array[i], length);
     
           /* If the buffer was not large enough, resize it
              and try again.  */
           if (transformed_length >= length)
             {
               /* Allocate the needed space. +1 for terminating
                  NUL character.  */
               transformed = (wchar_t *) xrealloc (transformed,
                                                   (transformed_length + 1)
                                                   * sizeof (wchar_t));
     
               /* The return value is not interesting because we know
                  how long the transformed string is.  */
               (void) wcsxfrm (transformed, array[i],
                               transformed_length + 1);
             }
       ...

Note the additional multiplication with sizeof (wchar_t) in the realloc call. 

Compatibility Note: The string collation functions are a new feature of ISO C90. Older C dialects have no equivalent feature. The wide character versions were introduced in Amendment 1 to ISO C90.

Comparison Functions 
Next:  Array Search Function , Up:  Searching and Sorting 




Defining the Comparison Function

In order to use the sorted array library functions, you have to describe how to compare the elements of the array. 

To do this, you supply a comparison function to compare two elements of the array. The library will call this function, passing as arguments pointers to two array elements to be compared. Your comparison function should return a value the way strcmp (see  String/Array Comparison ) does: negative if the first argument is "less" than the second, zero if they are "equal", and positive if the first argument is "greater". 

Here is an example of a comparison function which works with an array of numbers of type double:

     int
     compare_doubles (const void *a, const void *b)
     {
       const double *da = (const double *) a;
       const double *db = (const double *) b;
     
       return (*da > *db) - (*da < *db);
     }


Complex Numbers 
Next:  Operations on Complex , Previous:  Arithmetic Functions , Up:  Arithmetic 




Complex Numbers

ISO C99 introduces support for complex numbers in C. This is done with a new type qualifier, complex. It is a keyword if and only if complex.h has been included. There are three complex types, corresponding to the three real types: float complex, double complex, and long double complex. 

To construct complex numbers you need a way to indicate the imaginary part of a number. There is no standard notation for an imaginary floating point constant. Instead, complex.h defines two macros that can be used to create complex numbers.

-- Macro: const float complex _Complex_I

This macro is a representation of the complex number "0+1i". Multiplying a real floating-point value by _Complex_I gives a complex number whose value is purely imaginary. You can use this to construct complex constants: 

          3.0 + 4.0i = 3.0 + 4.0 * _Complex_I
     
Note that _Complex_I * _Complex_I has the value -1, but the type of that value is complex.

_Complex_I is a bit of a mouthful. complex.h also defines a shorter name for the same constant.

-- Macro: const float complex I

This macro has exactly the same value as _Complex_I. Most of the time it is preferable. However, it causes problems if you want to use the identifier I for something else. You can safely write 

          #include <complex.h>
          #undef I
     
if you need I for your own purposes. (In that case we recommend you also define some other short name for _Complex_I, such as J.)

Concepts of Signals 
Next:  Standard Signals , Up:  Signal Handling 




Basic Concepts of Signals

This section explains basic concepts of how signals are generated, what happens after a signal is delivered, and how programs can handle signals.

·  Kinds of Signals : Some examples of what can cause a signal.
·  Signal Generation : Concepts of why and how signals occur.

Consistency Checking 
Next:  Variadic Functions , Up:  Language Features 




Explicitly Checking Internal Consistency

When you're writing a program, it's often a good idea to put in checks at strategic places for "impossible" errors or violations of basic assumptions. These kinds of checks are helpful in debugging problems with the interfaces between different parts of the program, for example. 

The assert macro, defined in the header file assert.h, provides a convenient way to abort the program while printing a message about where in the program the error was detected. 

Once you think your program is debugged, you can disable the error checks performed by the assert macro by recompiling with the macro NDEBUG defined. This means you don't actually have to change the program source code to disable these checks. 

But disabling these consistency checks is undesirable unless they make the program significantly slower. All else being equal, more error checking is good no matter who is running the program. A wise user would rather have a program crash, visibly, than have it return nonsense without indicating anything might be wrong.

-- Macro: void assert (int expression)

Verify the programmer's belief that expression is nonzero at this point in the program. 

If NDEBUG is not defined, assert tests the value of expression. If it is false (zero), assert aborts the program (see  Aborting a Program ) after printing a message of the form: 

          Assertion failed file(function:linenum) : expression.
    
on the standard error stream stderr (see  Standard Streams ). The filename and line number are taken from the C preprocessor macros __FILE__ and __LINE__ and specify where the call to assert was made. When using the C compiler, the name of the function which calls assert is taken from the built-in variable __func__.  When C99 mode is not enabled, the function name and following colon are not present.

If the preprocessor macro NDEBUG is defined before assert.h is included, the assert macro is defined to do absolutely nothing. 

Warning: Even the argument expression expression is not evaluated if NDEBUG is in effect. So never use assert with arguments that involve side effects. For example, assert (++i > 0); is a bad idea, because i will not be incremented if NDEBUG is defined.

Usage note: The assert facility is designed for detecting internal inconsistency; it is not suitable for reporting invalid input or improper usage by the user of the program. 

The information in the diagnostic messages printed by the assert macro is intended to help you, the programmer, track down the cause of a bug, but is not really useful for telling a user of your program why his or her input was invalid or why a command could not be carried out. What's more, your program should not abort when given invalid input, as assert would do--it should exit with nonzero status (see  Exit Status ) after printing its error messages, or perhaps read another command or move on to the next input file. 

See  Error Messages , for information on printing error messages for problems that do not represent bugs in the program.

Control Functionsl 
Next:  Arithmetic Functions , Previous:  Rounding , Up:  Arithmetic 




Floating-Point Control Functions

IEEE 754 floating-point implementations allow the programmer to decide whether traps will occur for each of the exceptions, by setting bits in the control word. In C, traps result in the program receiving the SIGFPE signal; see  Signal Handling . 

Note: IEEE 754 says that trap handlers are given details of the exceptional situation, and can set the result value. C signals do not provide any mechanism to pass this information back and forth. Trapping exceptions in C is therefore not very useful. 

It is sometimes necessary to save the state of the floating-point unit while you perform some calculation. The library provides functions which save and restore the exception flags, the set of exceptions that generate traps, and the rounding mode. This information is known as the floating-point environment. 

The functions to save and restore the floating-point environment all use a variable of type fenv_t to store information. This type is defined in fenv.h. Its size and contents are implementation-defined. You should not attempt to manipulate a variable of this type directly. 

To save the state of the FPU, use one of these functions:

-- Function: int fegetenv (fenv_t *envp)

Store the floating-point environment in the variable pointed to by envp. 

The function returns zero in case the operation was successful, a non-zero value otherwise.

-- Function: int feholdexcept (fenv_t *envp)

Store the current floating-point environment in the object pointed to by envp. Then clear all exception flags, and set the FPU to trap no exceptions. Not all FPUs support trapping no exceptions; if feholdexcept cannot set this mode, it returns nonzero value. If it succeeds, it returns zero.

The functions which restore the floating-point environment can take these kinds of arguments:

· Pointers to fenv_t objects, which were initialized previously by a call to fegetenv or feholdexcept.
· The special macro FE_DFL_ENV which represents the floating-point environment as it was available at program start.
· Implementation defined macros with names starting with FE_ and having type fenv_t *. 

Some platforms might define other predefined environments.

To set the floating-point environment, you can use either of these functions:

-- Function: int fesetenv (const fenv_t *envp)

Set the floating-point environment to that described by envp. 

The function returns zero in case the operation was successful, a non-zero value otherwise.

-- Function: int feupdateenv (const fenv_t *envp)

Like fesetenv, this function sets the floating-point environment to that described by envp. However, if any exceptions were flagged in the status word before feupdateenv was called, they remain flagged after the call. In other words, after feupdateenv is called, the status word is the bitwise OR of the previous status word and the one saved in envp. 

The function returns zero in case the operation was successful, a non-zero value otherwise.

-- Function: void feclearexcept (int exceptflags)

This function clears specific  flags related to a floating point exception.

-- Function: void feraiseexcept (int exceptflags)

This function causes the floating point environment to raise the exceptions corresponding to the flags.

-- Function: void fetestexcept (int exceptflags)

This function tests the floating point environment to see if the exceptions corresponding to the flags have been raised.

The function returns a bit mask including flags for the exceptions that have been raised.

-- Function: void fegetexceptflag (fexcept_t *flagp, int exceptflags)

This function gets the state of the exceptions indicated by exceptflags, and stores it in flagp.

-- Function: void fesetexceptflag (fexcept_t *flagp, int exceptflags)

This function sets the internal state of the exception flags in flagp as masked by exceptflags.  It does not change the actual state of the floating point unit.

Controlling Buffering 
Previous:  Flushing Buffers , Up:  Stream Buffering 




Controlling Which Kind of Buffering

After opening a stream (but before any other operations have been performed on it), you can explicitly specify what kind of buffering you want it to have using the setvbuf function. The facilities listed in this section are declared in the header file stdio.h.

-- Function: int setvbuf (FILE *stream, char *buf, int mode, size_t size)

This function is used to specify that the stream stream should have the buffering mode mode, which can be either _IOFBF (for full buffering), _IOLBF (for line buffering), or _IONBF (for unbuffered input/output). 

If you specify a null pointer as the buf argument, then setvbuf allocates a buffer itself using malloc. This buffer will be freed when you close the stream. 

Otherwise, buf should be a character array that can hold at least size characters. You should not free the space for this array as long as the stream remains open and this array remains its buffer. You should usually either allocate it statically, or malloc (see  Unconstrained Allocation ) the buffer. Using an automatic array is not a good idea unless you close the file before exiting the block that declares the array. 

While the array remains a stream buffer, the stream I/O functions will use the buffer for their internal purposes. You shouldn't try to access the values in the array directly while the stream is using it for buffering. 

The setvbuf function returns zero on success, or a nonzero value if the value of mode is not valid or if the request could not be honored.

-- Macro: int _IOFBF

The value of this macro is an integer constant expression that can be used as the mode argument to the setvbuf function to specify that the stream should be fully buffered.

-- Macro: int _IOLBF

The value of this macro is an integer constant expression that can be used as the mode argument to the setvbuf function to specify that the stream should be line buffered.

-- Macro: int _IONBF

The value of this macro is an integer constant expression that can be used as the mode argument to the setvbuf function to specify that the stream should be unbuffered.

-- Macro: int BUFSIZ

The value of this macro is an integer constant expression that is good to use for the size argument to setvbuf. This value is guaranteed to be at least 256. 

The value of BUFSIZ is chosen on each system so as to make stream I/O efficient. So it is a good idea to use BUFSIZ as the size for the buffer when you call setvbuf. 

Sometimes people also use BUFSIZ as the allocation size of buffers used for related purposes, such as strings used to receive a line of input with fgets (see  Character Input ). There is no particular reason to use BUFSIZ for this instead of any other integer, except that it might lead to doing I/O in chunks of an efficient size.

-- Function: void setbuf (FILE *stream, char *buf)

If buf is a null pointer, the effect of this function is equivalent to calling setvbuf with a mode argument of _IONBF. Otherwise, it is equivalent to calling setvbuf with buf, and a mode of _IOFBF and a size argument of BUFSIZ. 

The setbuf function is provided for compatibility with old code; use setvbuf in all new programs.

Converting a Character 
Next:  Converting Strings , Previous:  Keeping the state , Up:  Restartable multibyte conversion 




Converting Single Characters

The most fundamental of the conversion functions are those dealing with single characters. Please note that this does not always mean single bytes. But since there is very often a subset of the multibyte character set that consists of single byte sequences, there are functions to help with converting bytes. Frequently, ASCII is a subpart of the multibyte character set. In such a scenario, each ASCII character stands for itself, and all other characters have at least a first byte that is beyond the range 0 to 127.

-- Function: wint_t btowc (int c)

The btowc function ("byte to wide character") converts a valid single byte character c in the initial shift state into the wide character equivalent using the conversion rules from the currently selected locale of the LC_CTYPE category. 

If (unsigned char) c is no valid single byte multibyte character or if c is EOF, the function returns WEOF. 

Please note the restriction of c being tested for validity only in the initial shift state. No mbstate_t object is used from which the state information is taken, and the function also does not use any static state. 

The btowc function was introduced in Amendment 1 to ISO C90 and is declared in wchar.h.

Despite the limitation that the single byte value always is interpreted in the initial state this function is actually useful most of the time. Most characters are either entirely single-byte character sets or they are extension to ASCII. But then it is possible to write code like this (not that this specific example is very useful):

     wchar_t *
     itow (unsigned long int val)
     {
       static wchar_t buf[30];
       wchar_t *wcp = &buf[29];
       *wcp = L'\0';
       while (val != 0)
         {
           *--wcp = btowc ('0' + val % 10);
           val /= 10;
         }
       if (wcp == &buf[29])
         *--wcp = L'0';
       return wcp;
     }

Why is it necessary to use such a complicated implementation and not simply cast '0' + val % 10 to a wide character? The answer is that there is no guarantee that one can perform this kind of arithmetic on the character of the character set used for wchar_t representation. In other situations the bytes are not constant at compile time and so the compiler cannot do the work. In situations like this it is necessary btowc.

There also is a function for the conversion in the other direction.

-- Function: int wctob (wint_t c)

The wctob function ("wide character to byte") takes as the parameter a valid wide character. If the multibyte representation for this character in the initial state is exactly one byte long, the return value of this function is this character. Otherwise the return value is EOF. 

wctob was introduced in Amendment 1 to ISO C90 and is declared in wchar.h.

There are more general functions to convert single character from multibyte representation to wide characters and vice versa. These functions pose no limit on the length of the multibyte representation and they also do not require it to be in the initial state.

-- Function: size_t mbrtowc (wchar_t *restrict pwc, const char *restrict s, size_t n, mbstate_t *restrict ps)

The mbrtowc function ("multibyte restartable to wide character") converts the next multibyte character in the string pointed to by s into a wide character and stores it in the wide character string pointed to by pwc. The conversion is performed according to the locale currently selected for the LC_CTYPE category. If the conversion for the character set used in the locale requires a state, the multibyte string is interpreted in the state represented by the object pointed to by ps. If ps is a null pointer, a static, internal state variable used only by the mbrtowc function is used. 

If the next multibyte character corresponds to the NUL wide character, the return value of the function is 0 and the state object is afterwards in the initial state. If the next n or fewer bytes form a correct multibyte character, the return value is the number of bytes starting from s that form the multibyte character. The conversion state is updated according to the bytes consumed in the conversion. In both cases the wide character (either the L'\0' or the one found in the conversion) is stored in the string pointed to by pwc if pwc is not null. 

If the first n bytes of the multibyte string possibly form a valid multibyte character but there are more than n bytes needed to complete it, the return value of the function is (size_t) -2 and no value is stored. Please note that this can happen even if n has a value greater than or equal to MB_CUR_MAX since the input might contain redundant shift sequences. 

If the first n bytes of the multibyte string cannot possibly form a valid multibyte character, no value is stored, the global variable errno is set to the value EILSEQ, and the function returns (size_t) -1. The conversion state is afterwards undefined. 

mbrtowc was introduced in Amendment 1 to ISO C90 and is declared in wchar.h.

Use of mbrtowc is straightforward. A function that copies a multibyte string into a wide character string while at the same time converting all lowercase characters into uppercase could look like this (this is not the final version, just an example; it has no error checking, and sometimes leaks memory):

     wchar_t *
     mbstouwcs (const char *s)
     {
       size_t len = strlen (s);
       wchar_t *result = malloc ((len + 1) * sizeof (wchar_t));
       wchar_t *wcp = result;
       wchar_t tmp[1];
       mbstate_t state;
       size_t nbytes;
     
       memset (&state, '\0', sizeof (state));
       while ((nbytes = mbrtowc (tmp, s, len, &state)) > 0)
         {
           if (nbytes >= (size_t) -2)
             /* Invalid input string.  */
             return NULL;
           *result++ = towupper (tmp[0]);
           len -= nbytes;
           s += nbytes;
         }
       return result;
     }

The use of mbrtowc should be clear. A single wide character is stored in tmp[0], and the number of consumed bytes is stored in the variable nbytes. If the conversion is successful, the uppercase variant of the wide character is stored in the result array and the pointer to the input string and the number of available bytes is adjusted. 

The only non-obvious thing about mbrtowc might be the way memory is allocated for the result. The above code uses the fact that there can never be more wide characters in the converted results than there are bytes in the multibyte input string. This method yields a pessimistic guess about the size of the result, and if many wide character strings have to be constructed this way or if the strings are long, the extra memory required to be allocated because the input string contains multibyte characters might be significant. The allocated memory block can be resized to the correct size before returning it, but a better solution might be to allocate just the right amount of space for the result right away. Unfortunately there is no function to compute the length of the wide character string directly from the multibyte string. There is, however, a function that does part of the work.
-- Function: size_t mbrlen (const char *restrict s, size_t n, mbstate_t *ps)

The mbrlen function ("multibyte restartable length") computes the number of at most n bytes starting at s, which form the next valid and complete multibyte character. 

If the next multibyte character corresponds to the NUL wide character, the return value is 0. If the next n bytes form a valid multibyte character, the number of bytes belonging to this multibyte character byte sequence is returned. 

If the the first n bytes possibly form a valid multibyte character but the character is incomplete, the return value is (size_t) -2. Otherwise the multibyte character sequence is invalid and the return value is (size_t) -1. 

The multibyte sequence is interpreted in the state represented by the object pointed to by ps. If ps is a null pointer, a state object local to mbrlen is used. 

mbrlen was introduced in Amendment 1 to ISO C90 and is declared in wchar.h.

The attentive reader now will note that mbrlen can be implemented as

     mbrtowc (NULL, s, n, ps != NULL ? ps : &internal)

This is true and in fact is mentioned in the official specification. How can this function be used to determine the length of the wide character string created from a multibyte character string? It is not directly usable, but we can define a function mbslen using it:

     size_t
     mbslen (const char *s)
     {
       mbstate_t state;
       size_t result = 0;
       size_t nbytes;
       memset (&state, '\0', sizeof (state));
       while ((nbytes = mbrlen (s, MB_LEN_MAX, &state)) > 0)
         {
           if (nbytes >= (size_t) -2)
             /* Something is wrong.  */
             return (size_t) -1;
           s += nbytes;
           ++result;
         }
       return result;
     }

This function simply calls mbrlen for each multibyte character in the string and counts the number of function calls. Please note that we here use MB_LEN_MAX as the size argument in the mbrlen call. This is acceptable since a) this value is larger then the length of the longest multibyte character sequence and b) we know that the string s ends with a NUL byte, which cannot be part of any other multibyte character sequence but the one representing the NUL wide character. Therefore, the mbrlen function will never read invalid memory. 

Now that this function is available (just to make this clear, this function is not part of the C library) we can compute the number of wide character required to store the converted multibyte character string s using

     wcs_bytes = (mbslen (s) + 1) * sizeof (wchar_t);

Please note that the mbslen function is quite inefficient. The implementation of mbstouwcs with mbslen would have to perform the conversion of the multibyte character input string twice, and this conversion might be quite expensive. So it is necessary to think about the consequences of using the easier but imprecise method before doing the work twice.

-- Function: size_t wcrtomb (char *restrict s, wchar_t wc, mbstate_t *restrict ps)

The wcrtomb function ("wide character restartable to multibyte") converts a single wide character into a multibyte string corresponding to that wide character. 

If s is a null pointer, the function resets the state stored in the objects pointed to by ps (or the internal mbstate_t object) to the initial state. This can also be achieved by a call like this: 

          wcrtombs (temp_buf, L'\0', ps)
     
since, if s is a null pointer, wcrtomb performs as if it writes into an internal buffer, which is guaranteed to be large enough. 

If wc is the NUL wide character, wcrtomb emits, if necessary, a shift sequence to get the state ps into the initial state followed by a single NUL byte, which is stored in the string s. 

Otherwise a byte sequence (possibly including shift sequences) is written into the string s. This only happens if wc is a valid wide character (i.e., it has a multibyte representation in the character set selected by locale of the LC_CTYPE category). If wc is no valid wide character, nothing is stored in the strings s, errno is set to EILSEQ, the conversion state in ps is undefined and the return value is (size_t) -1. 

If no error occurred the function returns the number of bytes stored in the string s. This includes all bytes representing shift sequences. 

One word about the interface of the function: there is no parameter specifying the length of the array s. Instead the function assumes that there are at least MB_CUR_MAX bytes available since this is the maximum length of any byte sequence representing a single character. So the caller has to make sure that there is enough space available, otherwise buffer overruns can occur. 

wcrtomb was introduced in Amendment 1 to ISO C90 and is declared in wchar.h.

Using wcrtomb is as easy as using mbrtowc. The following example appends a wide character string to a multibyte character string. Again, the code is not really useful (or correct), it is simply here to demonstrate the use and some problems.

     char *
     mbscatwcs (char *s, size_t len, const wchar_t *ws)
     {
       mbstate_t state;
       /* Find the end of the existing string.  */
       char *wp = strchr (s, '\0');
       len -= wp - s;
       memset (&state, '\0', sizeof (state));
       do
         {
           size_t nbytes;
           if (len < MB_CUR_LEN)
             {
               /* We cannot guarantee that the next
                  character fits into the buffer, so
                  return an error.  */
               errno = E2BIG;
               return NULL;
             }
           nbytes = wcrtomb (wp, *ws, &state);
           if (nbytes == (size_t) -1)
             /* Error in the conversion.  */
             return NULL;
           len -= nbytes;
           wp += nbytes;
         }
       while (*ws++ != L'\0');
       return s;
     }

First the function has to find the end of the string currently in the array s. The strchr call does this very efficiently since a requirement for multibyte character representations is that the NUL byte is never used except to represent itself (and in this context, the end of the string). 

After initializing the state object the loop is entered where the first task is to make sure there is enough room in the array s. We abort if there are not at least MB_CUR_LEN bytes available. This is not always optimal but we have no other choice. We might have less than MB_CUR_LEN bytes available but the next multibyte character might also be only one byte long. At the time the wcrtomb call returns it is too late to decide whether the buffer was large enough. If this solution is unsuitable, there is a very slow but more accurate solution.

       ...
       if (len < MB_CUR_LEN)
         {
           mbstate_t temp_state;
           memcpy (&temp_state, &state, sizeof (state));
           if (wcrtomb (NULL, *ws, &temp_state) > len)
             {
               /* We cannot guarantee that the next
                  character fits into the buffer, so
                  return an error.  */
               errno = E2BIG;
               return NULL;
             }
         }
       ...

Here we perform the conversion that might overflow the buffer so that we are afterwards in the position to make an exact decision about the buffer size. Please note the NULL argument for the destination buffer in the new wcrtomb call; since we are not interested in the converted text at this point, this is a nice way to express this. The most unusual thing about this piece of code certainly is the duplication of the conversion state object, but if a change of the state is necessary to emit the next multibyte character, we want to have the same shift state change performed in the real conversion. Therefore, we have to preserve the initial shift state information. 

There are certainly many more and even better solutions to this problem. This example is only provided for educational purposes.

Converting Strings 
Next:  Multibyte Conversion Example , Previous:  Converting a Character , Up:  Restartable multibyte conversion 




Converting Multibyte and Wide Character Strings

The functions described in the previous section only convert a single character at a time. Most operations to be performed in real-world programs include strings and therefore the ISO C standard also defines conversions on entire strings. 

-- Function: size_t mbsrtowcs (wchar_t *restrict dst, const char **restrict src, size_t len, mbstate_t *restrict ps)

The mbsrtowcs function ("multibyte string restartable to wide character string") converts an NUL-terminated multibyte character string at *src into an equivalent wide character string, including the NUL wide character at the end. The conversion is started using the state information from the object pointed to by ps or from an internal object of mbsrtowcs if ps is a null pointer. Before returning, the state object is updated to match the state after the last converted character. The state is the initial state if the terminating NUL byte is reached and converted. 

If dst is not a null pointer, the result is stored in the array pointed to by dst; otherwise, the conversion result is not available since it is stored in an internal buffer. 

If len wide characters are stored in the array dst before reaching the end of the input string, the conversion stops and len is returned. If dst is a null pointer, len is never checked. 

Another reason for a premature return from the function call is if the input string contains an invalid multibyte sequence. In this case the global variable errno is set to EILSEQ and the function returns (size_t) -1.

In all other cases the function returns the number of wide characters converted during this call. If dst is not null, mbsrtowcs stores in the pointer pointed to by src either a null pointer (if the NUL byte in the input string was reached) or the address of the byte following the last converted multibyte character. 

mbsrtowcs was introduced in Amendment 1 to ISO C90 and is declared in wchar.h.

The definition of the mbsrtowcs function has one important limitation. The requirement that dst has to be a NUL-terminated string provides problems if one wants to convert buffers with text. A buffer is normally no collection of NUL-terminated strings but instead a continuous collection of lines, separated by newline characters. Now assume that a function to convert one line from a buffer is needed. Since the line is not NUL-terminated, the source pointer cannot directly point into the unmodified text buffer. This means, either one inserts the NUL byte at the appropriate place for the time of the mbsrtowcs function call (which is not doable for a read-only buffer or in a multi-threaded application) or one copies the line in an extra buffer where it can be terminated by a NUL byte. Note that it is not in general possible to limit the number of characters to convert by setting the parameter len to any specific value. Since it is not known how many bytes each multibyte character sequence is in length, one can only guess. 

There is still a problem with the method of NUL-terminating a line right after the newline character, which could lead to very strange results. As said in the description of the mbsrtowcs function above the conversion state is guaranteed to be in the initial shift state after processing the NUL byte at the end of the input string. But this NUL byte is not really part of the text (i.e., the conversion state after the newline in the original text could be something different than the initial shift state and therefore the first character of the next line is encoded using this state). But the state in question is never accessible to the user since the conversion stops after the NUL byte (which resets the state). Most stateful character sets in use today require that the shift state after a newline be the initial state-but this is not a strict guarantee. Therefore, simply NUL-terminating a piece of a running text is not always an adequate solution and, therefore, should never be used in generally used code. 

-- Function: size_t wcsrtombs (char *restrict dst, const wchar_t **restrict src, size_t len, mbstate_t *restrict ps)

The wcsrtombs function ("wide character string restartable to multibyte string") converts the NUL-terminated wide character string at *src into an equivalent multibyte character string and stores the result in the array pointed to by dst. The NUL wide character is also converted. The conversion starts in the state described in the object pointed to by ps or by a state object locally to wcsrtombs in case ps is a null pointer. If dst is a null pointer, the conversion is performed as usual but the result is not available. If all characters of the input string were successfully converted and if dst is not a null pointer, the pointer pointed to by src gets assigned a null pointer. 

If one of the wide characters in the input string has no valid multibyte character equivalent, the conversion stops early, sets the global variable errno to EILSEQ, and returns (size_t) -1. 

Another reason for a premature stop is if dst is not a null pointer and the next converted character would require more than len bytes in total to the array dst. In this case (and if dest is not a null pointer) the pointer pointed to by src is assigned a value pointing to the wide character right after the last one successfully converted. 

Except in the case of an encoding error the return value of the wcsrtombs function is the number of bytes in all the multibyte character sequences stored in dst. Before returning the state in the object pointed to by ps (or the internal object in case ps is a null pointer) is updated to reflect the state after the last conversion. The state is the initial shift state in case the terminating NUL wide character was converted. 

The wcsrtombs function was introduced in Amendment 1 to ISO C90 and is declared in wchar.h.

The restriction mentioned above for the mbsrtowcs function applies here also. There is no possibility of directly controlling the number of input characters. One has to place the NUL wide character at the correct place or control the consumed input indirectly via the available output array size (the len parameter).


Copying and Concatenation 
Next:  String/Array Comparison , Previous:  String Length , Up:  String and Array Utilities 




Copying and Concatenation

You can use the functions described in this section to copy the contents of strings and arrays, or to append the contents of one string to another. The `str' and `mem' functions are declared in the header file string.h while the `wstr' and `wmem' functions are declared in the file wchar.h. A helpful way to remember the ordering of the arguments to the functions in this section is that it corresponds to an assignment expression, with the destination array specified to the left of the source array. All of these functions return the address of the destination array. 

Most of these functions do not work properly if the source and destination arrays overlap. For example, if the beginning of the destination array overlaps the end of the source array, the original contents of that part of the source array may get overwritten before it is copied. Even worse, in the case of the string functions, the null character marking the end of the string may be lost, and the copy function might get stuck in a loop trashing all the memory allocated to your program. 

All functions that have problems copying between overlapping arrays are explicitly identified in this manual. In addition to functions in this section, there are a few others like sprintf (see  Formatted Output Functions ) and scanf (see  Formatted Input Functions ).

-- Function: void * memcpy (void *restrict to, const void *restrict from, size_t size)

The memcpy function copies size bytes from the object beginning at from into the object beginning at to. The behavior of this function is undefined if the two arrays to and from overlap; use memmove instead if overlapping is possible. 

The value returned by memcpy is the value of to. 

Here is an example of how you might use memcpy to copy the contents of an array: 

          struct foo *oldarray, *newarray;
          int arraysize;
          ...
          memcpy (new, old, arraysize * sizeof (struct foo));
     
-- Function: wchar_t * wmemcpy (wchar_t *restrict wto, const wchar_t *restruct wfrom, size_t size)

The wmemcpy function copies size wide characters from the object beginning at wfrom into the object beginning at wto. The behavior of this function is undefined if the two arrays wto and wfrom overlap; use wmemmove instead if overlapping is possible. 

The following is a possible implementation of wmemcpy but there are more optimizations possible. 

          wchar_t *
          wmemcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
                   size_t size)
          {
            return (wchar_t *) memcpy (wto, wfrom, size * sizeof (wchar_t));
          }
     
The value returned by wmemcpy is the value of wto. 

This function was introduced in Amendment 1 to ISO C90.

-- Function: void * memmove (void *to, const void *from, size_t size)

memmove copies the size bytes at from into the size bytes at to, even if those two blocks of space overlap. In the case of overlap, memmove is careful to copy the original values of the bytes in the block at from, including those bytes which also belong to the block at to. 

The value returned by memmove is the value of to.

-- Function: wchar_t * wmemmove (wchar *wto, const wchar_t *wfrom, size_t size)

wmemmove copies the size wide characters at wfrom into the size wide characters at wto, even if those two blocks of space overlap. In the case of overlap, memmove is careful to copy the original values of the wide characters in the block at wfrom, including those wide characters which also belong to the block at wto. 

The following is a possible implementation of wmemcpy but there are more optimizations possible. 

          wchar_t *
          wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
                    size_t size)
          {
            return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
          }
     
The value returned by wmemmove is the value of wto. 

This function is a GNU extension.

-- Function: void * memset (void *block, int c, size_t size)

This function copies the value of c (converted to an unsigned char) into each of the first size bytes of the object beginning at block. It returns the value of block.

-- Function: wchar_t * wmemset (wchar_t *block, wchar_t wc, size_t size)

This function copies the value of wc into each of the first size wide characters of the object beginning at block. It returns the value of block.

-- Function: char * strcpy (char *restrict to, const char *restrict from)

This copies characters from the string from (up to and including the terminating null character) into the string to. Like memcpy, this function has undefined results if the strings overlap. The return value is the value of to.

-- Function: wchar_t * wcscpy (wchar_t *restrict wto, const wchar_t *restrict wfrom)

This copies wide characters from the string wfrom (up to and including the terminating null wide character) into the string wto. Like wmemcpy, this function has undefined results if the strings overlap. The return value is the value of wto.

-- Function: char * strncpy (char *restrict to, const char *restrict from, size_t size)

This function is similar to strcpy but always copies exactly size characters into to. 

If the length of from is more than size, then strncpy copies just the first size characters. Note that in this case there is no null terminator written into to. 

If the length of from is less than size, then strncpy copies all of from, followed by enough null characters to add up to size characters in all. This behavior is rarely useful, but it is specified by the ISO C standard. 

The behavior of strncpy is undefined if the strings overlap. 

Using strncpy as opposed to strcpy is a way to avoid bugs relating to writing past the end of the allocated space for to. However, it can also make your program much slower in one common case: copying a string which is probably small into a potentially large buffer. In this case, size may be large, and when it is, strncpy will waste a considerable amount of time copying null characters.

-- Function: wchar_t * wcsncpy (wchar_t *restrict wto, const wchar_t *restrict wfrom, size_t size)

This function is similar to wcscpy but always copies exactly size wide characters into wto. 

If the length of wfrom is more than size, then wcsncpy copies just the first size wide characters. Note that in this case there is no null terminator written into wto. 

If the length of wfrom is less than size, then wcsncpy copies all of wfrom, followed by enough null wide characters to add up to size wide characters in all. This behavior is rarely useful, but it is specified by the ISO C standard. 

The behavior of wcsncpy is undefined if the strings overlap. 

Using wcsncpy as opposed to wcscpy is a way to avoid bugs relating to writing past the end of the allocated space for wto. However, it can also make your program much slower in one common case: copying a string which is probably small into a potentially large buffer. In this case, size may be large, and when it is, wcsncpy will waste a considerable amount of time copying null wide characters.

-- Function: char * strdup (const char *s)

This function copies the null-terminated string s into a newly allocated string. The string is allocated using malloc; see  Unconstrained Allocation . If malloc cannot allocate space for the new string, strdup returns a null pointer. Otherwise it returns a pointer to the new string.

-- Function: char * strcat (char *restrict to, const char *restrict from)

The strcat function is similar to strcpy, except that the characters from from are concatenated or appended to the end of to, instead of overwriting it. That is, the first character from from overwrites the null character marking the end of to. 

An equivalent definition for strcat would be: 

          char *
          strcat (char *restrict to, const char *restrict from)
          {
            strcpy (to + strlen (to), from);
            return to;
          }
     
This function has undefined results if the strings overlap.

-- Function: wchar_t * wcscat (wchar_t *restrict wto, const wchar_t *restrict wfrom)

The wcscat function is similar to wcscpy, except that the characters from wfrom are concatenated or appended to the end of wto, instead of overwriting it. That is, the first character from wfrom overwrites the null character marking the end of wto. 

An equivalent definition for wcscat would be: 

          wchar_t *
          wcscat (wchar_t *wto, const wchar_t *wfrom)
          {
            wcscpy (wto + wcslen (wto), wfrom);
            return wto;
          }
     
This function has undefined results if the strings overlap.

Programmers using the strcat or wcscat function (or the following strncat or wcsncar functions for that matter) can easily be recognized as lazy and reckless. In almost all situations the lengths of the participating strings are known (it better should be since how can one otherwise ensure the allocated size of the buffer is sufficient?) Or at least, one could know them if one keeps track of the results of the various function calls. But then it is very inefficient to use strcat/wcscat. A lot of time is wasted finding the end of the destination string so that the actual copying can start. This is a common example:

     /* This function concatenates arbitrarily many strings.  The last
        parameter must be NULL.  */
     char *
     concat (const char *str, ...)
     {
       va_list ap, ap2;
       size_t total = 1;
       const char *s;
       char *result;
     
       va_start (ap, str);
       /* Actually va_copy, but this is the name more gcc versions
          understand.  */
       __va_copy (ap2, ap);
     
       /* Determine how much space we need.  */
       for (s = str; s != NULL; s = va_arg (ap, const char *))
         total += strlen (s);
     
       va_end (ap);
     
       result = (char *) malloc (total);
       if (result != NULL)
         {
           result[0] = '\0';
     
           /* Copy the strings.  */
           for (s = str; s != NULL; s = va_arg (ap2, const char *))
             strcat (result, s);
         }
     
       va_end (ap2);
     
       return result;
     }

This looks quite simple, especially the second loop where the strings are actually copied. But these innocent lines hide a major performance penalty. Just imagine that ten strings of 100 bytes each have to be concatenated. For the second string we search the already stored 100 bytes for the end of the string so that we can append the next string. For all strings in total the comparisons necessary to find the end of the intermediate results sums up to 5500! If we combine the copying with the search for the allocation we can write this function more efficient:

     char *
     concat (const char *str, ...)
     {
       va_list ap;
       size_t allocated = 100;
       char *result = (char *) malloc (allocated);
       char *wp;
     
       if (allocated != NULL)
         {
           char *newp;
     
           va_start (ap, atr);
     
           wp = result;
           for (s = str; s != NULL; s = va_arg (ap, const char *))
             {
               size_t len = strlen (s);
     
               /* Resize the allocated memory if necessary.  */
               if (wp + len + 1 > result + allocated)
                 {
                   allocated = (allocated + len) * 2;
                   newp = (char *) realloc (result, allocated);
                   if (newp == NULL)
                     {
                       free (result);
                       return NULL;
                     }
                   wp = newp + (wp - result);
                   result = newp;
                 }
     
               wp = mempcpy (wp, s, len);
             }
     
           /* Terminate the result string.  */
           *wp++ = '\0';
     
           /* Resize memory to the optimal size.  */
           newp = realloc (result, wp - result);
           if (newp != NULL)
             result = newp;
     
           va_end (ap);
         }
     
       return result;
     }

With a bit more knowledge about the input strings one could fine-tune the memory allocation. The difference we are pointing to here is that we don't use strcat anymore. We always keep track of the length of the current intermediate result so we can safe us the search for the end of the string and use mempcpy. Please note that we also don't use stpcpy which might seem more natural since we handle with strings. But this is not necessary since we already know the length of the string and therefore can use the faster memory copying function. The example would work for wide characters the same way. 

Whenever a programmer feels the need to use strcat she or he should think twice and look through the program whether the code cannot be rewritten to take advantage of already calculated results. Again: it is almost always unnecessary to use strcat.
-- Function: char * strncat (char *restrict to, const char *restrict from, size_t size)

This function is like strcat except that not more than size characters from from are appended to the end of to. A single null character is also always appended to to, so the total allocated size of to must be at least size + 1 bytes longer than its initial length. 

The strncat function could be implemented like this: 

          char *
          strncat (char *to, const char *from, size_t size)
          {
            to[strlen (to) + size] = '\0';
            strncpy (to + strlen (to), from, size);
            return to;
          }
     
The behavior of strncat is undefined if the strings overlap.

-- Function: wchar_t * wcsncat (wchar_t *restrict wto, const wchar_t *restrict wfrom, size_t size)

This function is like wcscat except that not more than size characters from from are appended to the end of to. A single null character is also always appended to to, so the total allocated size of to must be at least size + 1 bytes longer than its initial length. 

The wcsncat function could be implemented like this: 

          wchar_t *
          wcsncat (wchar_t *restrict wto, const wchar_t *restrict wfrom,
                   size_t size)
          {
            wto[wcslen (to) + size] = L'\0';
            wcsncpy (wto + wcslen (wto), wfrom, size);
            return wto;
          }
     
The behavior of wcsncat is undefined if the strings overlap.

Here is an example showing the use of strncpy and strncat (the wide character version is equivalent). Notice how, in the call to strncat, the size parameter is computed to avoid overflowing the character array buffer.

     #include <string.h>
     #include <stdio.h>
     
     #define SIZE 10
     
     static char buffer[SIZE];
     
     main ()
     {
       strncpy (buffer, "hello", SIZE);
       puts (buffer);
       strncat (buffer, ", world", SIZE - strlen (buffer) - 1);
       puts (buffer);
     }

The output produced by this program looks like:

     hello
     hello, wo

-- Function: void bcopy (const void *from, void *to, size_t size)

This is a partially obsolete alternative for memmove, derived from BSD. Note that it is not quite equivalent to memmove, because the arguments are not in the same order and there is no return value.

-- Function: void bzero (void *block, size_t size)

This is a partially obsolete alternative for memset, derived from BSD. Note that it is not as general as memset, because the only value it can store is zero.

Copying
Next:  Documentation License , Previous:  Free Manuals , Up:  Top 




Appendix G GNU Lesser General Public License

Version 2.1, February 1999

     Copyright © 1991, 1999 Free Software Foundation, Inc.
     59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
     
     Everyone is permitted to copy and distribute verbatim copies
     of this license document, but changing it is not allowed.
     
     [This is the first released version of the Lesser GPL.  It also counts
     as the successor of the GNU Library Public License, version 2, hence the
     version number 2.1.]

G.0.1 Preamble

The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. 

This license, the Lesser General Public License, applies to some specially designated software--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. 

When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. 

To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. 

For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. 

We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. 

To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. 

Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. 

Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. 

When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. 

We call this license the Lesser General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. 

For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. 

In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. 

Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. 

The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run.

1. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". 

A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. 

The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) 

"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. 

Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 
2. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. 

You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 
3. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:

1. The modified work must itself be a software library. 
2. You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. 
3. You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. 
4. If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. 

(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)

These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. 

Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. 

In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 
4. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. 

Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. 

This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 
5. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. 

If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 
6. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. 

However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. 

When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. 

If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) 

Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 
7. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. 

You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:

1. Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) 
2. Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. 
3. Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. 
4. If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. 
5. Verify that the user has already received a copy of these materials or that you have already sent this user a copy.

For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. 

It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 
8. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:

1. Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. 
2. Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.

9. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 
10. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 
11. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 
12. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. 

If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. 

It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. 

This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 
13. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 
14. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 

Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 
15. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. 
16. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 
17. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

How to Apply These Terms to Your New Libraries

If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). 

To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.

     one line to give the library's name and an idea of what it does.
     Copyright (C) year  name of author
     
     This library is free software; you can redistribute it and/or modify it
     under the terms of the GNU Lesser General Public License as published by
     the Free Software Foundation; either version 2.1 of the License, or (at
     your option) any later version.
     
     This library is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     Lesser General Public License for more details.
     
     You should have received a copy of the GNU Lesser General Public
     License along with this library; if not, write to the Free Software
     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
     USA.

Also add information on how to contact you by electronic and paper mail. 

You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names:

     Yoyodyne, Inc., hereby disclaims all copyright interest in the library
     `Frob' (a library for tweaking knobs) written by James Random Hacker.
     
     signature of Ty Coon, 1 April 1990
     Ty Coon, President of Vice

That's all there is to it!

CPU Time 
Next:  Calendar Time , Previous:  Elapsed Time ,Up: Date and Time 




CPU Time Inquiry

To get a process' CPU time, you can use the clock function. This facility is declared in the header file time.h. In typical usage, you call the clock function at the beginning and end of the interval you want to time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second) to get processor time, like this:

     #include <time.h>
     
     clock_t start, end;
     double cpu_time_used;
     
     start = clock();
     ... /* Do the work. */
     end = clock();
     cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

Do not use a single CPU time as an amount of time; it doesn't work that way. Either do a subtraction as shown above or query processor time directly. See  Processor Time . 

Different computers and operating systems vary wildly in how they keep track of CPU time. It's common for the internal processor clock to have a resolution somewhere between a hundredth and millionth of a second.

-- Macro: int CLOCKS_PER_SEC

The value of this macro is the number of clock ticks per second measured by the clock function. POSIX requires that this value be one million independent of the actual resolution.

-- Macro: int CLK_TCK

This is an obsolete name for CLOCKS_PER_SEC.

-- Data Type: clock_t

This is the type of the value returned by the clock function. Values of type clock_t are numbers of clock ticks.

-- Function: clock_t clock (void)

This function returns the calling process' current CPU time. If the CPU time is not available or cannot be represented, clock returns the value (clock_t)(-1).

+ Creating Directories 
Next:  Attribute Meanings , Previous:  Renaming Files , Up:  File System Interface 




Creating Directories

Directories are created with the mkdir function. (There is also a shell command mkdir which does the same thing.)
-- Function: int mkdir (const char *filename, mode_t mode)

The mkdir function creates a new, empty directory with name filename. 

The argument mode specifies the file permissions for the new directory file. 

A return value of 0 indicates successful completion, and -1 indicates failure. In addition to the usual file name syntax errors (see  File Name Errors ), the following errno error conditions are defined for this function:

EACCES
Write permission is denied for the parent directory in which the new directory is to be added. 
EEXIST
A file named filename already exists. 
ENOSPC
The file system doesn't have enough room to create the new directory. 

To use this function, your program should include the header file dir.h.

Currency Symbol 
Next:  Sign of Money Amount , Previous:  General Numeric , Up:  The Lame Way to Locale Data 




Printing the Currency Symbol

These members of the struct lconv structure specify how to print the symbol to identify a monetary value--the international analog of `$' for US dollars. 

Each country has two standard currency symbols. The local currency symbol is used commonly within the country, while the international currency symbol is used internationally to refer to that country's currency when it is necessary to indicate the country unambiguously. 

For example, many countries use the dollar as their monetary unit, and when dealing with international currencies it's important to specify that one is dealing with (say) Canadian dollars instead of U.S. dollars or Australian dollars. But when the context is known to be Canada, there is no need to make this explicit--dollar amounts are implicitly assumed to be in Canadian dollars.

char *currency_symbol
The local currency symbol for the selected locale. 

In the standard `C' locale, this member has a value of "" (the empty string), meaning "unspecified". The ISO standard doesn't say what to do when you find this value; we recommend you simply print the empty string as you would print any other string pointed to by this variable. 
char *int_curr_symbol
The international currency symbol for the selected locale. 

The value of int_curr_symbol should normally consist of a three-letter abbreviation determined by the international standard ISO 4217 Codes for the Representation of Currency and Funds, followed by a one-character separator (often a space). 

In the standard `C' locale, this member has a value of "" (the empty string), meaning "unspecified". We recommend you simply print the empty string as you would print any other string pointed to by this variable. 
char p_cs_precedes
char n_cs_precedes
char int_p_cs_precedes
char int_n_cs_precedes
These members are 1 if the currency_symbol or int_curr_symbol strings should precede the value of a monetary amount, or 0 if the strings should follow the value. The p_cs_precedes and int_p_cs_precedes members apply to positive amounts (or zero), and the n_cs_precedes and int_n_cs_precedes members apply to negative amounts. 

In the standard `C' locale, all of these members have a value of CHAR_MAX, meaning "unspecified". The ISO standard doesn't say what to do when you find this value. We recommend printing the currency symbol before the amount, which is right for most countries. In other words, treat all nonzero values alike in these members. 

The members with the int_ prefix apply to the int_curr_symbol while the other two apply to currency_symbol. 
char p_sep_by_space
char n_sep_by_space
char int_p_sep_by_space
char int_n_sep_by_space
These members are 1 if a space should appear between the currency_symbol or int_curr_symbol strings and the amount, or 0 if no space should appear. The p_sep_by_space and int_p_sep_by_space members apply to positive amounts (or zero), and the n_sep_by_space and int_n_sep_by_space members apply to negative amounts. 

In the standard `C' locale, all of these members have a value of CHAR_MAX, meaning "unspecified". The ISO standard doesn't say what you should do when you find this value; we suggest you treat it as 1 (print a space). In other words, treat all nonzero values alike in these members. 

The members with the int_ prefix apply to the int_curr_symbol while the other two apply to currency_symbol. There is one specialty with the int_curr_symbol, though. Since all legal values contain a space at the end the string one either printf this space (if the currency symbol must appear in front and must be separated) or one has to avoid printing this character at all (especially when at the end of the string).

+ Data Type Measurements 
Previous:  Important Data Types , Up:  Language Features 




Data Type Measurements

Most of the time, if you choose the proper C data type for each object in your program, you need not be concerned with just how it is represented or how many bits it uses. When you do need such information, the C language itself does not provide a way to get it. The header files limits.h and float.h contain macros which give you this information in full detail.

·  Width of Type : How many bits does an integer type hold?
·  Range of Type : What are the largest and smallest values that an integer type can hold?
·  Floating Type Macros : Parameters that measure the floating point types.
·  Structure Measurement : Getting measurements on structure types.

Date and Time 
Next:  Non-Local Exits , Previous:  Arithmetic , Up:  Top 




Date and Time

This chapter describes functions for manipulating dates and times, including functions for determining what time it is and conversion between different time representations.

·  Time Basics : Concepts and definitions.
·  Elapsed Time : Data types to represent elapsed times
·  CPU Time : Time a program has spent executing.
·  Calendar Time : Manipulation of ``real'' dates and times.
·  Sleeping : Waiting for a period of time.

Defining Handlers 
Next:  Handler Returns , Previous:  Signal Actions , Up:  Signal Handling 




Defining Signal Handlers

This section describes how to write a signal handler function that can be established with the signal or sigaction functions. 

A signal handler is just a function that you compile together with the rest of the program. Instead of directly invoking the function, you use signal or sigaction to tell the operating system to call it when a signal arrives. This is known as establishing the handler. See  Signal Actions . 

There are two basic strategies you can use in signal handler functions:

· You can have the handler function note that the signal arrived by tweaking some global data structures, and then return normally. 
· You can have the handler function terminate the program or transfer control to a point where it can recover from the situation that caused the signal.

You need to take special care in writing handler functions because they can be called asynchronously. That is, a handler might be called at any point in the program, unpredictably. If two signals arrive during a very short interval, one handler can run within another. This section describes what your handler should do, and what you should avoid.

·  Handler Returns : Handlers that return normally, and what this means.
·  Termination in Handler : How handler functions terminate a program.
·  Longjmp in Handler : Nonlocal transfer of control out of a signal handler.
·  Signals in Handler : What happens when signals arrive while the handler is already occupied.
·  Nonreentrancy : Do not call any functions unless you know they are reentrant with respect to signals.
·  Atomic Data Access : A single handler can run in the middle of reading or writing a single object.

Deleting Files 
Next:  Renaming Files , Previous:  Working Directory, Up:  File System Interface 




Deleting Files

You can delete a file with unlink or remove. 

Deletion actually deletes a file name. If this is the file's only name, then the file is deleted as well. 

-- Function: int unlink (const char *filename)

The unlink function deletes the file name filename. If this is a file's sole name, the file itself is also deleted. (Actually, if any process has the file open when this happens, deletion is postponed until all processes have closed the file.) 

The function unlink is declared in the header file dir.h. 

This function returns 0 on successful completion, and -1 on error. In addition to the usual file name errors (see  File Name Errors ), the following errno error conditions are defined for this function:

EACCES
Write permission is denied for the directory from which the file is to be removed, or the directory has the sticky bit set and you do not own the file. 
EBUSY
This error indicates that the file is being used by the system in such a way that it can't be unlinked. For example, you might see this error if the file name specifies the root directory or a mount point for a file system. 
ENOENT
The file name to be deleted doesn't exist. 
EPERM
On some systems unlink cannot be used to delete the name of a directory, or at least can only be used this way by a privileged user. To avoid such problems, use rmdir to delete directories. (In the GNU system unlink can never delete the name of a directory.) 
EROFS
The directory containing the file name to be deleted is on a read-only file system and can't be modified.

-- Function: int rmdir (const char *filename)

The rmdir function deletes a directory. The directory must be empty before it can be removed; in other words, it can only contain entries for . and ... 

In most other respects, rmdir behaves like unlink. There are two additional errno error conditions defined for rmdir:

ENOTEMPTY
EEXIST
The directory to be deleted is not empty.

These two error codes are synonymous; some systems use one, and some use the other. The GNU system always uses ENOTEMPTY. 

The prototype for this function is declared in the header file unistd.h.

-- Function: int remove (const char *filename)

This is the ISO C function to remove a file. It works like unlink for files and like rmdir for directories. remove is declared in stdio.h.

Descriptors and Streams 
Next:  Duplicating Descriptors , Previous:  File Position Primitive , Up:  Low-Level I/O 




Descriptors and Streams

Given an open file descriptor, you can create a stream for it with the fdopen function.  This functions is declared in the header file stdio.h.

-- Function: FILE * fdopen (int filedes, const char *opentype)

The fdopen function returns a new stream for the file descriptor filedes. 

The opentype argument is interpreted in the same way as for the fopen function (see  Opening Streams ), except that the `b' option is not permitted; this is because GNU makes no distinction between text and binary files. Also, "w" and "w+" do not cause truncation of the file; these have an effect only when opening a file, and in this case the file has already been opened. You must make sure that the opentype argument matches the actual mode of the open file descriptor. 

The return value is the new stream. If the stream cannot be created (for example, if the modes for the file indicated by the file descriptor do not permit the access specified by the opentype argument), a null pointer is returned instead. 

In some other systems, fdopen may fail to detect that the modes for file descriptor do not permit the access specified by opentype. The C library always checks for this.

Directories
Next:  File Name Resolution , Up:  File Names 




Directories

In order to understand the syntax of file names, you need to understand how the file system is organized into a hierarchy of directories. 

A directory is a file that contains information to associate other files with names; these associations are called links or directory entries. Sometimes, people speak of "files in a directory", but in reality, a directory only contains pointers to files, not the files themselves. 

The name of a file contained in a directory entry is called a file name component. In general, a file name consists of a sequence of one or more such components, separated by the slash character (`\'). A file name which is just one component names a file with respect to its directory. A file name with multiple components names a directory, and then a file in that directory, and so on. 

Some other documents, such as the POSIX standard, use the term pathname for what we call a file name, and either filename or pathname component for what this manual calls a file name component. We don't use this terminology because a "path" is something completely different (a list of directories to search), and we think that "pathname" used for something else will confuse users. We always use "file name" and "file name component" (or sometimes just "component", where the context is obvious) in GNU documentation.  

You can find more detailed information about operations on directories in  File System Interface .

Disadvantages of Alloca 
Next:  Variable-Size Arrays , Previous:  Advantages of Alloca , Up:  Variable Size Automatic 




Disadvantages of alloca

These are the disadvantages of alloca in comparison with malloc:

· If you try to allocate more memory than the machine can provide, you don't get a clean error message. Instead you get a fatal signal like the one you would get from an infinite recursion; probably a segmentation violation (see  Program Error Signals ). 
· Some other systems fail to support alloca, so it is less portable. However, a slower emulation of alloca written in C is available for use on systems with this deficiency.

Documentation License 
Next:  Concept Index , Previous:  Copying , Up:  Top 




GNU Free Documentation License

Version 1.1, March 2000

     Copyright © 2000 Free Software Foundation, Inc.
     59 Temple Place, Suite 330, Boston, MA  02111-1307, USA
     
     Everyone is permitted to copy and distribute verbatim copies
     of this license document, but changing it is not allowed.

1. PREAMBLE 

The purpose of this License is to make a manual, textbook, or other written document free in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. 

This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. 

We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. 
2. APPLICABILITY AND DEFINITIONS 

This License applies to any manual or other work that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". 

A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. 

A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (For example, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. 

The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. 

The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. 

A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, whose contents can be viewed and edited directly and straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup has been designed to thwart or discourage subsequent modification by readers is not Transparent. A copy that is not "Transparent" is called "Opaque". 

Examples of suitable formats for Transparent copies include plain ascii without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML designed for human modification. Opaque formats include PostScript, PDF, proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML produced by some word processors for output purposes only. 

The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text. 
3. VERBATIM COPYING 

You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. 

You may also lend copies, under the same conditions stated above, and you may publicly display copies. 
4. COPYING IN QUANTITY 

If you publish printed copies of the Document numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. 

If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. 

If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a publicly-accessible computer-network location containing a complete Transparent copy of the Document, free of added material, which the general network-using public has access to download anonymously at no charge using public-standard network protocols. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. 

It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. 
5. MODIFICATIONS 

You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:

1. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. 
2. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has less than five). 
3. State on the Title page the name of the publisher of the Modified Version, as the publisher. 
4. Preserve all the copyright notices of the Document. 
5. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. 
6. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. 
7. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. 
8. Include an unaltered copy of this License. 
9. Preserve the section entitled "History", and its title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. 
10. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. 
11. In any section entitled "Acknowledgments" or "Dedications", preserve the section's title, and preserve in the section all the substance and tone of each of the contributor acknowledgments and/or dedications given therein. 
12. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. 
13. Delete any section entitled "Endorsements". Such a section may not be included in the Modified Version. 
14. Do not retitle any existing section as "Endorsements" or to conflict in title with any Invariant Section.

If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles. 

You may add a section entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. 

You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. 

The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. 
6. COMBINING DOCUMENTS 

You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice. 

The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. 

In the combination, you must combine any sections entitled "History" in the various original documents, forming one section entitled "History"; likewise combine any sections entitled "Acknowledgments", and any sections entitled "Dedications". You must delete all sections entitled "Endorsements." 
7. COLLECTIONS OF DOCUMENTS 

You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. 

You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. 
8. AGGREGATION WITH INDEPENDENT WORKS 

A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, does not as a whole count as a Modified Version of the Document, provided no compilation copyright is claimed for the compilation. Such a compilation is called an "aggregate", and this License does not apply to the other self-contained works thus compiled with the Document, on account of their being thus compiled, if they are not themselves derivative works of the Document. 

If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one quarter of the entire aggregate, the Document's Cover Texts may be placed on covers that surround only the Document within the aggregate. Otherwise they must appear on covers around the whole aggregate. 
9. TRANSLATION 

Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License provided that you also include the original English version of this License. In case of a disagreement between the translation and the original English version of this License, the original English version will prevail. 
10. TERMINATION 

You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 
11. FUTURE REVISIONS OF THIS LICENSE 

The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See  http://www.gnu.org/copyleft/ . 

Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation.

ADDENDUM: How to use this License for your documents

To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:

       Copyright (C)  year  your name.
       Permission is granted to copy, distribute and/or modify this document
       under the terms of the GNU Free Documentation License, Version 1.1
       or any later version published by the Free Software Foundation;
       with the Invariant Sections being list their titles, with the
       Front-Cover Texts being list, and with the Back-Cover Texts being list.
       A copy of the license is included in the section entitled ``GNU
       Free Documentation License''.

If you have no Invariant Sections, write "with no Invariant Sections" instead of saying which ones are invariant. If you have no Front-Cover Texts, write "no Front-Cover Texts" instead of "Front-Cover Texts being list"; likewise for Back-Cover Texts. 

If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.

Duplicating Descriptors 
Next:  File Status Flags , Previous:  Previous:  Duplicating Descriptors , Up:  Low-Level I/O 



Duplicating Descriptors

You can duplicate a file descriptor, or allocate another file descriptor that refers to the same open file as the original. Duplicate descriptors share one file position and one set of file status flags (see  File Status Flags ), but each has its own set of file descriptor flags.

The major use of duplicating a file descriptor is to implement redirection of input or output: that is, to change the file or pipe that a particular file descriptor corresponds to. 

There are also convenient functions dup and dup2 for duplicating descriptors. 

Prototypes for dup and dup2 are in the header file io.h.

-- Function: int dup (int old)

This function copies descriptor old to the first available descriptor number (the first number not currently open).

-- Function: int dup2 (int old, int new)

This function copies the descriptor old to descriptor number new. 

If old is an invalid descriptor, then dup2 does nothing; it does not close new. Otherwise, the new duplicate of old replaces any previous meaning of descriptor new, as if new were closed first. 

Here is an example showing how to use dup2 to do redirection. Typically, redirection of the standard streams (like stdin) is done by a shell or shell-like program before calling one of the exec functions (see  Executing a File ) to execute a new program in a child process. When the new program is executed, it creates and initializes the standard streams to point to the corresponding file descriptors, before its main function is invoked. 

So, to redirect standard input to a file, the shell could do something like:

         char *filename;
         char *program;
         int file;
         ...
         file = TEMP_FAILURE_RETRY (open (filename, O_RDONLY));
         dup2 (file, STDIN_FILENO);
         TEMP_FAILURE_RETRY (close (file));
         execv (program, NULL);


Effects of Locale 
Next:  Choosing Locale , Up:  Locales 




What Effects a Locale Has

Each locale specifies conventions for several purposes, including the following:

· What multibyte character sequences are valid, and how they are interpreted (see  Character Set Handling ). 
· Classification of which characters in the local character set are considered alphabetic, and upper- and lower-case conversion conventions (see  Character Handling ). 
· The collating sequence for the local language and character set (see  Collation Functions ). 
· Formatting of numbers and currency amounts (see  General Numeric ). 
· Formatting of dates and times (see  Formatting Calendar Time ). 
· What language to use for user answers to yes-or-no questions (see  Yes-or-No Questions ). 

Some aspects of adapting to the specified locale are handled automatically by the library subroutines. For example, all your program needs to do in order to use the collating sequence of the chosen locale is to use strcoll or strxfrm to compare strings. 

Other aspects of locales are beyond the comprehension of the library. For example, the library can't automatically translate your program's output messages into other languages. The only way you can support output in the user's favorite language is to program this more or less by hand. The C library provides functions to handle translations for multiple languages easily. 

This chapter discusses the mechanism by which you can modify the current locale. The effects of the current locale on specific library functions are discussed in more detail in the descriptions of those functions.

Elapsed Time 
Next: CPU Time{linkID=480}, Previous:  Time Basics , Up:  Date and Time 




Elapsed Time

One way to represent an elapsed time is with a simple arithmetic data type, as with the following function to compute the elapsed time between two calendar times. This function is declared in time.h.

-- Function: double difftime (time_t time1, time_t time0)

The difftime function returns the number of seconds of elapsed time between calendar time time1 and calendar time time0, as a value of type double. The difference ignores leap seconds unless leap second support is enabled. 

In this system, you can simply subtract time_t values. But on other systems, the time_t data type might use some other encoding where subtraction doesn't work directly.


Environment Access 
Previous:  Environment Variables , Up:  Environment Variables 




Environment Access

The value of an environment variable can be accessed with the getenv function. This is declared in the header file stdlib.h. All of the following functions can be safely used in multi-threaded programs. It is made sure that concurrent modifications to the environment do not lead to errors.

-- Function: char * getenv (const char *name)

This function returns a string that is the value of the environment variable name. You must not modify this string. In some systems it might be overwritten by subsequent calls to getenv (but not by any other library function). If the environment variable name is not defined, the value is a null pointer.

-- Function: int putenv (const char *name)

The putenv function can be used to add a new definition to the environment, or to modify an existing definition.  As an example:

		putenv("myvar=hello");

sets the environment variable 'myvar' to the value 'hello'.

Please note that you cannot remove an entry completely using this function. 


You can deal directly with the underlying representation of environment objects to add more variables to the environment (for example, to communicate with another program you are about to execute; see  Executing a File ).

-- Variable: char ** _environ

The environment is represented as an array of strings. Each string is of the format `name=value'. The order in which strings appear in the environment is not significant, but the same name must not appear more than once. The last element of the array is a null pointer. 

This variable is declared in the header file stdlib.h. 

If you just want to get the value of an environment variable, use getenv.

This system passes the initial value of _environ as the third argument to main. See  Program Arguments .

Environment Variables 
Previous:  Program Arguments , Up:  Program Basics 




Environment Variables

When a program is executed, it receives information about the context in which it was invoked in two ways. The first mechanism uses the argv and argc arguments to its main function, and is discussed in  Program Arguments . The second mechanism uses environment variables and is discussed in this section. 

The argv mechanism is typically used to pass command-line arguments specific to the particular program being invoked. The environment, on the other hand, keeps track of information that is shared by many programs, changes infrequently, and that is less frequently used. 

The environment variables discussed in this section are the same environment variables that you set using assignments and the export command in the shell. Programs executed from the shell inherit all of the environment variables from the shell. 

Standard environment variables are used for information about the user's home directory, terminal type, current locale, and so on; you can define additional variables for other purposes. The set of all environment variables that have values is collectively known as the environment. 

Names of environment variables are case-sensitive and must not contain the character `='. System-defined environment variables are invariably uppercase. 

The values of environment variables can be anything that can be represented as a string. A value must not contain an embedded null character, since this is assumed to terminate the string.

·  Environment Access : How to get and set the values of environment variables.

EOF and Errors 
Next:  Error Recovery , Previous:  Formatted Input , Up:  I/O on Streams 




End-Of-File and Errors

Many of the functions described in this chapter return the value of the macro EOF to indicate unsuccessful completion of the operation. Since EOF is used to report both end of file and random errors, it's often better to use the feof function to check explicitly for end of file and ferror to check for errors. These functions check indicators that are part of the internal state of the stream object, indicators set if the appropriate condition was detected by a previous I/O operation on that stream.
-- Macro: int EOF

This macro is an integer value that is returned by a number of narrow stream functions to indicate an end-of-file condition, or some other error situation. With the GNU library, EOF is -1. In other libraries, its value may be some other negative number. 

This symbol is declared in stdio.h.

-- Macro: int WEOF

This macro is an integer value that is returned by a number of wide stream functions to indicate an end-of-file condition, or some other error situation. With the GNU library, WEOF is -1. In other libraries, its value may be some other negative number. 

This symbol is declared in wchar.h.

-- Function: int feof (FILE *stream)

The feof function returns nonzero if and only if the end-of-file indicator for the stream stream is set. 

This symbol is declared in stdio.h.

-- Function: int ferror (FILE *stream)

The ferror function returns nonzero if and only if the error indicator for the stream stream is set, indicating that an error has occurred on a previous operation on the stream. 

This symbol is declared in stdio.h.

In addition to setting the error indicator associated with the stream, the functions that operate on streams also set errno in the same way as the corresponding low-level functions that operate on file descriptors. For example,  all of the errno error conditions defined for write are meaningful for functions such as fputc, printf, and fflush. For more information about the descriptor-level I/O functions, see  Low-Level I/O .

Error Codes 
Next:  Error Messages , Previous:  Checking for Errors , Up:  Error Reporting 




Error Codes

The error code macros are defined in the header file errno.h. All of them expand into integer constant values. Some of these error codes can't occur on the GNU system, but they can occur using the GNU library on other systems.
-- Macro: int EPERM

Operation not permitted; only the owner of the file (or other resource) or processes with special privileges can perform the operation.

-- Macro: int ENOENT

No such file or directory. This is a "file doesn't exist" error for ordinary files that are referenced in contexts where they are expected to already exist.

-- Macro: int ESRCH

No process matches the specified process ID.

-- Macro: int EINTR

Interrupted function call; an asynchronous signal occurred and prevented completion of the call. When this happens, you should try the call again. 

You can choose to have functions resume after a signal that is handled, rather than failing with EINTR; see  Interrupted Primitives .

-- Macro: int EIO

Input/output error; usually used for physical read or write errors.

-- Macro: int ENXIO

No such device or address. The system tried to use the device represented by a file you specified, and it couldn't find the device. This can mean that the device file was installed incorrectly, or that the physical device is missing or not correctly attached to the computer.

-- Macro: int E2BIG

Argument list too long; used when the arguments passed to a new program being executed with one of the exec functions (see  Executing a File ) occupy too much memory space. This condition never arises in the GNU system.

-- Macro: int ENOEXEC

Invalid executable file format. This condition is detected by the exec functions; see  Executing a File .

-- Macro: int EBADF

Bad file descriptor; for example, I/O on a descriptor that has been closed or reading from a descriptor open only for writing (or vice versa).

-- Macro: int ECHILD

There are no child processes. This error happens on operations that are supposed to manipulate child processes, when there aren't any processes to manipulate.

-- Macro: int EDEADLK

Deadlock avoided; allocating a system resource would have resulted in a deadlock situation. The system does not guarantee that it will notice all such situations. This error means you got lucky and the system noticed; it might just hang. See  File Locks , for an example.

-- Macro: int ENOMEM

No memory available. The system cannot allocate more virtual memory because its capacity is full.

-- Macro: int EACCES

Permission denied; the file permissions do not allow the attempted operation.

-- Macro: int EFAULT

Bad address; an invalid pointer was detected. In the GNU system, this error never happens; you get a signal instead.

-- Macro: int ENOTBLK

A file that isn't a block special file was given in a situation that requires one. For example, trying to mount an ordinary file as a file system in Unix gives this error.

-- Macro: int EBUSY

Resource busy; a system resource that can't be shared is already in use. For example, if you try to delete a file that is the root of a currently mounted filesystem, you get this error.

-- Macro: int EEXIST

File exists; an existing file was specified in a context where it only makes sense to specify a new file.

-- Macro: int EXDEV

An attempt to make an improper link across file systems was detected. This happens not only when you use link (see  Hard Links ) but also when you rename a file with rename (see  Renaming Files ).

-- Macro: int ENODEV

The wrong type of device was given to a function that expects a particular sort of device.

-- Macro: int ENOTDIR

A file that isn't a directory was specified when a directory is required.

-- Macro: int EISDIR

File is a directory; you cannot open a directory for writing, or create or remove hard links to it.

-- Macro: int EINVAL

Invalid argument. This is used to indicate various kinds of problems with passing the wrong argument to a library function.

-- Macro: int EMFILE

The current process has too many files open and can't open any more. Duplicate descriptors do count toward this limit. 

In BSD and GNU, the number of open files is controlled by a resource limit that can usually be increased. If you get this error, you might want to increase the RLIMIT_NOFILE limit or make it unlimited; see  Limits on Resources .

-- Macro: int ENFILE

There are too many distinct file openings in the entire system. Note that any number of linked channels count as just one file opening; see  Linked Channels . This error never occurs in the GNU system.

-- Macro: int ENOTTY

Inappropriate I/O control operation, such as trying to set terminal modes on an ordinary file.

-- Macro: int ETXTBSY

An attempt to execute a file that is currently open for writing, or write to a file that is currently being executed. Often using a debugger to run a program is considered having it open for writing and will cause this error. (The name stands for "text file busy".) This is not an error in the GNU system; the text is copied as necessary.

-- Macro: int EFBIG

File too big; the size of a file would be larger than allowed by the system.

-- Macro: int ENOSPC

No space left on device; write operation on a file failed because the disk is full.

-- Macro: int ESPIPE

Invalid seek operation (such as on a pipe).

-- Macro: int EROFS

An attempt was made to modify something on a read-only file system.

-- Macro: int EMLINK

Too many links; the link count of a single file would become too large. rename can cause this error if the file being renamed already has as many links as it can take (see  Renaming Files ).

-- Macro: int EPIPE

Broken pipe; there is no process reading from the other end of a pipe. Every library function that returns this error code also generates a SIGPIPE signal; this signal terminates the program if not handled or blocked. Thus, your program will never actually see EPIPE unless it has handled or blocked SIGPIPE.

-- Macro: int EDOM

Domain error; used by mathematical functions when an argument value does not fall into the domain over which the function is defined.

-- Macro: int ERANGE

Range error; used by mathematical functions when the result value is not representable because of overflow or underflow.

-- Macro: int EAGAIN

Resource temporarily unavailable; the call might work if you try again later. The macro EWOULDBLOCK is another name for EAGAIN; they are always the same in the C library. 

This error can happen in a few different situations:

· An operation that would block was attempted on an object that has non-blocking mode selected. Trying the same operation again will block until some external condition makes it possible to read, write, or connect (whatever the operation). You can use select to find out when the operation will be possible; see  Waiting for I/O . 

Portability Note: In many older Unix systems, this condition was indicated by EWOULDBLOCK, which was a distinct error code different from EAGAIN. To make your program portable, you should check for both codes and treat them the same. 
· A temporary resource shortage made an operation impossible. fork can return this error. It indicates that the shortage is expected to pass, so your program can try the call again later and it may succeed. It is probably a good idea to delay for a few seconds before trying it again, to allow time for other processes to release scarce resources. Such shortages are usually fairly serious and affect the whole system, so usually an interactive program should report the error to the user and return to its command loop.

-- Macro: int EWOULDBLOCK

In the C library, this is another name for EAGAIN (above). The values are always the same, on every operating system. 

C libraries in many older Unix systems have EWOULDBLOCK as a separate error code.

-- Macro: int EINPROGRESS

An operation that cannot complete immediately was initiated on an object that has non-blocking mode selected. Some functions that must always block (such as connect; see  Connecting ) never return EAGAIN. Instead, they return EINPROGRESS to indicate that the operation has begun and will take some time. Attempts to manipulate the object before the call completes return EALREADY. You can use the select function to find out when the pending operation has completed; see  Waiting for I/O .

-- Macro: int EALREADY

An operation is already in progress on an object that has non-blocking mode selected.

-- Macro: int ENOTSOCK

A file that isn't a socket was specified when a socket is required.

-- Macro: int EMSGSIZE

The size of a message sent on a socket was larger than the supported maximum size.

-- Macro: int EPROTOTYPE

The socket type does not support the requested communications protocol.

-- Macro: int ENOPROTOOPT

You specified a socket option that doesn't make sense for the particular protocol being used by the socket. See  Socket Options .

-- Macro: int EPROTONOSUPPORT

The socket domain does not support the requested communications protocol (perhaps because the requested protocol is completely invalid). See  Creating a Socket .

-- Macro: int ESOCKTNOSUPPORT

The socket type is not supported.

-- Macro: int EOPNOTSUPP

The operation you requested is not supported. Some socket functions don't make sense for all types of sockets, and others may not be implemented for all communications protocols. In the GNU system, this error can happen for many calls when the object does not support the particular operation; it is a generic indication that the server knows nothing to do for that call.

-- Macro: int EPFNOSUPPORT

The socket communications protocol family you requested is not supported.

-- Macro: int EAFNOSUPPORT

The address family specified for a socket is not supported; it is inconsistent with the protocol being used on the socket. See  Sockets .

-- Macro: int EADDRINUSE

The requested socket address is already in use. See  Socket Addresses .

-- Macro: int EADDRNOTAVAIL

The requested socket address is not available; for example, you tried to give a socket a name that doesn't match the local host name. See  Socket Addresses .

-- Macro: int ENETDOWN

A socket operation failed because the network was down.

-- Macro: int ENETUNREACH

A socket operation failed because the subnet containing the remote host was unreachable.

-- Macro: int ENETRESET

A network connection was reset because the remote host crashed.

-- Macro: int ECONNABORTED

A network connection was aborted locally.

-- Macro: int ECONNRESET

A network connection was closed for reasons outside the control of the local host, such as by the remote machine rebooting or an unrecoverable protocol violation.

-- Macro: int ENOBUFS

The kernel's buffers for I/O operations are all in use. In GNU, this error is always synonymous with ENOMEM; you may get one or the other from network operations.

-- Macro: int EISCONN

You tried to connect a socket that is already connected. See  Connecting .

-- Macro: int ENOTCONN

The socket is not connected to anything. You get this error when you try to transmit data over a socket, without first specifying a destination for the data. For a connectionless socket (for datagram protocols, such as UDP), you get EDESTADDRREQ instead.

-- Macro: int EDESTADDRREQ

No default destination address was set for the socket. You get this error when you try to transmit data over a connectionless socket, without first specifying a destination for the data with connect.

-- Macro: int ESHUTDOWN

The socket has already been shut down.

-- Macro: int ETOOMANYREFS

???

-- Macro: int ETIMEDOUT

A socket operation with a specified timeout received no response during the timeout period.

-- Macro: int ECONNREFUSED

A remote host refused to allow the network connection (typically because it is not running the requested service).

-- Macro: int ELOOP

Too many levels of symbolic links were encountered in looking up a file name. This often indicates a cycle of symbolic links.

-- Macro: int ENAMETOOLONG

Filename too long (longer than PATH_MAX; see  Limits for Files ) or host name too long (in gethostname or sethostname; see  Host Identification ).

-- Macro: int EHOSTDOWN

The remote host for a requested network connection is down.

-- Macro: int EHOSTUNREACH

The remote host for a requested network connection is not reachable.

-- Macro: int ENOTEMPTY

Directory not empty, where an empty directory was expected. Typically, this error occurs when you are trying to delete a directory.

-- Macro: int EPROCLIM

This means that the per-user limit on new process would be exceeded by an attempted fork. See  Limits on Resources , for details on the RLIMIT_NPROC limit.

-- Macro: int EUSERS

The file quota system is confused because there are too many users.

-- Macro: int EDQUOT

The user's disk quota was exceeded.

-- Macro: int ESTALE

Stale NFS file handle. This indicates an internal confusion in the NFS system which is due to file system rearrangements on the server host. Repairing this condition usually requires unmounting and remounting the NFS file system on the local host.

-- Macro: int EREMOTE

An attempt was made to NFS-mount a remote file system with a file name that already specifies an NFS-mounted file. (This is an error on some operating systems, but we expect it to work properly on the GNU system, making this error code impossible.)

-- Macro: int EBADRPC

???

-- Macro: int ERPCMISMATCH

???

-- Macro: int EPROGUNAVAIL

???

-- Macro: int EPROGMISMATCH

???

-- Macro: int EPROCUNAVAIL

???

-- Macro: int ENOLCK

No locks available. This is used by the file locking facilities; see  File Locks . This error is never generated by the GNU system, but it can result from an operation to an NFS server running another operating system.

-- Macro: int EFTYPE

Inappropriate file type or format. The file was the wrong type for the operation, or a data file had the wrong format. 

On some systems chmod returns this error if you try to set the sticky bit on a non-directory file; see  Setting Permissions .

-- Macro: int EAUTH

???

-- Macro: int ENEEDAUTH

???

-- Macro: int ENOSYS

Function not implemented. This indicates that the function called is not implemented at all, either in the C library itself or in the operating system. When you get this error, you can be sure that this particular function will always fail with ENOSYS unless you install a new version of the C library or the operating system.

-- Macro: int ENOTSUP

Not supported. A function returns this error when certain parameter values are valid, but the functionality they request is not available. This can mean that the function does not implement a particular command or option value or flag bit at all. For functions that operate on some object given in a parameter, such as a file descriptor or a port, it might instead mean that only that specific object (file descriptor, port, etc.) is unable to support the other parameters given; different file descriptors might support different ranges of parameter values. 

If the entire function is not available at all in the implementation, it returns ENOSYS instead.

-- Macro: int EILSEQ

While decoding a multibyte character the function came along an invalid or an incomplete sequence of bytes or the given wide character is invalid.

-- Macro: int EBACKGROUND

In the GNU system, servers supporting the term protocol return this error for certain operations when the caller is not in the foreground process group of the terminal. Users do not usually see this error because functions such as read and write translate it into a SIGTTIN or SIGTTOU signal. See  Job Control , for information on process groups and these signals.

-- Macro: int EDIED

In the GNU system, opening a file returns this error when the file is translated by a program and the translator program dies while starting up, before it has connected to the file.

-- Macro: int ED

The experienced user will know what is wrong.

-- Macro: int EGREGIOUS

You did what?

-- Macro: int EIEIO

Go home and have a glass of warm, dairy-fresh milk.

-- Macro: int EGRATUITOUS

This error code has no purpose.

-- Macro: int EBADMSG

-- Macro: int EIDRM

-- Macro: int EMULTIHOP

-- Macro: int ENODATA

-- Macro: int ENOLINK

-- Macro: int ENOMSG

-- Macro: int ENOSR

-- Macro: int ENOSTR

-- Macro: int EOVERFLOW

-- Macro: int EPROTO

-- Macro: int ETIME

The following error codes are defined by the Linux/i386 kernel. They are not yet documented.
-- Macro: int ERESTART

-- Macro: int ECHRNG

-- Macro: int EL2NSYNC

-- Macro: int EL3HLT

-- Macro: int EL3RST

-- Macro: int ELNRNG

-- Macro: int EUNATCH

-- Macro: int ENOCSI

-- Macro: int EL2HLT

-- Macro: int EBADE

-- Macro: int EBADR

-- Macro: int EXFULL

-- Macro: int ENOANO

-- Macro: int EBADRQC

-- Macro: int EBADSLT

-- Macro: int EDEADLOCK

-- Macro: int EBFONT

-- Macro: int ENONET

-- Macro: int ENOPKG

-- Macro: int EADV

-- Macro: int ESRMNT

-- Macro: int ECOMM

-- Macro: int EDOTDOT

-- Macro: int ENOTUNIQ

-- Macro: int EBADFD

-- Macro: int EREMCHG

-- Macro: int ELIBACC

-- Macro: int ELIBBAD

-- Macro: int ELIBSCN

-- Macro: int ELIBMAX

-- Macro: int ELIBEXEC

-- Macro: int ESTRPIPE

-- Macro: int EUCLEAN

-- Macro: int ENOTNAM

-- Macro: int ENAVAIL

-- Macro: int EISNAM

-- Macro: int EREMOTEIO

-- Macro: int ENOMEDIUM

-- Macro: int EMEDIUMTYPE

+ Error Messages 
Previous:  Error Codes , Up:  Error Reporting 




Error Messages

The library has functions and variables designed to make it easy for your program to report informative error messages in the customary format about the failure of a library call. The functions strerror and perror give you the standard error message for a given error code; the variable program_invocation_short_name gives you convenient access to the name of the program that encountered the error.

-- Function: char * strerror (int errnum)

The strerror function maps the error code (see  Checking for Errors ) specified by the errnum argument to a descriptive error message string. The return value is a pointer to this string. 

The value errnum normally comes from the variable errno. 

You should not modify the string returned by strerror. Also, if you make subsequent calls to strerror, the string might be overwritten. (But it's guaranteed that no library function ever calls strerror behind your back.) 

The function strerror is declared in string.h.


-- Function: void perror (const char *message)

This function prints an error message to the stream stderr; see  Standard Streams . The orientation of stderr is not changed. 

If you call perror with a message that is either a null pointer or an empty string, perror just prints the error message corresponding to errno, adding a trailing newline. 

If you supply a non-null message argument, then perror prefixes its output with this string. It adds a colon and a space character to separate the message from the error string corresponding to errno. 

The function perror is declared in stdio.h.

strerror and perror produce the exact same message for any given error code; the precise text varies from system to system. In this system, the messages are fairly short; there are no multi-line messages or embedded newlines. Each error message begins with a capital letter and does not include any terminating punctuation. 


Here is an example showing how to handle failure to open a file correctly. The function open_sesame tries to open the named file for reading and returns a stream if successful. The fopen library function returns a null pointer if it couldn't open the file for some reason. In that situation, open_sesame constructs an appropriate error message using the strerror function, and terminates the program. If we were going to make some other library calls before passing the error code to strerror, we'd have to save it in a local variable instead, because those other library functions might overwrite errno in the meantime.

     #include <errno.h>
     #include <stdio.h>
     #include <stdlib.h>
     #include <string.h>
     
     FILE *
     open_sesame (char *name)
     {
       FILE *stream;
     
       errno = 0;
       stream = fopen (name, "r");
       if (stream == NULL)
         {
           fprintf (stderr, "Couldn't open file %s; %s\n",
                    name, strerror (errno));
           exit (EXIT_FAILURE);
         }
       else
         return stream;
     }


Error Recovery 
Next:  Binary Streams , Previous:  EOF and Errors , Up:  I/O on Streams 




Recovering from errors

You may explicitly clear the error and EOF flags with the clearerr function.

-- Function: void clearerr (FILE *stream)

This function clears the end-of-file and error indicators for the stream stream. 

The file positioning functions (see  File Positioning ) also clear the end-of-file indicator for the stream.

Note that it is not correct to just clear the error flag and retry a failed stream operation. After a failed write, any number of characters since the last buffer flush may have been committed to the file, while some buffered data may have been discarded. Merely retrying can thus cause lost or repeated data. 

A failed read may leave the file pointer in an inappropriate position for a second try. In both cases, you should seek to a known position before retrying. 

Most errors that can happen are not recoverable -- a second try will always fail again in the same way. So usually it is best to give up and report the error to the user, rather than install complicated recovery logic. 


Error Reporting 
Next:  Memory , Previous:  Introduction , Up:  Top 




Error Reporting

Many functions in the C library detect and report error conditions, and sometimes your programs need to check for these error conditions. For example, when you open an input file, you should verify that the file was actually opened correctly, and print an error message or take other appropriate action if the call to the library function failed. 

This chapter describes how the error reporting facility works. Your program should include the header file errno.h to use this facility.

·  Checking for Errors : How errors are reported by library functions.
·  Error Codes : Error code macros; all of these expand into integer constant values.
·  Error Messages : Mapping error codes onto error messages.

Executing a File 
Next:  Consistency Checking , Previous:  Running a Command , Up:  Top 




Executing a File

This section describes the exec family of functions, for executing a file as a process image. You can use these functions to make a child process execute a new program after it has been forked. 

To see the effects of exec from the point of view of the called program, See  Program Basics . 

The functions in this family differ in how you specify the arguments, but otherwise they all do the same thing. They are declared in the header file process.h
.
-- Function: int execv (const char *filename, char *const argv[])

The execv function executes the file named by filename as a new process image. 

The argv argument is an array of null-terminated strings that is used to provide a value for the argv argument to the main function of the program to be executed. The last element of this array must be a null pointer. By convention, the first element of this array is the file name of the program sans directory names. See  Program Arguments , for full details on how programs can access these arguments. 

The environment for the new process image is taken from the environ variable of the current process image; see  Environment Variables , for information about environments.

-- Function: int execl (const char *filename, const char *arg0, ...)

This is similar to execv, but the argv strings are specified individually instead of as an array. A null pointer must be passed as the last such argument.

-- Function: int execve (const char *filename, char *const argv[], char *const env[])

This is similar to execv, but permits you to specify the environment for the new program explicitly as the env argument. This should be an array of strings in the same format as for the environ variable; see  Environment Access .

-- Function: int execle (const char *filename, const char *arg0, char *const env[], ...)

This is similar to execl, but permits you to specify the environment for the new program explicitly. The environment argument is passed following the null pointer that marks the last argv argument, and should be an array of strings in the same format as for the environ variable.

-- Function: int execvp (const char *filename, char *const argv[])

The execvp function is similar to execv, except that it searches the directories listed in the PATH environment variable (see  Standard Environment ) to find the full file name of a file from filename if filename does not contain a slash. 

This function is useful for executing system utility programs, because it looks for them in the places that the user has chosen. Shells use it to run the commands that users type.

-- Function: int execlp (const char *filename, const char *arg0, ...)

This function is like execl, except that it performs the same file name searching as the execvp function.

These functions normally don't return, since execution of a new program causes the currently executing program to go away completely. A value of -1 is returned in the event of a failure. In addition to the usual file name errors (see  File Name Errors ), the following errno error conditions are defined for these functions:

E2BIG
The combined size of the new program's argument list and environment list is larger than ARG_MAX bytes. The GNU system has no specific limit on the argument list size, so this error code cannot result, but you may get ENOMEM instead if the arguments are too big for available memory. 
ENOEXEC
The specified file can't be executed because it isn't in the right format. 
ENOMEM
Executing the specified file requires more storage than is available.

If execution of the new file succeeds, it updates the access time field of the file as if the file had been read. See  File Times , for more details about access times of files. 

The point at which the file is closed again is not specified, but is at some point before the process exits or before another process image is executed. 

Executing a new process image completely changes the contents of memory, copying only the argument and environment strings to new locations.  In this system file descriptors and streams are closed when the current process ends.

Exit Status 
Next:  Cleanups on Exit , Previous:  Normal Termination , Up:  Program Termination 




Exit Status

When a program exits, it can return to the parent process a small amount of information about the cause of termination, using the exit status. This is a value between 0 and 255 that the exiting process passes as an argument to exit. 

Normally you should use the exit status to report very broad information about success or failure. You can't provide a lot of detail about the reasons for the failure, and most parent processes would not want much detail anyway. 

There are conventions for what sorts of status values certain programs should return. The most common convention is simply 0 for success and 1 for failure. Programs that perform comparison use a different convention: they use status 1 to indicate a mismatch, and status 2 to indicate an inability to compare. Your program should follow an existing convention if an existing convention makes sense for it. 

A general convention reserves status values 128 and up for special purposes. In particular, the value 128 is used to indicate failure to execute another program in a subprocess. This convention is not universally obeyed, but it is a good idea to follow it in your programs. 

Warning: Don't try to use the number of errors as the exit status. This is actually not very useful; a parent process would generally not care how many errors occurred. Worse than that, it does not work, because the status value is truncated to eight bits. Thus, if the program tried to report 256 errors, the parent would receive a report of 0 errors--that is, success. 

For the same reason, it does not work to use the value of errno as the exit status--these can exceed 255. 

Portability note: Some non-POSIX systems use different conventions for exit status values. For greater portability, you can use the macros EXIT_SUCCESS and EXIT_FAILURE for the conventional status value for success and failure, respectively. They are declared in the file stdlib.h.

-- Macro: int EXIT_SUCCESS

This macro can be used with the exit function to indicate successful program completion. 

On POSIX systems, the value of this macro is 0. On other systems, the value might be some other (possibly non-constant) integer expression.

-- Macro: int EXIT_FAILURE

This macro can be used with the exit function to indicate unsuccessful program completion in a general sense. 

On POSIX systems, the value of this macro is 1. On other systems, the value might be some other (possibly non-constant) integer expression. Other nonzero status values also indicate failures. Certain programs use different nonzero status values to indicate particular kinds of "non-success". For example, diff uses status value 1 to mean that the files are different, and 2 or more to mean that there was difficulty in opening the files.

Don't confuse a program's exit status with a process' termination status. There are lots of ways a process can terminate besides having it's program finish. In the event that the process termination is caused by program termination (i.e. exit), though, the program's exit status becomes part of the process' termination status.

Exponents and Logarithms 
Next:  Hyperbolic Functions , Previous:  Inverse Trig Functions , Up:  Mathematics 




Exponentiation and Logarithms

-- Function: double exp (double x)

-- Function: float expf (float x)

-- Function: long double expl (long double x)

These functions compute e (the base of natural logarithms) raised to the power x. 

If the magnitude of the result is too large to be representable, exp signals overflow.

-- Function: double exp2 (double x)

-- Function: float exp2f (float x)

-- Function: long double exp2l (long double x)

These functions compute 2 raised to the power x. Mathematically, exp2 (x) is the same as exp (x * log (2)).

-- Function: double exp10 (double x)

-- Function: float exp10f (float x)

-- Function: long double exp10l (long double x)

-- Function: double pow10 (double x)

-- Function: float pow10f (float x)

-- Function: long double pow10l (long double x)

These functions compute 10 raised to the power x. Mathematically, exp10 (x) is the same as exp (x * log (10)). 

These functions are GNU extensions. The name exp10 is preferred, since it is analogous to exp and exp2.

-- Function: double log (double x)

-- Function: float logf (float x)

-- Function: long double logl (long double x)

These functions compute the natural logarithm of x. exp (log (x)) equals x, exactly in mathematics and approximately in C. 

If x is negative, log signals a domain error. If x is zero, it returns negative infinity; if x is too close to zero, it may signal overflow.

-- Function: double log10 (double x)

-- Function: float log10f (float x)

-- Function: long double log10l (long double x)

These functions return the base-10 logarithm of x. log10 (x) equals log (x) / log (10).

-- Function: double log2 (double x)

-- Function: float log2f (float x)

-- Function: long double log2l (long double x)

These functions return the base-2 logarithm of x. log2 (x) equals log (x) / log (2).

-- Function: double logb (double x)

-- Function: float logbf (float x)

-- Function: long double logbl (long double x)

These functions extract the exponent of x and return it as a floating-point value. If FLT_RADIX is two, logb is equal to floor (log2 (x)), except it's probably faster. 

If x is de-normalized, logb returns the exponent x would have if it were normalized. If x is infinity (positive or negative), logb returns &infin;. If x is zero, logb returns &infin;. It does not signal.

-- Function: int ilogb (double x)

-- Function: int ilogbf (float x)

-- Function: int ilogbl (long double x)

These functions are equivalent to the corresponding logb functions except that they return signed integer values.

Since integers cannot represent infinity and NaN, ilogb instead returns an integer that can't be the exponent of a normal floating-point number. math.h defines constants so you can check for this.
-- Macro: int FP_ILOGB0

ilogb returns this value if its argument is 0. The numeric value is either INT_MIN or -INT_MAX. 

This macro is defined in ISO C99.

-- Macro: int FP_ILOGBNAN

ilogb returns this value if its argument is NaN. The numeric value is either INT_MIN or INT_MAX. 

This macro is defined in ISO C99.

These values are system specific. They might even be the same. The proper way to test the result of ilogb is as follows:

     i = ilogb (f);
     if (i == FP_ILOGB0 || i == FP_ILOGBNAN)
       {
         if (isnan (f))
           {
             /* Handle NaN.  */
           }
         else if (f  == 0.0)
           {
             /* Handle 0.0.  */
           }
         else
           {
             /* Some other value with large exponent,
                perhaps +Inf.  */
           }
       }

-- Function: double pow (double base, double power)

-- Function: float powf (float base, float power)

-- Function: long double powl (long double base, long double power)

These are general exponentiation functions, returning base raised to power. 

Mathematically, pow would return a complex number when base is negative and power is not an integral value. pow can't do that, so instead it signals a domain error. pow may also underflow or overflow the destination type.

-- Function: double sqrt (double x)

-- Function: float sqrtf (float x)

-- Function: long double sqrtl (long double x)

These functions return the nonnegative square root of x. 

If x is negative, sqrt signals a domain error. Mathematically, it should return a complex number.

-- Function: double cbrt (double x)

-- Function: float cbrtf (float x)

-- Function: long double cbrtl (long double x)

These functions return the cube root of x. They cannot fail; every representable real value has a representable real cube root.

-- Function: double hypot (double x, double y)

-- Function: float hypotf (float x, float y)

-- Function: long double hypotl (long double x, long double y)

These functions return sqrt (x*x + y*y). This is the length of the hypotenuse of a right triangle with sides of length x and y, or the distance of the point (x, y) from the origin. Using this function instead of the direct formula is wise, since the error is much smaller. See also the function cabs in  Absolute Value .

-- Function: double expm1 (double x)

-- Function: float expm1f (float x)

-- Function: long double expm1l (long double x)

These functions return a value equivalent to exp (x) - 1. They are computed in a way that is accurate even if x is near zero--a case where exp (x) - 1 would be inaccurate owing to subtraction of two numbers that are nearly equal.

-- Function: double log1p (double x)

-- Function: float log1pf (float x)

-- Function: long double log1pl (long double x)

These functions returns a value equivalent to log (1 + x). They are computed in a way that is accurate even if x is near zero.

ISO C99 defines complex variants of some of the exponentiation and logarithm functions.
-- Function: complex double cexp (complex double z)

-- Function: complex float cexpf (complex float z)

-- Function: complex long double cexpl (complex long double z)

These functions return e (the base of natural logarithms) raised to the power of z. Mathematically, this corresponds to the value 

exp (z) = exp (creal (z)) * (cos (cimag (z)) + I * sin (cimag (z)))

-- Function: complex double clog (complex double z)

-- Function: complex float clogf (complex float z)

-- Function: complex long double clogl (complex long double z)

These functions return the natural logarithm of z. Mathematically, this corresponds to the value 

log (z) = log (cabs (z)) + I * carg (z) 

clog has a pole at 0, and will signal overflow if z equals or is very close to 0. It is well-defined for all other values of z.

-- Function: complex double clog10 (complex double z)

-- Function: complex float clog10f (complex float z)

-- Function: complex long double clog10l (complex long double z)

These functions return the base 10 logarithm of the complex value z. Mathematically, this corresponds to the value 

log (z) = log10 (cabs (z)) + I * carg (z) 

These functions are GNU extensions.

-- Function: complex double csqrt (complex double z)

-- Function: complex float csqrtf (complex float z)

-- Function: complex long double csqrtl (complex long double z)

These functions return the complex square root of the argument z. Unlike the real-valued functions, they are defined for all values of z.

-- Function: complex double cpow (complex double base, complex double power)

-- Function: complex float cpowf (complex float base, complex float power)

-- Function: complex long double cpowl (complex long double base, complex long double power)

These functions return base raised to the power of power. This is equivalent to cexp (y * clog (x))

Extended Char Intro 
Next:  Charset Function Overview , Up:  Character Set Handling 




Introduction to Extended Characters

A variety of solutions is available to overcome the differences between character sets with a 1:1 relation between bytes and characters and character sets with ratios of 2:1 or 4:1. The remainder of this section gives a few examples to help understand the design decisions made while developing the functionality of the C library. 

A distinction we have to make right away is between internal and external representation. Internal representation means the representation used by a program while keeping the text in memory. External representations are used when text is stored or transmitted through some communication channel. Examples of external representations include files waiting in a directory to be read and parsed. 

Traditionally there has been no difference between the two representations. It was equally comfortable and useful to use the same single-byte representation internally and externally. This comfort level decreases with more and larger character sets. 

One of the problems to overcome with the internal representation is handling text that is externally encoded using different character sets. Assume a program that reads two texts and compares them using some metric. The comparison can be usefully done only if the texts are internally kept in a common format. 

For such a common format (= character set) eight bits are certainly no longer enough. So the smallest entity will have to grow: wide characters will now be used. Instead of one byte per character, two or four will be used instead. (Three are not good to address in memory and more than four bytes seem not to be necessary). 

As shown in some other part of this manual, a completely new family has been created of functions that can handle wide character texts in memory. The most commonly used character sets for such internal wide character representations are Unicode and ISO 10646 (also known as UCS for Universal Character Set). Unicode was originally planned as a 16-bit character set; whereas, ISO 10646 was designed to be a 31-bit large code space. The two standards are practically identical. They have the same character repertoire and code table, but Unicode specifies added semantics. At the moment, only characters in the first 0x10000 code positions (the so-called Basic Multilingual Plane, BMP) have been assigned, but the assignment of more specialized characters outside this 16-bit space is already in progress. A number of encodings have been defined for Unicode and ISO 10646 characters: UCS-2 is a 16-bit word that can only represent characters from the BMP, UCS-4 is a 32-bit word than can represent any Unicode and ISO 10646 character, UTF-8 is an ASCII compatible encoding where ASCII characters are represented by ASCII bytes and non-ASCII characters by sequences of 2-6 non-ASCII bytes, and finally UTF-16 is an extension of UCS-2 in which pairs of certain UCS-2 words can be used to encode non-BMP characters up to 0x10ffff. 

To represent wide characters the char type is not suitable. For this reason the ISO C standard introduces a new type that is designed to keep one character of a wide character string. To maintain the similarity there is also a type corresponding to int for those functions that take a single wide character.

-- Data type: wchar_t

This data type is used as the base type for wide character strings. In other words, arrays of objects of this type are the equivalent of char[] for multibyte character strings. The type is defined in stddef.h. 

The ISO C90 standard, where wchar_t was introduced, does not say anything specific about the representation. It only requires that this type is capable of storing all elements of the basic character set. Therefore it would be legitimate to define wchar_t as char, which might make sense for embedded systems. 

In this system wchar_t is always 16 bits wide and UTF-16 encoding with surrogate characters is used.

-- Data type: wint_t

wint_t is a data type used for parameters and variables that contain a single wide character. As the name suggests this type is the equivalent of int when using the normal char strings. The types wchar_t and wint_t often have the same representation if their size is 32 bits wide but in this system wchar_t is defined as short,  and the type wint_t is be defined as int due to the parameter promotion. 

This type is defined in wchar.h and was introduced in Amendment 1 to ISO C90.

As there are for the char data type macros are available for specifying the minimum and maximum value representable in an object of type wchar_t.

-- Macro: wint_t WCHAR_MIN

The macro WCHAR_MIN evaluates to the minimum value representable by an object of type wint_t. 

This macro was introduced in Amendment 1 to ISO C90.

-- Macro: wint_t WCHAR_MAX

The macro WCHAR_MAX evaluates to the maximum value representable by an object of type wint_t. 

This macro was introduced in Amendment 1 to ISO C90.

Another special wide character value is the equivalent to EOF.

-- Macro: wint_t WEOF

The macro WEOF evaluates to a constant expression of type wint_t whose value is different from any member of the extended character set. 

WEOF need not be the same value as EOF and unlike EOF it also need not be negative. In other words, sloppy code like 

          {
            int c;
            ...
            while ((c = getc (fp)) < 0)
              ...
          }
     
has to be rewritten to use WEOF explicitly when wide characters are used: 

          {
            wint_t c;
            ...
            while ((c = wgetc (fp)) != WEOF)
              ...
          }
     
This macro was introduced in Amendment 1 to ISO C90 and is defined in wchar.h.

These internal representations present problems when it comes to storing and transmittal. Because each single wide character consists of more than one byte, they are effected by byte-ordering. Thus, machines with different endianesses would see different values when accessing the same data. This byte ordering concern also applies for communication protocols that are all byte-based and, thereforet require that the sender has to decide about splitting the wide character in bytes. A last (but not least important) point is that wide characters often require more storage space than a customized byte-oriented character set. 

For all the above reasons, an external encoding that is different from the internal encoding is often used if the latter is UCS-2 or UCS-4. The external encoding is byte-based and can be chosen appropriately for the environment and for the texts to be handled. A variety of different character sets can be used for this external encoding (information that will not be exhaustively presented here-instead, a description of the major groups will suffice). All of the ASCII-based character sets fulfill one requirement: they are "filesystem safe." This means that the character '/' is used in the encoding only to represent itself. Things are a bit different for character sets like EBCDIC (Extended Binary Coded Decimal Interchange Code, a character set family used by IBM), but if the operation system does not understand EBCDIC directly the parameters-to-system calls have to be converted first anyhow.

· The simplest character sets are single-byte character sets. There can be only up to 256 characters (for 8 bit character sets), which is not sufficient to cover all languages but might be sufficient to handle a specific text. Handling of a 8 bit character sets is simple. This is not true for other kinds presented later, and therefore, the application one uses might require the use of 8 bit character sets. 

· The ISO 2022 standard defines a mechanism for extended character sets where one character can be represented by more than one byte. This is achieved by associating a state with the text. Characters that can be used to change the state can be embedded in the text. Each byte in the text might have a different interpretation in each state. The state might even influence whether a given byte stands for a character on its own or whether it has to be combined with some more bytes. 

In most uses of ISO 2022 the defined character sets do not allow state changes that cover more than the next character. This has the big advantage that whenever one can identify the beginning of the byte sequence of a character one can interpret a text correctly. Examples of character sets using this policy are the various EUC character sets (used by Sun's operations systems, EUC-JP, EUC-KR, EUC-TW, and EUC-CN) or Shift_JIS (SJIS, a Japanese encoding). 

But there are also character sets using a state that is valid for more than one character and has to be changed by another byte sequence. Examples for this are ISO-2022-JP, ISO-2022-KR, and ISO-2022-CN. 
· Early attempts to fix 8 bit character sets for other languages using the Roman alphabet lead to character sets like ISO 6937. Here bytes representing characters like the acute accent do not produce output themselves: one has to combine them with other characters to get the desired result. For example, the byte sequence 0xc2 0x61 (non-spacing acute accent, followed by lower-case `a') to get the "small a with acute" character. To get the acute accent character on its own, one has to write 0xc2 0x20 (the non-spacing acute followed by a space). 

Character sets like ISO 6937 are used in some embedded systems such as teletex. 
· Instead of converting the Unicode or ISO 10646 text used internally, it is often also sufficient to simply use an encoding different than UCS-2/UCS-4. The Unicode and ISO 10646 standards even specify such an encoding: UTF-8. This encoding is able to represent all of ISO 10646 31 bits in a byte string of length one to six. 

There were a few other attempts to encode ISO 10646 such as UTF-7, but UTF-8 is today the only encoding that should be used. In fact, with any luck UTF-8 will soon be the only external encoding that has to be supported. It proves to be universally usable and its only disadvantage is that it favors Roman languages by making the byte string representation of other scripts (Cyrillic, Greek, Asian scripts) longer than necessary if using a specific character set for these scripts. Methods like the Unicode compression scheme can alleviate these problems.

The question remaining is: how to select the character set or encoding to use. The answer: you cannot decide about it yourself, it is decided by the developers of the system or the majority of the users. Since the goal is interoperability one has to use whatever the other people one works with use. If there are no constraints, the selection is based on the requirements the expected circle of users will have. In other words, if a project is expected to be used in only, say, Russia it is fine to use KOI8-R or a similar character set. But if at the same time people from, say, Greece are participating one should use a character set that allows all people to collaborate. 

The most widely useful solution seems to be: go with the most general character set, namely ISO 10646. Use UTF-8 as the external encoding and problems about users not being able to use their own language adequately are a thing of the past. 

One final comment about the choice of the wide character representation is necessary at this point. We have said above that the natural choice is using Unicode or ISO 10646. This is not required, but at least encouraged, by the ISO C standard. The standard defines at least a macro __STDC_ISO_10646__ that is only defined on systems where the wchar_t type encodes ISO 10646 characters. If this symbol is not defined one should avoid making assumptions about the wide character representation. If the programmer uses only the functions provided by the C library to handle wide character strings there should be no compatibility problems with other systems.

File Name Errors 
Previous:  File Name Resolution , Up:  File Names 




File Name Errors

Functions that accept file name arguments usually detect these errno error conditions relating to the file name syntax or trouble finding the named file. These errors are referred to throughout this manual as the usual file name errors.

EACCES
The process does not have search permission for a directory component of the file name. 
ENAMETOOLONG
This error is used when either the total length of a file name is greater than PATH_MAX, or when an individual file name component has a length greater than NAME_MAX.

In the GNU system, there is no imposed limit on overall file name length, but some file systems may place limits on the length of a component. 
ENOENT
This error is reported when a file referenced as a directory component in the file name doesn't exist.

ENOTDIR
A file that is referenced as a directory component in the file name exists, but it isn't a directory. 

File Name Resolution 
Next:  File Name Errors , Previous:  Directories , Up:  File Names 




File Name Resolution

A file name consists of file name components separated by slash (`\') characters.

The process of determining what file a file name refers to is called file name resolution. This is performed by examining the components that make up a file name in left-to-right order, and locating each successive component in the directory named by the previous component. Of course, each of the files that are referenced as directories must actually exist, be directories instead of regular files, and have the appropriate permissions to be accessible by the process; otherwise the file name resolution fails. 

If a file name begins with a letter followed by a colon, the first component is located on the specified drive.  

If the file name begins with a slash '\' the first component is located in the root of the current drive.  Such a file name is called an absolute file name. 

Otherwise, the first component in the file name is located in the current working directory (see  Working Directory ). This kind of file name is called a relative file name. 

The file name components . ("dot") and .. ("dot-dot") have special meanings. Every directory has entries for these file name components. The file name component . refers to the directory itself, while the file name component .. refers to its parent directory (the directory that contains the link for the directory in question). As a special case, .. in the root directory refers to the root directory itself, since it has no parent; thus /.. is the same as /. 

Here are some examples of file names:

\a
The file named a, in the root directory of the current drive. 
c:\a
The file named a, int the root directory of the drive C
\a\b
The file named b, in the directory named a in the root directory of the current drive. 
c:\a\b
The file named b, in the directory named a in the root directory of drive C. 
a
The file named a, in the current working directory. 
\a\.\b
This is the same as /a/b. 
.\a
The file named a, in the current working directory. 
..\a
The file named a, in the parent directory of the current working directory.

A file name that names a directory may optionally end in a `\'. You can specify a file name of \ to refer to the root directory, but the empty string is not a meaningful file name. If you want to refer to the current working directory, use a file name of . or .\. 

File names may also include support for file types, specified by extensions to file names.  File types occur at the end of a file name, and are preceded by a dot.  For example:

C:\a.c

Is the C language source file a.c, located in the root directory of drive C.

File Names 
Previous:  I/O Concepts , Up:  I/O Overview 




File Names

In order to open a connection to a file, or to perform other operations such as deleting a file, you need some way to refer to the file. Nearly all files have names that are strings--even files which are actually devices such as tape drives or terminals. These strings are called file names. You specify the file name to say which file you want to open or operate on. 

This section describes the conventions for file names and how the operating system works with them.

·  Directories : Directories contain entries for files.
·  File Name Resolution : A file name specifies how to look up a file.
·  File Name Errors : Error conditions relating to file names.
File Position Primitive 
Next:  Descriptors and Streams , Previous:  I/O Primitives , Up:  Low-Level I/O 




Setting the File Position of a Descriptor

Just as you can set the file position of a stream with fseek, you can set the file position of a descriptor with lseek. This specifies the position in the file for the next read or write operation. See  File Positioning , for more information on the file position and what it means. 

To read the current file position value from a descriptor, use lseek (desc, 0, SEEK_CUR).

-- Function: off_t lseek (int filedes, off_t offset, int whence)

The lseek function is used to change the file position of the file with descriptor filedes. 

The whence argument specifies how the offset should be interpreted, in the same way as for the fseek function, and it must be one of the symbolic constants SEEK_SET, SEEK_CUR, or SEEK_END.

SEEK_SET
Specifies that whence is a count of characters from the beginning of the file. 
SEEK_CUR
Specifies that whence is a count of characters from the current file position. This count may be positive or negative. 
SEEK_END
Specifies that whence is a count of characters from the end of the file. A negative count specifies a position within the current extent of the file; a positive count specifies a position past the current end. If you set the position past the current end, and actually write data, you will extend the file with zeros up to that position.

The return value from lseek is normally the resulting file position, measured in bytes from the beginning of the file. You can use this feature together with SEEK_CUR to read the current file position. 

If you want to append to the file, setting the file position to the current end of file with SEEK_END is not sufficient. Another process may write more data after you seek but before you write, extending the file so the position you write onto clobbers their data. Instead, use the O_APPEND operating mode; see  Operating Modes . 

You can set the file position past the current end of the file. This does not by itself make the file longer; lseek never changes the file. But subsequent output at that position will extend the file. Characters between the previous end of file and the new position are filled with zeros. Extending the file in this way can create a "hole": the blocks of zeros are not actually allocated on disk, so the file takes up less space than it appears to; it is then called a "sparse file". If the file position cannot be changed, or the operation is in some way invalid, lseek returns a value of -1. The following errno error conditions are defined for this function:

EBADF
The filedes is not a valid file descriptor. 
EINVAL
The whence argument value is not valid, or the resulting file offset is not valid. A file offset is invalid. 
ESPIPE
The filedes corresponds to an object that cannot be positioned, such as a pipe, FIFO or terminal device. (POSIX.1 specifies this error only for pipes and FIFOs, but in the GNU system, you always get ESPIPE if the object is not seekable.)

You can have multiple descriptors for the same file if you open the file more than once, or if you duplicate a descriptor with dup. Descriptors that come from separate calls to open have independent file positions; using lseek on one descriptor has no effect on the other. For example,

     {
       int d1, d2;
       char buf[4];
       d1 = open ("foo", O_RDONLY);
       d2 = open ("foo", O_RDONLY);
       lseek (d1, 1024, SEEK_SET);
       read (d2, buf, 4);
     }

will read the first four characters of the file foo. (The error-checking code necessary for a real program has been omitted here for brevity.) 

By contrast, descriptors made by duplication share a common file position with the original descriptor that was duplicated. Anything which alters the file position of one of the duplicates, including reading or writing data, affects all of them alike. Thus, for example,

     {
       int d1, d2, d3;
       char buf1[4], buf2[4];
       d1 = open ("foo", O_RDONLY);
       d2 = dup (d1);
       d3 = dup (d2);
       lseek (d3, 1024, SEEK_SET);
       read (d1, buf1, 4);
       read (d2, buf2, 4);
     }

will read four characters starting with the 1024'th character of foo, and then four more characters starting with the 1028'th character.
File Position 
Previous:  Streams and File Descriptors , Up:  I/O Concepts 




File Position

One of the attributes of an open file is its file position that keeps track of where in the file the next character is to be read or written. In this system, and all POSIX.1 systems, the file position is simply an integer representing the number of bytes from the beginning of the file. 

The file position is normally set to the beginning of the file when it is opened, and each time a character is read or written, the file position is incremented. In other words, access to the file is normally sequential. Ordinary files permit read or write operations at any position within the file. Some other kinds of files may also permit this. Files which do permit this are sometimes referred to as random-access files. You can change the file position using the fseek function on a stream (see  File Positioning ) or the lseek function on a file descriptor (see  I/O Primitives ). If you try to change the file position on a file that doesn't support random access, you get the ESPIPE error. Streams and descriptors that are opened for append access are treated specially for output: output to such files is always appended sequentially to the end of the file, regardless of the file position. However, the file position is still used to control where in the file reading is done. If you think about it, you'll realize that several programs can read a given file at the same time. In order for each program to be able to read the file at its own pace, each program must have its own file pointer, which is not affected by anything the other programs do. 

In fact, each opening of a file creates a separate file position. Thus, if you open a file twice even in the same program, you get two streams or descriptors with independent file positions. 

By contrast, if you open a descriptor and then duplicate it to get another descriptor, these two descriptors share the same file position: changing the file position of one descriptor will affect the other.

File Positioning 
Next:  Portable Positioning , Previous:  Binary Streams , Up:  I/O on Streams 




File Positioning

The file position of a stream describes where in the file the stream is currently reading or writing. I/O on the stream advances the file position through the file. In this system, the file position is represented as an integer, which counts the number of bytes from the beginning of the file. See  File Position . 

During I/O to an ordinary disk file, you can change the file position whenever you wish, so as to read or write any portion of the file. Some other kinds of files may also permit this. Files which support changing the file position are sometimes referred to as random-access files. 

You can use the functions in this section to examine or modify the file position indicator associated with a stream. The symbols listed below are declared in the header file stdio.h.

-- Function: long int ftell (FILE *stream)

This function returns the current file position of the stream stream. 

This function can fail if the stream doesn't support file positioning, or if the file position can't be represented in a long int, and possibly for other reasons as well. If a failure occurs, a value of -1 is returned.

-- Function: int fseek (FILE *stream, long int offset, int whence)

The fseek function is used to change the file position of the stream stream. The value of whence must be one of the constants SEEK_SET, SEEK_CUR, or SEEK_END, to indicate whether the offset is relative to the beginning of the file, the current file position, or the end of the file, respectively. 

This function returns a value of zero if the operation was successful, and a nonzero value to indicate failure. A successful call also clears the end-of-file indicator of stream and discards any characters that were "pushed back" by the use of ungetc. 

fseek either flushes any buffered output before setting the file position or else remembers it so it will be written later in its proper place in the file.


Portability Note: In this system, ftell, and fseek work reliably only on binary streams. See  Binary Streams . 

The following symbolic constants are defined for use as the whence argument to fseek. They are also used with the lseek function (see  I/O Primitives ).

-- Macro: int SEEK_SET

This is an integer constant which, when used as the whence argument to the fseek or fseeko function, specifies that the offset provided is relative to the beginning of the file.

-- Macro: int SEEK_CUR

This is an integer constant which, when used as the whence argument to the fseek or fseeko function, specifies that the offset provided is relative to the current file position.

-- Macro: int SEEK_END

This is an integer constant which, when used as the whence argument to the fseek or fseeko function, specifies that the offset provided is relative to the end of the file.

-- Function: void rewind (FILE *stream)

The rewind function positions the stream stream at the beginning of the file. It is equivalent to calling fseek or fseek on the stream with an offset argument of 0L and a whence argument of SEEK_SET, except that the return value is discarded and the error indicator for the stream is reset.

File Size 
Previous:  Temporary Files , Up:  File System Interface 




File Size

Normally file sizes are maintained automatically. A file begins with a size of 0 and is automatically extended when data is written past its end. It is also possible to empty a file completely by an open or fopen call. 

However, sometimes it is necessary to reduce the size of a file. This can be done with the truncate and ftruncate functions. They were introduced in BSD Unix. ftruncate was later added to POSIX.1. 

Some systems allow you to extend a file (creating holes) with these functions. 

Using these functions on anything other than a regular file gives undefined results. On many systems, such a call will appear to succeed, without actually accomplishing anything.
-- Function: int truncate (const char *filename, off_t length)

The truncate function changes the size of filename to length. If length is shorter than the previous length, data at the end will be lost. The file must be writable by the user to perform this operation. 

If length is longer, holes will be added to the end. However, some systems do not support this feature and will leave the file unchanged. 

When the source file is compiled with _FILE_OFFSET_BITS == 64 the truncate function is in fact truncate64 and the type off_t has 64 bits which makes it possible to handle files up to 2^63 bytes in length. 

The return value is 0 for success, or -1 for an error. In addition to the usual file name errors, the following errors may occur:

EACCES
The file is a directory or not writable. 
EINVAL
length is negative. 
EFBIG
The operation would extend the file beyond the limits of the operating system. 
EIO
A hardware I/O error occurred. 
EPERM
The file is "append-only" or "immutable". 
EINTR
The operation was interrupted by a signal.

-- Function: int truncate64 (const char *name, off64_t length)

This function is similar to the truncate function. The difference is that the length argument is 64 bits wide even on 32 bits machines, which allows the handling of files with sizes up to 2^63 bytes. 

When the source file is compiled with _FILE_OFFSET_BITS == 64 on a 32 bits machine this function is actually available under the name truncate and so transparently replaces the 32 bits interface.

-- Function: int ftruncate (int fd, off_t length)

This is like truncate, but it works on a file descriptor fd for an opened file instead of a file name to identify the object. The file must be opened for writing to successfully carry out the operation. 

The POSIX standard leaves it implementation defined what happens if the specified new length of the file is bigger than the original size. The ftruncate function might simply leave the file alone and do nothing or it can increase the size to the desired size. In this later case the extended area should be zero-filled. So using ftruncate is no reliable way to increase the file size but if it is possible it is probably the fastest way. The function also operates on POSIX shared memory segments if these are implemented by the system. 

ftruncate is especially useful in combination with mmap. Since the mapped region must have a fixed size one cannot enlarge the file by writing something beyond the last mapped page. Instead one has to enlarge the file itself and then remap the file with the new size. The example below shows how this works. 

When the source file is compiled with _FILE_OFFSET_BITS == 64 the ftruncate function is in fact ftruncate64 and the type off_t has 64 bits which makes it possible to handle files up to 2^63 bytes in length. 

The return value is 0 for success, or -1 for an error. The following errors may occur:

EBADF
fd does not correspond to an open file. 
EACCES
fd is a directory or not open for writing. 
EINVAL
length is negative. 
EFBIG
The operation would extend the file beyond the limits of the operating system. 
EIO
A hardware I/O error occurred. 
EPERM
The file is "append-only" or "immutable". 
EINTR
The operation was interrupted by a signal.

-- Function: int ftruncate64 (int id, off64_t length)

This function is similar to the ftruncate function. The difference is that the length argument is 64 bits wide even on 32 bits machines which allows the handling of files with sizes up to 2^63 bytes. 

When the source file is compiled with _FILE_OFFSET_BITS == 64 on a 32 bits machine this function is actually available under the name ftruncate and so transparently replaces the 32 bits interface.

As announced here is a little example of how to use ftruncate in combination with mmap:

     int fd;
     void *start;
     size_t len;
     
     int
     add (off_t at, void *block, size_t size)
     {
       if (at + size > len)
         {
           /* Resize the file and remap.  */
           size_t ps = sysconf (_SC_PAGESIZE);
           size_t ns = (at + size + ps - 1) & ~(ps - 1);
           void *np;
           if (ftruncate (fd, ns) < 0)
             return -1;
           np = mmap (NULL, ns, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
           if (np == MAP_FAILED)
             return -1;
           start = np;
           len = ns;
         }
       memcpy ((char *) start + at, block, size);
       return 0;
     }

The function add writes a block of memory at an arbitrary position in the file. If the current size of the file is too small it is extended. Note the it is extended by a round number of pages. This is a requirement of mmap. The program has to keep track of the real size, and when it has finished a final ftruncate call should set the real size of the file.

File Status Flags 
Next:  Access Modes ,  Previous:  Duplicating Descriptors , Up:  Low-Level I/O 




File Status Flags

File status flags are used to specify attributes of the opening of a file. The file status flags are shared by duplicated file descriptors resulting from a single opening of the file. The file status flags are specified with the flags argument to open; see  Opening and Closing Files . 

File status flags fall into three categories, which are described in the following sections.

·  Access Modes , specify what type of access is allowed to the file: reading, writing, or both. They are set by open, but cannot be changed. 
·  Open-time Flags , control details of what open will do. These flags are not preserved after the open call. 
·  Operating Modes , affect how operations such as read and write are done. They are set by open.

The symbols in this section are defined in the header file fcntl.h.

File System Interface 
Next:  Working Directory , Previous:  Low-Level I/O , Up:  Top 




File System Interface

This chapter describes the C library's functions for manipulating files. Unlike the input and output functions (see  I/O on Streams ; see  Low-Level I/O ), these functions are concerned with operating on the files themselves rather than on their contents. 

Among the facilities described in this chapter are functions for examining or modifying directories, functions for renaming and deleting files, and functions for examining and setting file attributes such as access permissions and modification times.

·  Working Directory : This is used to resolve relative file names.
·  Deleting Files : How to delete a file, and what that means.
·  Renaming Files : Changing a file's name.
·  Creating Directories : A system call just for creating a directory.
·  Temporary Files : Naming and creating temporary files.
· File Size: Size of files.
Finding Tokens in a String 
Previous:  Search Functions , Up:  String and Array Utilities 




Finding Tokens in a String

It's fairly common for programs to have a need to do some simple kinds of lexical analysis and parsing, such as splitting a command string up into tokens. You can do this with the strtok function, declared in the header file string.h.

-- Function: char * strtok (char *restrict newstring, const char *restrict delimiters)

A string can be split into tokens by making a series of calls to the function strtok. 

The string to be split up is passed as the newstring argument on the first call only. The strtok function uses this to set up some internal state information. Subsequent calls to get additional tokens from the same string are indicated by passing a null pointer as the newstring argument. Calling strtok with another non-null newstring argument reinitializes the state information. It is guaranteed that no other library function ever calls strtok behind your back (which would mess up this internal state information). 

The delimiters argument is a string that specifies a set of delimiters that may surround the token being extracted. All the initial characters that are members of this set are discarded. The first character that is not a member of this set of delimiters marks the beginning of the next token. The end of the token is found by looking for the next character that is a member of the delimiter set. This character in the original string newstring is overwritten by a null character, and the pointer to the beginning of the token in newstring is returned. 

On the next call to strtok, the searching begins at the next character beyond the one that marked the end of the previous token. Note that the set of delimiters delimiters do not have to be the same on every call in a series of calls to strtok. 

If the end of the string newstring is reached, or if the remainder of string consists only of delimiter characters, strtok returns a null pointer. 

Note that "character" is here used in the sense of byte. In a string using a multibyte character encoding (abstract) character consisting of more than one byte are not treated as an entity. Each byte is treated separately. The function is not locale-dependent. 

Note that "character" is here used in the sense of byte. In a string using a multibyte character encoding (abstract) character consisting of more than one byte are not treated as an entity. Each byte is treated separately. The function is not locale-dependent.

-- Function: wchar_t * wcstok (wchar_t *newstring, const char *delimiters)

A string can be split into tokens by making a series of calls to the function wcstok. 

The string to be split up is passed as the newstring argument on the first call only. The wcstok function uses this to set up some internal state information. Subsequent calls to get additional tokens from the same wide character string are indicated by passing a null pointer as the newstring argument. Calling wcstok with another non-null newstring argument reinitializes the state information. It is guaranteed that no other library function ever calls wcstok behind your back (which would mess up this internal state information). 

The delimiters argument is a wide character string that specifies a set of delimiters that may surround the token being extracted. All the initial wide characters that are members of this set are discarded. The first wide character that is not a member of this set of delimiters marks the beginning of the next token. The end of the token is found by looking for the next wide character that is a member of the delimiter set. This wide character in the original wide character string newstring is overwritten by a null wide character, and the pointer to the beginning of the token in newstring is returned. 

On the next call to wcstok, the searching begins at the next wide character beyond the one that marked the end of the previous token. Note that the set of delimiters delimiters do not have to be the same on every call in a series of calls to wcstok. 

If the end of the wide character string newstring is reached, or if the remainder of string consists only of delimiter wide characters, wcstok returns a null pointer. 

Note that "character" is here used in the sense of byte. In a string using a multibyte character encoding (abstract) character consisting of more than one byte are not treated as an entity. Each byte is treated separately. The function is not locale-dependent.

Warning: Since strtok and wcstok alter the string they is parsing, you should always copy the string to a temporary buffer before parsing it with strtok/wcstok (see  Copying and Concatenation ). If you allow strtok or wcstok to modify a string that came from another part of your program, you are asking for trouble; that string might be used for other purposes after strtok or wcstok has modified it, and it would not have the expected value. 

The string that you are operating on might even be a constant. Then when strtok or wcstok tries to modify it, your program will get a fatal signal for writing in read-only memory. See  Program Error Signals . Even if the operation of strtok or wcstok would not require a modification of the string (e.g., if there is exactly one token) the string can (and in the GNU libc case will) be modified. 

This is a special case of a general principle: if a part of a program does not have as its purpose the modification of a certain data structure, then it is error-prone to modify the data structure temporarily. 

The functions strtok and wcstok are not reentrant. See  Nonreentrancy , for a discussion of where and why reentrancy is important. 

Here is a simple example showing the use of strtok.

     #include <string.h>
     #include <stddef.h>
     
     ...
     
     const char string[] = "words separated by spaces -- and, punctuation!";
     const char delimiters[] = " .,;:!-";
     char *token, *cp;
     
     ...
     
     cp = strdup (string);                 /* Make writable copy.  */
     token = strtok (cp, delimiters);      /* token => "words" */
     token = strtok (NULL, delimiters);    /* token => "separated" */
     token = strtok (NULL, delimiters);    /* token => "by" */
     token = strtok (NULL, delimiters);    /* token => "spaces" */
     token = strtok (NULL, delimiters);    /* token => "and" */
     token = strtok (NULL, delimiters);    /* token => "punctuation" */
     token = strtok (NULL, delimiters);    /* token => NULL */
     free(cp);                             /* free the copy */
Floating Point Classes 
Next:  Floating Point Errors , Previous:  Floating Point Numbers , Up:  Arithmetic 




Floating-Point Number Classification Functions

ISO C99 defines macros that let you determine what sort of floating-point number a variable holds.

-- Macro: int fpclassify (float-type x)

This is a generic macro which works on all floating-point types and which returns a value of type int. The possible values are:

FP_NAN
The floating-point number x is "Not a Number" (see  Infinity and NaN )
FP_INFINITE
The value of x is either plus or minus infinity (see  Infinity and NaN )
FP_ZERO
The value of x is zero. In floating-point formats like IEEE 754, where zero can be signed, this value is also returned if x is negative zero.
FP_SUBNORMAL
Numbers whose absolute value is too small to be represented in the normal format are represented in an alternate, denormalized format (see  Floating Point Concepts ). This format is less precise but can represent values closer to zero. fpclassify returns this value for values of x in this alternate format.
FP_NORMAL
This value is returned for all other values of x. It indicates that there is nothing special about the number.

fpclassify is most useful if more than one property of a number must be tested. There are more specific macros which only test one property at a time. Generally these macros execute faster than fpclassify, since there is special hardware support for them. You should therefore use the specific macros whenever possible.

-- Macro: int isfinite (float-type x)

This macro returns a nonzero value if x is finite: not plus or minus infinity, and not NaN. It is equivalent to 

          (fpclassify (x) != FP_NAN && fpclassify (x) != FP_INFINITE)
     
isfinite is implemented as a macro which accepts any floating-point type.

-- Macro: int isnormal (float-type x)

This macro returns a nonzero value if x is finite and normalized. It is equivalent to 

          (fpclassify (x) == FP_NORMAL)
     
-- Macro: int isnan (float-type x)

This macro returns a nonzero value if x is NaN. It is equivalent to 

          (fpclassify (x) == FP_NAN)
     

Floating Point Concepts 
Next:  Floating Point Parameters , Up:  Floating Type Macros 




Floating Point Representation Concepts

This section introduces the terminology for describing floating point representations. 

You are probably already familiar with most of these concepts in terms of scientific or exponential notation for floating point numbers. For example, the number 123456.0 could be expressed in exponential notation as 1.23456e+05, a shorthand notation indicating that the mantissa 1.23456 is multiplied by the base 10 raised to power 5. 

More formally, the internal representation of a floating point number can be characterized in terms of the following parameters:

· The sign is either -1 or 1. 
· The base or radix for exponentiation, an integer greater than 1. This is a constant for a particular representation. 
· The exponent to which the base is raised. The upper and lower bounds of the exponent value are constants for a particular representation. 

Sometimes, in the actual bits representing the floating point number, the exponent is biased by adding a constant to it, to make it always be represented as an unsigned quantity. This is only important if you have some reason to pick apart the bit fields making up the floating point number by hand, which is something for which the C library provides no support. So this is ignored in the discussion that follows. 
· The mantissa or significand is an unsigned integer which is a part of each floating point number. 
· The precision of the mantissa. If the base of the representation is b, then the precision is the number of base-b digits in the mantissa. This is a constant for a particular representation. 

Many floating point representations have an implicit hidden bit in the mantissa. This is a bit which is present virtually in the mantissa, but not stored in memory because its value is always 1 in a normalized number. The precision figure (see above) includes any hidden bits. 

Again, the C library provides no facilities for dealing with such low-level aspects of the representation.

The mantissa of a floating point number represents an implicit fraction whose denominator is the base raised to the power of the precision. Since the largest representable mantissa is one less than this denominator, the value of the fraction is always strictly less than 1. The mathematical value of a floating point number is then the product of this fraction, the sign, and the base raised to the exponent. 

We say that the floating point number is normalized if the fraction is at least 1/b, where b is the base. In other words, the mantissa would be too large to fit if it were multiplied by the base. Non-normalized numbers are sometimes called denormal; they contain less precision than the representation normally can hold. 

If the number is not normalized, then you can subtract 1 from the exponent while multiplying the mantissa by the base, and get another floating point number with the same value. Normalization consists of doing this repeatedly until the number is normalized. Two distinct normalized floating point numbers cannot be equal in value. 

(There is an exception to this rule: if the mantissa is zero, it is considered normalized. Another exception happens on certain machines where the exponent is as small as the representation can hold. Then it is impossible to subtract 1 from the exponent, so a number may be normalized even if its fraction is less than 1/b.)

 Floating Point Errors 
Next:  Rounding , Previous:  Floating Point Classes , Up:  Arithmetic 




Errors in Floating-Point Calculations

·  FP Exceptions : IEEE 754 math exceptions and how to detect them.
·  Infinity and NaN : Special values returned by calculations.
·  Status bit operations : Checking for exceptions after the fact.
·  Math Error Reporting : How the math functions report errors.

Floating Point Numbers 
Next:  Floating Point Classes , Previous:  Integer Division , Up:  Arithmetic 




Floating Point Numbers

Most computer hardware has support for two different kinds of numbers: integers (...-3, -2, -1, 0, 1, 2, 3...) and floating-point numbers. Floating-point numbers have three parts: the mantissa, the exponent, and the sign bit. The real number represented by a floating-point value is given by (s ? -1 : 1) * 2^e * M where s is the sign bit, e the exponent, and M the mantissa. See  Floating Point Concepts , for details. (It is possible to have a different base for the exponent, but all modern hardware uses 2.) 

Floating-point numbers can represent a finite subset of the real numbers. While this subset is large enough for most purposes, it is important to remember that the only reals that can be represented exactly are rational numbers that have a terminating binary expansion shorter than the width of the mantissa. Even simple fractions such as 1/5 can only be approximated by floating point. 

Mathematical operations and functions frequently need to produce values that are not representable. Often these values can be approximated closely enough for practical purposes, but sometimes they can't. Historically there was no way to tell when the results of a calculation were inaccurate. Modern computers implement the IEEE 754 standard for numerical computations, which defines a framework for indicating to the program when the results of calculation are not trustworthy. This framework consists of a set of exceptions that indicate why a result could not be represented, and the special values infinity and not a number (NaN).

Floating Point Parameters 
Next:  IEEE Floating Point , Previous:  Floating Point Concepts , Up:  Floating Type Macros 




Floating Point Parameters

These macro definitions can be accessed by including the header file float.h in your program. 

Macro names starting with `FLT_' refer to the float type, while names beginning with `DBL_' refer to the double type and names beginning with `LDBL_' refer to the long double type. 

Of these macros, only FLT_RADIX is guaranteed to be a constant expression. The other macros listed here cannot be reliably used in places that require constant expressions, such as `#if' preprocessing directives or in the dimensions of static arrays. 

FLT_ROUNDS
This value characterizes the rounding mode for floating point addition. The following values indicate standard rounding modes:

-1
The mode is indeterminable.
0
Rounding is towards zero.
1
Rounding is to the nearest number.
2
Rounding is towards positive infinity.
3
Rounding is towards negative infinity.

Any other value represents a machine-dependent nonstandard rounding mode. 

On most machines, the value is 1, in accordance with the IEEE standard for floating point. 

Here is a table showing how certain values round for each possible value of FLT_ROUNDS, if the other aspects of the representation match the IEEE single-precision standard. 

                          0      1             2             3
           1.00000003    1.0    1.0           1.00000012    1.0
           1.00000007    1.0    1.00000012    1.00000012    1.0
          -1.00000003   -1.0   -1.0          -1.0          -1.00000012
          -1.00000007   -1.0   -1.00000012   -1.0          -1.00000012
     
FLT_RADIX
This is the value of the base, or radix, of the exponent representation. This is guaranteed to be a constant expression, unlike the other macros described in this section. The value is 2.
FLT_MANT_DIG
This is the number of base-FLT_RADIX digits in the floating point mantissa for the float data type. The following expression yields 1.0 (even though mathematically it should not) due to the limited number of mantissa digits: 

          float radix = FLT_RADIX;
          
          1.0f + 1.0f / radix / radix / ... / radix
     
where radix appears FLT_MANT_DIG times.
DBL_MANT_DIG
LDBL_MANT_DIG
This is the number of base-FLT_RADIX digits in the floating point mantissa for the data types double and long double, respectively.
FLT_DIG
This is the number of decimal digits of precision for the float data type. Technically, if p and b are the precision and base (respectively) for the representation, then the decimal precision q is the maximum number of decimal digits such that any floating point number with q base 10 digits can be rounded to a floating point number with p base b digits and back again, without change to the q decimal digits. 

The value of this macro is supposed to be at least 6, to satisfy ISO C.
DBL_DIG
LDBL_DIG
These are similar to FLT_DIG, but for the data types double and long double, respectively. The values of these macros are supposed to be at least 10.
FLT_MIN_EXP
This is the smallest possible exponent value for type float. More precisely, is the minimum negative integer such that the value FLT_RADIX raised to this power minus 1 can be represented as a normalized floating point number of type float.
DBL_MIN_EXP
LDBL_MIN_EXP
These are similar to FLT_MIN_EXP, but for the data types double and long double, respectively.
FLT_MIN_10_EXP
This is the minimum negative integer such that 10 raised to this power minus 1 can be represented as a normalized floating point number of type float. This is supposed to be -37 or even less.
DBL_MIN_10_EXP
LDBL_MIN_10_EXP
These are similar to FLT_MIN_10_EXP, but for the data types double and long double, respectively.
FLT_MAX_EXP
This is the largest possible exponent value for type float. More precisely, this is the maximum positive integer such that value FLT_RADIX raised to this power minus 1 can be represented as a floating point number of type float.
DBL_MAX_EXP
LDBL_MAX_EXP
These are similar to FLT_MAX_EXP, but for the data types double and long double, respectively.
FLT_MAX_10_EXP
This is the maximum positive integer such that 10 raised to this power minus 1 can be represented as a normalized floating point number of type float. This is supposed to be at least 37.
DBL_MAX_10_EXP
LDBL_MAX_10_EXP
These are similar to FLT_MAX_10_EXP, but for the data types double and long double, respectively.
FLT_MAX
The value of this macro is the maximum number representable in type float. It is supposed to be at least 1E+37. The value has type float. 

The smallest representable number is - FLT_MAX.
DBL_MAX
LDBL_MAX
These are similar to FLT_MAX, but for the data types double and long double, respectively. The type of the macro's value is the same as the type it describes.
FLT_MIN
The value of this macro is the minimum normalized positive floating point number that is representable in type float. It is supposed to be no more than 1E-37.
DBL_MIN
LDBL_MIN
These are similar to FLT_MIN, but for the data types double and long double, respectively. The type of the macro's value is the same as the type it describes.
FLT_EPSILON
This is the maximum positive floating point number of type float such that 1.0 + FLT_EPSILON != 1.0 is true. It's supposed to be no greater than 1E-5.
DBL_EPSILON
LDBL_EPSILON
These are similar to FLT_EPSILON, but for the data types double and long double, respectively. The type of the macro's value is the same as the type it describes. The values are not supposed to be greater than 1E-9.

Floating Type Macros 
Next:  Structure Measurement , Previous:  Range of Type , Up:  Data Type Measurements 




Floating Type Macros

The specific representation of floating point numbers varies from machine to machine. Because floating point numbers are represented internally as approximate quantities, algorithms for manipulating floating point data often need to take account of the precise details of the machine's floating point representation. 

Some of the functions in the C library itself need this information; for example, the algorithms for printing and reading floating point numbers (see  I/O on Streams ) and for calculating trigonometric and irrational functions (see  Mathematics ) use it to avoid round-off error and loss of accuracy. User programs that implement numerical analysis techniques also often need this information in order to minimize or compute error bounds. 

The header file float.h describes the format used by your machine.

·  Floating Point Concepts : Definitions of terminology.
·  Floating Point Parameters : Details of specific macros.
·  IEEE Floating Point : The measurements for one common representation.

+ Floating-Point Conversions 
Next:  Other Output Conversions , Previous:  Integer Conversions , Up:  Formatted Output 




Floating-Point Conversions

This section discusses the conversion specifications for floating-point numbers: the `%f', `%e', `%E', `%g', and `%G' conversions. 

The `%f' conversion prints its argument in fixed-point notation, producing output of the form [-]ddd.ddd, where the number of digits following the decimal point is controlled by the precision you specify. 

The `%e' conversion prints its argument in exponential notation, producing output of the form [-]d.ddde[+|-]dd. Again, the number of digits following the decimal point is controlled by the precision. The exponent always contains at least two digits. The `%E' conversion is similar but the exponent is marked with the letter `E' instead of `e'. 

The `%g' and `%G' conversions print the argument in the style of `%e' or `%E' (respectively) if the exponent would be less than -4 or greater than or equal to the precision; otherwise they use the `%f' style. A precision of 0, is taken as 1. is Trailing zeros are removed from the fractional portion of the result and a decimal-point character appears only if it is followed by a digit. 

The `%a' and `%A' conversions are meant for representing floating-point numbers exactly in textual form so that they can be exchanged as texts between different programs and/or machines. The numbers are represented is the form [-]0xh.hhhp[+|-]dd. At the left of the decimal-point character exactly one digit is print. This character is only 0 if the number is denormalized. Otherwise the value is unspecified; it is implementation dependent how many bits are used. The number of hexadecimal digits on the right side of the decimal-point character is equal to the precision. If the precision is zero it is determined to be large enough to provide an exact representation of the number (or it is large enough to distinguish two adjacent values if the FLT_RADIX is not a power of 2, see  Floating Point Parameters ). For the `%a' conversion lower-case characters are used to represent the hexadecimal number and the prefix and exponent sign are printed as 0x and p respectively. Otherwise upper-case characters are used and 0X and P are used for the representation of prefix and exponent string. The exponent to the base of two is printed as a decimal number using at least one digit but at most as many digits as necessary to represent the value exactly. 

If the value to be printed represents infinity or a NaN, the output is [-]inf or nan respectively if the conversion specifier is `%a', `%e', `%f', or `%g' and it is [-]INF or NAN respectively if the conversion is `%A', `%E', or `%G'. 

The following flags can be used to modify the behavior:

`-'
Left-justify the result in the field. Normally the result is right-justified. 
`+'
Always include a plus or minus sign in the result. 
` '
If the result doesn't start with a plus or minus sign, prefix it with a space instead. Since the `+' flag ensures that the result includes a sign, this flag is ignored if you supply both of them. 
`#'
Specifies that the result should always include a decimal point, even if no digits follow it. For the `%g' and `%G' conversions, this also forces trailing zeros after the decimal point to be left in place where they would otherwise be removed. 
`''
Separate the digits of the integer part of the result into groups as specified by the locale specified for the LC_NUMERIC category; see  General Numeric . This flag is a GNU extension. 
`0'
Pad the field with zeros instead of spaces; the zeros are placed after any sign. This flag is ignored if the `-' flag is also specified.

The precision specifies how many digits follow the decimal-point character for the `%f', `%e', and `%E' conversions. For these conversions, the default precision is 6. If the precision is explicitly 0, this suppresses the decimal point character entirely. For the `%g' and `%G' conversions, the precision specifies how many significant digits to print. Significant digits are the first digit before the decimal point, and all the digits after it. If the precision is 0 or not specified for `%g' or `%G', it is treated like a value of 1. If the value being printed cannot be expressed accurately in the specified number of digits, the value is rounded to the nearest number that fits. 

Without a type modifier, the floating-point conversions use an argument of type double. (By the default argument promotions, any float arguments are automatically converted to double.) The following type modifier is supported:

`L'
An uppercase `L' specifies that the argument is a long double.

Here are some examples showing how numbers print using the various floating-point conversions. All of the numbers were printed using this template string:

     "|%13.4a|%13.4f|%13.4e|%13.4g|\n"

Here is the output:

     |  0x0.0000p+0|       0.0000|   0.0000e+00|            0|
     |  0x1.0000p-1|       0.5000|   5.0000e-01|          0.5|
     |  0x1.0000p+0|       1.0000|   1.0000e+00|            1|
     | -0x1.0000p+0|      -1.0000|  -1.0000e+00|           -1|
     |  0x1.9000p+6|     100.0000|   1.0000e+02|          100|
     |  0x1.f400p+9|    1000.0000|   1.0000e+03|         1000|
     | 0x1.3880p+13|   10000.0000|   1.0000e+04|        1e+04|
     | 0x1.81c8p+13|   12345.0000|   1.2345e+04|    1.234e+04|
     | 0x1.86a0p+16|  100000.0000|   1.0000e+05|        1e+05|
     | 0x1.e240p+16|  123456.0000|   1.2346e+05|    1.235e+05|

Notice how the `%g' conversion drops trailing zeros.

Flushing Buffers 
Next:  Controlling Buffering , Previous:  Buffering Concepts , Up:  Stream Buffering 




Flushing Buffers

Flushing output on a buffered stream means transmitting all accumulated characters to the file. There are many circumstances when buffered output on a stream is flushed automatically:

· When you try to do output and the output buffer is full. 
· When the stream is closed. See  Closing Streams . 
· When the program terminates by calling exit. See  Normal Termination . 
· When a newline is written, if the stream is line buffered. 
· Whenever an input operation on a console stream actually reads data from its file.

If you want to flush the buffered output at another time, call fflush, which is declared in the header file stdio.h.

-- Function: int fflush (FILE *stream)

This function causes any buffered output on stream to be delivered to the file. If stream is a null pointer, then fflush causes buffered output on all open output streams to be flushed. 

This function returns EOF if a write error occurs, or zero otherwise.


Formatted Input Basics 
Next:  Input Conversion Syntax , Up:  Formatted Input 




Formatted Input Basics

Calls to scanf are superficially similar to calls to printf in that arbitrary arguments are read under the control of a template string. While the syntax of the conversion specifications in the template is very similar to that for printf, the interpretation of the template is oriented more towards free-format input and simple pattern matching, rather than fixed-field formatting. For example, most scanf conversions skip over any amount of "white space" (including spaces, tabs, and newlines) in the input file, and there is no concept of precision for the numeric input conversions as there is for the corresponding output conversions. Ordinarily, non-whitespace characters in the template are expected to match characters in the input stream exactly, but a matching failure is distinct from an input error on the stream. Another area of difference between scanf and printf is that you must remember to supply pointers rather than immediate values as the optional arguments to scanf; the values that are read are stored in the objects that the pointers point to. Even experienced programmers tend to forget this occasionally, so if your program is getting strange errors that seem to be related to scanf, you might want to double-check this. 

When a matching failure occurs, scanf returns immediately, leaving the first non-matching character as the next character to be read from the stream. The normal return value from scanf is the number of values that were assigned, so you can use this to determine if a matching error happened before all the expected values were read. The scanf function is typically used for things like reading in the contents of tables. For example, here is a function that uses scanf to initialize an array of double:

     void
     readarray (double *array, int n)
     {
       int i;
       for (i=0; i<n; i++)
         if (scanf (" %lf", &(array[i])) != 1)
           invalid_input_error ();
     }

The formatted input functions are not used as frequently as the formatted output functions. Partly, this is because it takes some care to use them properly. Another reason is that it is difficult to recover from a matching error. 

+ Formatted Input Functions 
Next:  Variable Arguments Input , Previous:  Other Input Conversions , Up:  Formatted Input 




Formatted Input Functions

Here are the descriptions of the functions for performing formatted input. Prototypes for these functions are in the header file stdio.h.

-- Function: int scanf (const char *template, ...)

The scanf function reads formatted input from the stream stdin under the control of the template string template. The optional arguments are pointers to the places which receive the resulting values. 

The return value is normally the number of successful assignments. If an end-of-file condition is detected before any matches are performed, including matches against whitespace and literal characters in the template, then EOF is returned.

-- Function: int wscanf (const wchar_t *template, ...)

The wscanf function reads formatted input from the stream stdin under the control of the template string template. The optional arguments are pointers to the places which receive the resulting values. 

The return value is normally the number of successful assignments. If an end-of-file condition is detected before any matches are performed, including matches against whitespace and literal characters in the template, then WEOF is returned.

-- Function: int fscanf (FILE *stream, const char *template, ...)

This function is just like scanf, except that the input is read from the stream stream instead of stdin.

-- Function: int fwscanf (FILE *stream, const wchar_t *template, ...)

This function is just like wscanf, except that the input is read from the stream stream instead of stdin.

-- Function: int sscanf (const char *s, const char *template, ...)

This is like scanf, except that the characters are taken from the null-terminated string s instead of from a stream. Reaching the end of the string is treated as an end-of-file condition. 

The behavior of this function is undefined if copying takes place between objects that overlap--for example, if s is also given as an argument to receive a string read under control of the `%s', `%S', or `%[' conversion.

-- Function: int swscanf (const wchar_t *ws, const char *template, ...)

This is like wscanf, except that the characters are taken from the null-terminated string ws instead of from a stream. Reaching the end of the string is treated as an end-of-file condition. 

The behavior of this function is undefined if copying takes place between objects that overlap--for example, if ws is also given as an argument to receive a string read under control of the `%s', `%S', or `%[' conversion.

Formatted Input 
Next:  EOF and Errors , Previous:  Variable Arguments Input , Up:  I/O on Streams 




Formatted Input

The functions described in this section (scanf and related functions) provide facilities for formatted input analogous to the formatted output facilities. These functions provide a mechanism for reading arbitrary values under the control of a format string or template string.

·  Formatted Input Basics : Some basics to get you started.
·  Input Conversion Syntax : Syntax of conversion specifications.
·  Table of Input Conversions : Summary of input conversions and what they do.
·  Numeric Input Conversions : Details of conversions for reading numbers.
·  String Input Conversions : Details of conversions for reading strings.
·  Other Input Conversions : Details of miscellaneous other conversions.
·  Formatted Input Functions : Descriptions of the actual functions.
·  Variable Arguments Input : vscanf and friends.

Formatted Output Basics 
Next:  Output Conversion Syntax , Up:  Formatted Output 




Formatted Output Basics

The printf function can be used to print any number of arguments. The template string argument you supply in a call provides information not only about the number of additional arguments, but also about their types and what style should be used for printing them. 

Ordinary characters in the template string are simply written to the output stream as-is, while conversion specifications introduced by a `%' character in the template cause subsequent arguments to be formatted and written to the output stream. For example,

     int pct = 37;
     char filename[] = "foo.txt";
     printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n",
             filename, pct);

produces output like

     Processing of `foo.txt' is 37% finished.
     Please be patient.

This example shows the use of the `%d' conversion to specify that an int argument should be printed in decimal notation, the `%s' conversion to specify printing of a string argument, and the `%%' conversion to print a literal `%' character. 

There are also conversions for printing an integer argument as an unsigned value in octal, decimal, or hexadecimal radix (`%o', `%u', or `%x', respectively); or as a character value (`%c'). 

Floating-point numbers can be printed in normal, fixed-point notation using the `%f' conversion or in exponential notation using the `%e' conversion. The `%g' conversion uses either `%e' or `%f' format, depending on what is more appropriate for the magnitude of the particular number. 

You can control formatting more precisely by writing modifiers between the `%' and the character that indicates which conversion to apply. These slightly alter the ordinary behavior of the conversion. For example, most conversion specifications permit you to specify a minimum field width and a flag indicating whether you want the result left- or right-justified within the field. 

The specific flags and modifiers that are permitted and their interpretation vary depending on the particular conversion. They're all described in more detail in the following sections. Don't worry if this all seems excessively complicated at first; you can almost always get reasonable free-format output without using any of the modifiers at all. The modifiers are mostly used to make the output look "prettier" in tables.

Formatted Output Functions 
Next:  Dynamic Output , Previous:  Other Output Conversions , Up:  Formatted Output 




Formatted Output Functions

This section describes how to call printf and related functions. Prototypes for these functions are in the header file stdio.h. Because these functions take a variable number of arguments, you must declare prototypes for them before using them. Of course, the easiest way to make sure you have all the right prototypes is to just include stdio.h.

-- Function: int printf (const char *template, ...)

The printf function prints the optional arguments under the control of the template string template to the stream stdout. It returns the number of characters printed, or a negative value if there was an output error.

-- Function: int wprintf (const wchar_t *template, ...)

The wprintf function prints the optional arguments under the control of the wide template string template to the stream stdout. It returns the number of wide characters printed, or a negative value if there was an output error.

-- Function: int fprintf (FILE *stream, const char *template, ...)

This function is just like printf, except that the output is written to the stream stream instead of stdout.

-- Function: int fwprintf (FILE *stream, const wchar_t *template, ...)

This function is just like wprintf, except that the output is written to the stream stream instead of stdout.

-- Function: int sprintf (char *s, const char *template, ...)

This is like printf, except that the output is stored in the character array s instead of written to a stream. A null character is written to mark the end of the string. 

The sprintf function returns the number of characters stored in the array s, not including the terminating null character. 

The behavior of this function is undefined if copying takes place between objects that overlap--for example, if s is also given as an argument to be printed under control of the `%s' conversion. See  Copying and Concatenation . 

Warning: The sprintf function can be dangerous because it can potentially output more characters than can fit in the allocation size of the string s. Remember that the field width given in a conversion specification is only a minimum value. 

To avoid this problem, you can use snprintf or asprintf, described below.

-- Function: int swprintf (wchar_t *s, size_t size, const wchar_t *template, ...)

This is like wprintf, except that the output is stored in the wide character array ws instead of written to a stream. A null wide character is written to mark the end of the string. The size argument specifies the maximum number of characters to produce. The trailing null character is counted towards this limit, so you should allocate at least size wide characters for the string ws. 

The return value is the number of characters generated for the given input, excluding the trailing null. If not all output fits into the provided buffer a negative value is returned. You should try again with a bigger output string. Note: this is different from how snprintf handles this situation. 

Note that the corresponding narrow stream function takes fewer parameters. swprintf in fact corresponds to the snprintf function. Since the sprintf function can be dangerous and should be avoided the ISO C committee refused to make the same mistake again and decided to not define an function exactly corresponding to sprintf.

-- Function: int snprintf (char *s, size_t size, const char *template, ...)

The snprintf function is similar to sprintf, except that the size argument specifies the maximum number of characters to produce. The trailing null character is counted towards this limit, so you should allocate at least size characters for the string s. 

The return value is the number of characters which would be generated for the given input, excluding the trailing null. If this value is greater or equal to size, not all characters from the result have been stored in s. You should try again with a bigger output string. Here is an example of doing this: 

          /* Construct a message describing the value of a variable
             whose name is name and whose value is value. */
          char *
          make_message (char *name, char *value)
          {
            /* Guess we need no more than 100 chars of space. */
            int size = 100;
            char *buffer = (char *) xmalloc (size);
            int nchars;
            if (buffer == NULL)
              return NULL;
          
           /* Try to print in the allocated space. */
            nchars = snprintf (buffer, size, "value of %s is %s",
                               name, value);
            if (nchars >= size)
              {
                /* Reallocate buffer now that we know
                   how much space is needed. */
                buffer = (char *) xrealloc (buffer, nchars + 1);
          
                if (buffer != NULL)
                  /* Try again. */
                  snprintf (buffer, size, "value of %s is %s",
                            name, value);
              }
            /* The last call worked, return the string. */
            return buffer;
          }
     
Formatted Output 
Next:  Customizing Printf , Previous:  Block Input/Output , Up:  I/O on Streams 




Formatted Output

The functions described in this section (printf and related functions) provide a convenient way to perform formatted output. You call printf with a format string or template string that specifies how to format the values of the remaining arguments. 

Unless your program is a filter that specifically performs line- or character-oriented processing, using printf or one of the other related functions described in this section is usually the easiest and most concise way to perform output. These functions are especially useful for printing error messages, tables of data, and the like.

·  Formatted Output Basics : Some examples to get you started.
·  Output Conversion Syntax : General syntax of conversion specifications.
·  Table of Output Conversions : Summary of output conversions and what they do.
·  Integer Conversions : Details about formatting of integers.
·  Floating-Point Conversions : Details about formatting of floating-point numbers.
·  Other Output Conversions : Details about formatting of strings, characters, pointers, and the like.
·  Formatted Output Functions : Descriptions of the actual functions.
·  Variable Arguments Output : vprintf and friends.
Formatting Calendar Time 
Next:  TZ Variable , Previous:  Broken-down Time , Up:  Calendar Time 




Formatting Calendar Time

The functions described in this section format calendar time values as strings. These functions are declared in the header file time.h.

-- Function: char * asctime (const struct tm *brokentime)

The asctime function converts the broken-down time value that brokentime points to into a string in a standard format: 

          "Tue May 21 13:46:22 1991\n"
     
The abbreviations for the days of week are: `Sun', `Mon', `Tue', `Wed', `Thu', `Fri', and `Sat'. 

The abbreviations for the months are: `Jan', `Feb', `Mar', `Apr', `May', `Jun', `Jul', `Aug', `Sep', `Oct', `Nov', and `Dec'. 

The return value points to a statically allocated string, which might be overwritten by subsequent calls to asctime or ctime. (But no other library function overwrites the contents of this string.)

-- Function: char * ctime (const time_t *time)

The ctime function is similar to asctime, except that you specify the calendar time argument as a time_t simple time value rather than in broken-down local time format. It is equivalent to 

          asctime (localtime (time))
     
ctime sets the variable tzname, because localtime does so. See  Time Zone Functions .

-- Function: size_t strftime (char *s, size_t size, const char *template, const struct tm *brokentime)

This function is similar to the sprintf function (see  Formatted Input ), but the conversion specifications that can appear in the format template template are specialized for printing components of the date and time brokentime according to the locale currently specified for time conversion (see  Locales ). 

Ordinary characters appearing in the template are copied to the output string s; this can include multibyte character sequences. Conversion specifiers are introduced by a `%' character, followed by an optional flag which can be one of the following. These flags are all GNU extensions. The first three affect only the output of numbers:

_
The number is padded with spaces. 
-
The number is not padded at all. 
0
The number is padded with zeros even if the format specifies padding with spaces. 
^
The output uses uppercase characters, but only if this is possible (see  Case Conversion ).

The default action is to pad the number with zeros to keep it a constant width. Numbers that do not have a range indicated below are never padded, since there is no natural width for them. 

Following the flag an optional specification of the width is possible. This is specified in decimal notation. If the natural size of the output is of the field has less than the specified number of characters, the result is written right adjusted and space padded to the given size. 

An optional modifier can follow the optional flag and width specification. The modifiers, which are POSIX.2 extensions, are:

E
Use the locale's alternate representation for date and time. This modifier applies to the %c, %C, %x, %X, %y and %Y format specifiers. In a Japanese locale, for example, %Ex might yield a date format based on the Japanese Emperors' reigns. 
O
Use the locale's alternate numeric symbols for numbers. This modifier applies only to numeric format specifiers.

If the format supports the modifier but no alternate representation is available, it is ignored. 

The conversion specifier ends with a format specifier taken from the following list. The whole `%' sequence is replaced in the output string as follows:

%a
The abbreviated weekday name according to the current locale. 
%A
The full weekday name according to the current locale. 
%b
The abbreviated month name according to the current locale. 
%B
The full month name according to the current locale. 
%c
The preferred calendar time representation for the current locale. 
%C
The century of the year. This is equivalent to the greatest integer not greater than the year divided by 100. 

This format is a POSIX.2 extension and also appears in ISO C99. 
%d
The day of the month as a decimal number (range 01 through 31). 
%D
The date using the format %m/%d/%y. 

This format is a POSIX.2 extension and also appears in ISO C99. 
%e
The day of the month like with %d, but padded with blank (range 1 through 31). 

This format is a POSIX.2 extension and also appears in ISO C99. 
%F
The date using the format %Y-%m-%d. This is the form specified in the ISO 8601 standard and is the preferred form for all uses. 

This format is a ISO C99 extension. 
%g
The year corresponding to the ISO week number, but without the century (range 00 through 99). This has the same format and value as %y, except that if the ISO week number (see %V) belongs to the previous or next year, that year is used instead. 

This format was introduced in ISO C99. 
%G
The year corresponding to the ISO week number. This has the same format and value as %Y, except that if the ISO week number (see %V) belongs to the previous or next year, that year is used instead. 

This format was introduced in ISO C99 but was previously available as a GNU extension. 
%h
The abbreviated month name according to the current locale. The action is the same as for %b. 

This format is a POSIX.2 extension and also appears in ISO C99. 
%H
The hour as a decimal number, using a 24-hour clock (range 00 through 23). 
%I
The hour as a decimal number, using a 12-hour clock (range 01 through 12). 
%j
The day of the year as a decimal number (range 001 through 366). 
%k
The hour as a decimal number, using a 24-hour clock like %H, but padded with blank (range 0 through 23). 

This format is a GNU extension. 
%l
The hour as a decimal number, using a 12-hour clock like %I, but padded with blank (range 1 through 12). 

This format is a GNU extension. 
%m
The month as a decimal number (range 01 through 12). 
%M
The minute as a decimal number (range 00 through 59). 
%n
A single `\n' (newline) character. 

This format is a POSIX.2 extension and also appears in ISO C99. 
%p
Either `AM' or `PM', according to the given time value; or the corresponding strings for the current locale. Noon is treated as `PM' and midnight as `AM'. 
%P
Either `am' or `pm', according to the given time value; or the corresponding strings for the current locale, printed in lowercase characters. Noon is treated as `pm' and midnight as `am'. 

This format was introduced in ISO C99 but was previously available as a GNU extension. 
%r
The complete calendar time using the AM/PM format of the current locale. 

This format is a POSIX.2 extension and also appears in ISO C99. 
%R
The hour and minute in decimal numbers using the format %H:%M. 

This format was introduced in ISO C99 but was previously available as a GNU extension. 
%s
The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC. Leap seconds are not counted unless leap second support is available. 

This format is a GNU extension. 
%S
The seconds as a decimal number (range 00 through 60). 
%t
A single `\t' (tabulator) character. 

This format is a POSIX.2 extension and also appears in ISO C99. 
%T
The time of day using decimal numbers using the format %H:%M:%S. 

This format is a POSIX.2 extension. 
%u
The day of the week as a decimal number (range 1 through 7), Monday being 1. 

This format is a POSIX.2 extension and also appears in ISO C99. 
%U
The week number of the current year as a decimal number (range 00 through 53), starting with the first Sunday as the first day of the first week. Days preceding the first Sunday in the year are considered to be in week 00. 
%V
The ISO 8601:1988 week number as a decimal number (range 01 through 53). ISO weeks start with Monday and end with Sunday. Week 01 of a year is the first week which has the majority of its days in that year; this is equivalent to the week containing the year's first Thursday, and it is also equivalent to the week containing January 4. Week 01 of a year can contain days from the previous year. The week before week 01 of a year is the last week (52 or 53) of the previous year even if it contains days from the new year. 

This format is a POSIX.2 extension and also appears in ISO C99. 
%w
The day of the week as a decimal number (range 0 through 6), Sunday being 0. 
%W
The week number of the current year as a decimal number (range 00 through 53), starting with the first Monday as the first day of the first week. All days preceding the first Monday in the year are considered to be in week 00. 
%x
The preferred date representation for the current locale. 
%X
The preferred time of day representation for the current locale. 
%y
The year without a century as a decimal number (range 00 through 99). This is equivalent to the year modulo 100. 
%Y
The year as a decimal number, using the Gregorian calendar. Years before the year 1 are numbered 0, -1, and so on. 
%z
RFC 822/ISO 8601:1988 style numeric time zone (e.g., -0600 or +0100), or nothing if no time zone is determinable. 

This format was introduced in ISO C99 but was previously available as a GNU extension. 

A full RFC 822 timestamp is generated by the format `"%a, %d %b %Y %H:%M:%S %z"' (or the equivalent `"%a, %d %b %Y %T %z"'). 
%Z
The time zone abbreviation (empty if the time zone can't be determined). 
%%
A literal `%' character.

The size parameter can be used to specify the maximum number of characters to be stored in the array s, including the terminating null character. If the formatted time requires more than size characters, strftime returns zero and the contents of the array s are undefined. Otherwise the return value indicates the number of characters placed in the array s, not including the terminating null character. 

Warning: This convention for the return value which is prescribed in ISO C can lead to problems in some situations. For certain format strings and certain locales the output really can be the empty string and this cannot be discovered by testing the return value only. E.g., in most locales the AM/PM time format is not supported (most of the world uses the 24 hour time representation). In such locales "%p" will return the empty string, i.e., the return value is zero. To detect situations like this something similar to the following code should be used: 

          buf[0] = '\1';
          len = strftime (buf, bufsize, format, tp);
          if (len == 0 && buf[0] != '\0')
            {
              /* Something went wrong in the strftime call.  */
              ...
            }
     
If s is a null pointer, strftime does not actually write anything, but instead returns the number of characters it would have written. 

According to POSIX.1 every call to strftime implies a call to tzset. So the contents of the environment variable TZ is examined before any output is produced. 

For an example of strftime, see  Time Functions Example .

-- Function: size_t wcsftime (wchar_t *s, size_t size, const wchar_t *template, const struct tm *brokentime)

The wcsftime function is equivalent to the strftime function with the difference that it operates on wide character strings. The buffer where the result is stored, pointed to by s, must be an array of wide characters. The parameter size which specifies the size of the output buffer gives the number of wide character, not the number of bytes. 

Also the format string template is a wide character string. Since all characters needed to specify the format string are in the basic character set it is portably possible to write format strings in the C source code using the L"..." notation. The parameter brokentime has the same meaning as in the strftime call. 

The wcsftime function supports the same flags, modifiers, and format specifiers as the strftime function. 

The return value of wcsftime is the number of wide characters stored in s. When more characters would have to be written than can be placed in the buffer s the return value is zero, with the same problems indicated in the strftime documentation.

FP Bit Twiddling {keepn}
Next:  FP Comparison Functions , Previous:  Remainder Functions , Up:  Arithmetic Functions 




Setting and modifying single bits of FP values

There are some operations that are too complicated or expensive to perform by hand on floating-point numbers. ISO C99 defines functions to do these operations, which mostly involve changing single bits.

-- Function: double copysign (double x, double y)

-- Function: float copysignf (float x, float y)

-- Function: long double copysignl (long double x, long double y)

These functions return x but with the sign of y. They work even if x or y are NaN or zero. Both of these can carry a sign (although not all implementations support it) and this is one of the few operations that can tell the difference. 

copysign never raises an exception. 

This function is defined in IEC 559 (and the appendix with recommended functions in IEEE 754/IEEE 854).

-- Function: int signbit (float-type x)

signbit is a generic macro which can work on all floating-point types. It returns a nonzero value if the value of x has its sign bit set. 

This is not the same as x < 0.0, because IEEE 754 floating point allows zero to be signed. The comparison -0.0 < 0.0 is false, but signbit (-0.0) will return a nonzero value.

-- Function: double nextafter (double x, double y)

-- Function: float nextafterf (float x, float y)

-- Function: long double nextafterl (long double x, long double y)

The nextafter function returns the next representable neighbor of x in the direction towards y. The size of the step between x and the result depends on the type of the result. If x = y the function simply returns y. If either value is NaN, NaN is returned. Otherwise a value corresponding to the value of the least significant bit in the mantissa is added or subtracted, depending on the direction. nextafter will signal overflow or underflow if the result goes outside of the range of normalized numbers. 

This function is defined in IEC 559 (and the appendix with recommended functions in IEEE 754/IEEE 854).

-- Function: double nexttoward (double x, long double y)

-- Function: float nexttowardf (float x, long double y)

-- Function: long double nexttowardl (long double x, long double y)

These functions are identical to the corresponding versions of nextafter except that their second argument is a long double.

-- Function: double nan (const char *tagp)

-- Function: float nanf (const char *tagp)

-- Function: long double nanl (const char *tagp)

The nan function returns a representation of NaN, provided that NaN is supported by the target platform. nan ("n-char-sequence") is equivalent to strtod ("NAN(n-char-sequence)"). 

The argument tagp is used in an unspecified manner. On IEEE 754 systems, there are many representations of NaN, and tagp selects one. On other systems it may do nothing.

FP Comparison Functions 
Next:  Misc FP Arithmetic , Previous:  FP Bit Twiddling , Up:  Arithmetic Functions 




Floating-Point Comparison Functions

The standard C comparison operators provoke exceptions when one or other of the operands is NaN. For example,

     int v = a < 1.0;

will raise an exception if a is NaN. (This does not happen with == and !=; those merely return false and true, respectively, when NaN is examined.) Frequently this exception is undesirable. ISO C99 therefore defines comparison functions that do not raise exceptions when NaN is examined. All of the functions are implemented as macros which allow their arguments to be of any floating-point type. The macros are guaranteed to evaluate their arguments only once.

-- Macro: int isgreater (real-floating x, real-floating y)

This macro determines whether the argument x is greater than y. It is equivalent to (x) > (y), but no exception is raised if x or y are NaN.

-- Macro: int isgreaterequal (real-floating x, real-floating y)

This macro determines whether the argument x is greater than or equal to y. It is equivalent to (x) >= (y), but no exception is raised if x or y are NaN.

-- Macro: int isless (real-floating x, real-floating y)

This macro determines whether the argument x is less than y. It is equivalent to (x) < (y), but no exception is raised if x or y are NaN.

-- Macro: int islessequal (real-floating x, real-floating y)

This macro determines whether the argument x is less than or equal to y. It is equivalent to (x) <= (y), but no exception is raised if x or y are NaN.

-- Macro: int islessgreater (real-floating x, real-floating y)

This macro determines whether the argument x is less or greater than y. It is equivalent to (x) < (y) || (x) > (y) (although it only evaluates x and y once), but no exception is raised if x or y are NaN. 

This macro is not equivalent to x != y, because that expression is true if x or y are NaN.

-- Macro: int isunordered (real-floating x, real-floating y)

This macro determines whether its arguments are unordered. In other words, it is true if x or y are NaN, and false otherwise.

Not all machines provide hardware support for these operations. On machines that don't, the macros can be very slow. Therefore, you should not use these functions when NaN is not a concern. 

Note: There are no macros isequal or isunequal. They are unnecessary, because the == and != operators do not throw an exception if one or both of the operands are NaN.

FP Exceptions 
Next:  Infinity and NaN , Up:  Floating Point Errors 




FP Exceptions

The IEEE 754 standard defines five exceptions that can occur during a calculation. Each corresponds to a particular sort of error, such as overflow. 

When exceptions occur (when exceptions are raised, in the language of the standard), one of two things can happen. By default the exception is simply noted in the floating-point status word, and the program continues as if nothing had happened. The operation produces a default value, which depends on the exception (see the table below). Your program can check the status word to find out which exceptions happened. 

Alternatively, you can enable traps for exceptions. In that case, when an exception is raised, your program will receive the SIGFPE signal. The default action for this signal is to terminate the program. See  Signal Handling , for how you can change the effect of the signal. 

In the System V math library, the user-defined function matherr is called when certain exceptions occur inside math library functions. However, the Unix98 standard deprecates this interface. We support it for historical compatibility, but recommend that you do not use it in new programs.

The exceptions defined in IEEE 754 are:

`Invalid Operation'
This exception is raised if the given operands are invalid for the operation to be performed. Examples are (see IEEE 754, section 7):

1. Addition or subtraction: &infin; - &infin;. (But &infin; + &infin; = &infin;).
2. Multiplication: 0 &middot; &infin;.
3. Division: 0/0 or &infin;/&infin;.
4. Remainder: x REM y, where y is zero or x is infinite.
5. Square root if the operand is less then zero. More generally, any mathematical function evaluated outside its domain produces this exception.
6. Conversion of a floating-point number to an integer or decimal string, when the number cannot be represented in the target format (due to overflow, infinity, or NaN).
7. Conversion of an unrecognizable input string.
8. Comparison via predicates involving < or >, when one or other of the operands is NaN. You can prevent this exception by using the unordered comparison functions instead; see  FP Comparison Functions .

If the exception does not trap, the result of the operation is NaN. 
`Division by Zero'
This exception is raised when a finite nonzero number is divided by zero. If no trap occurs the result is either +&infin; or -&infin;, depending on the signs of the operands. 
`Overflow'
This exception is raised whenever the result cannot be represented as a finite value in the precision format of the destination. If no trap occurs the result depends on the sign of the intermediate result and the current rounding mode (IEEE 754, section 7.3):

1. Round to nearest carries all overflows to &infin; with the sign of the intermediate result.
2. Round toward 0 carries all overflows to the largest representable finite number with the sign of the intermediate result.
3. Round toward -&infin; carries positive overflows to the largest representable finite number and negative overflows to -&infin;. 
4. Round toward &infin; carries negative overflows to the most negative representable finite number and positive overflows to &infin;.

Whenever the overflow exception is raised, the inexact exception is also raised. 
`Underflow'
The underflow exception is raised when an intermediate result is too small to be calculated accurately, or if the operation's result rounded to the destination precision is too small to be normalized. 

When no trap is installed for the underflow exception, underflow is signaled (via the underflow flag) only when both tininess and loss of accuracy have been detected. If no trap handler is installed the operation continues with an imprecise small value, or zero if the destination precision cannot hold the small exact result. 
`Inexact'
This exception is signalled if a rounded result is not exact (such as when calculating the square root of two) or a result overflows without an overflow trap.

Free Manuals 
Next:  Copying , Previous:  Language Features , Up:  Top 




Appendix F Free Software Needs Free Documentation

The biggest deficiency in the free software community today is not in the software--it is the lack of good free documentation that we can include with the free software. Many of our most important programs do not come with free reference manuals and free introductory texts. Documentation is an essential part of any software package; when an important free software package does not come with a free manual and a free tutorial, that is a major gap. We have many such gaps today. 

Consider Perl, for instance. The tutorial manuals that people normally use are non-free. How did this come about? Because the authors of those manuals published them with restrictive terms--no copying, no modification, source files not available--which exclude them from the free software world. 

That wasn't the first time this sort of thing happened, and it was far from the last. Many times we have heard a GNU user eagerly describe a manual that he is writing, his intended contribution to the community, only to learn that he had ruined everything by signing a publication contract to make it non-free. 

Free documentation, like free software, is a matter of freedom, not price. The problem with the non-free manual is not that publishers charge a price for printed copies--that in itself is fine. (The Free Software Foundation sells printed copies of manuals, too.) The problem is the restrictions on the use of the manual. Free manuals are available in source code form, and give you permission to copy and modify. Non-free manuals do not allow this. 

The criteria of freedom for a free manual are roughly the same as for free software. Redistribution (including the normal kinds of commercial redistribution) must be permitted, so that the manual can accompany every copy of the program, both on-line and on paper. 

Permission for modification of the technical content is crucial too. When people modify the software, adding or changing features, if they are conscientious they will change the manual too--so they can provide accurate and clear documentation for the modified program. A manual that leaves you no choice but to write a new manual to document a changed version of the program is not really available to our community. 

Some kinds of limits on the way modification is handled are acceptable. For example, requirements to preserve the original author's copyright notice, the distribution terms, or the list of authors, are ok. It is also no problem to require modified versions to include notice that they were modified. Even entire sections that may not be deleted or changed are acceptable, as long as they deal with nontechnical topics (like this one). These kinds of restrictions are acceptable because they don't obstruct the community's normal use of the manual. 

However, it must be possible to modify all the technical content of the manual, and then distribute the result in all the usual media, through all the usual channels. Otherwise, the restrictions obstruct the use of the manual, it is not free, and we need another manual to replace it. 

Please spread the word about this issue. Our community continues to lose manuals to proprietary publishing. If we spread the word that free software needs free reference manuals and free tutorials, perhaps the next person who wants to contribute by writing documentation will realize, before it is too late, that only free manuals contribute to the free software community. 

If you are writing documentation, please insist on publishing it under the GNU Free Documentation License or another free documentation license. Remember that this decision requires your approval--you don't have to let the publisher decide. Some commercial publishers will use a free license if you insist, but they will not propose the option; it is up to you to raise the issue and say firmly that this is what you want. If the publisher you are dealing with refuses, please try other publishers. If you're not sure whether a proposed license is free, write to  licensing@gnu.org . 

You can encourage commercial publishers to sell more free, copylefted manuals and tutorials by buying them, and particularly by buying copies from the publishers that paid for their writing or for major improvements. Meanwhile, try to avoid buying non-free documentation at all. Check the distribution terms of a manual before you buy it, and insist that whoever seeks your business must respect your freedom. Check the history of the book, and try reward the publishers that have paid or pay the authors to work on it. 

The Free Software Foundation maintains a list of free documentation published by other publishers, at  http://www.fsf.org/doc/other-free-books.html .

Freeing after Malloc 
Next:  Changing Block Size , Previous:  Malloc Examples , Up:  Unconstrained Allocation 




Freeing Memory Allocated with malloc

When you no longer need a block that you got with malloc, use the function free to make the block available to be allocated again. The prototype for this function is in stdlib.h.

-- Function: void free (void *ptr)

The free function deallocates the block of memory pointed at by ptr.

Freeing a block alters the contents of the block. Do not expect to find any data (such as a pointer to the next block in a chain of blocks) in the block after freeing it. Copy whatever you need out of the block before freeing it! Here is an example of the proper way to free all the blocks in a chain, and the strings that they point to:

     struct chain
       {
         struct chain *next;
         char *name;
       }
     
     void
     free_chain (struct chain *chain)
     {
       while (chain != 0)
         {
           struct chain *next = chain->next;
           free (chain->name);
           free (chain);
           chain = next;
         }
     }

Occasionally, free can actually return memory to the operating system and make the process smaller. Usually, all it can do is allow a later call to malloc to reuse the space. In the meantime, the space remains in your program as part of a free-list used internally by malloc. 

There is no point in freeing blocks at the end of a program, because all of the program's space is given back to the system when the process terminates.

General Numeric 
Next:  Currency Symbol , Up:  The Lame Way to Locale Data 




Generic Numeric Formatting Parameters

These are the standard members of struct lconv; there may be others.

char *decimal_point
char *mon_decimal_point
These are the decimal-point separators used in formatting non-monetary and monetary quantities, respectively. In the `C' locale, the value of decimal_point is ".", and the value of mon_decimal_point is "".
char *thousands_sep
char *mon_thousands_sep
These are the separators used to delimit groups of digits to the left of the decimal point in formatting non-monetary and monetary quantities, respectively. In the `C' locale, both members have a value of "" (the empty string). 
char *grouping
char *mon_grouping
These are strings that specify how to group the digits to the left of the decimal point. grouping applies to non-monetary quantities and mon_grouping applies to monetary quantities. Use either thousands_sep or mon_thousands_sep to separate the digit groups. Each member of these strings is to be interpreted as an integer value of type char. Successive numbers (from left to right) give the sizes of successive groups (from right to left, starting at the decimal point.) The last member is either 0, in which case the previous member is used over and over again for all the remaining groups, or CHAR_MAX, in which case there is no more grouping--or, put another way, any remaining digits form one large group without separators. 

For example, if grouping is "\04\03\02", the correct grouping for the number 123456787654321 is `12', `34', `56', `78', `765', `4321'. This uses a group of 4 digits at the end, preceded by a group of 3 digits, preceded by groups of 2 digits (as many as needed). With a separator of `,', the number would be printed as `12,34,56,78,765,4321'. 

A value of "\03" indicates repeated groups of three digits, as normally used in the U.S. 

In the standard `C' locale, both grouping and mon_grouping have a value of "". This value specifies no grouping at all. 
char int_frac_digits
char frac_digits
These are small integers indicating how many fractional digits (to the right of the decimal point) should be displayed in a monetary value in international and local formats, respectively. (Most often, both members have the same value.) 

In the standard `C' locale, both of these members have the value CHAR_MAX, meaning "unspecified". The ISO standard doesn't say what to do when you find this value; we recommend printing no fractional digits. (This locale also specifies the empty string for mon_decimal_point, so printing any fractional digits would be confusing!)

Generating Signals 
Previous:  Signal Actions , Up:  Signal Handling 




Generating Signals

Besides signals that are generated as a result of a hardware trap or interrupt, your program can explicitly send signals to itself or to another process.

·  Signaling Yourself : A process can send a signal to itself.

Getting Started 
Next:  Roadmap to the Manual , Up:  Introduction 




Getting Started

This manual is written with the assumption that you are at least somewhat familiar with the C programming language and basic programming concepts. Specifically, familiarity with ISO standard C (see  ISO C ), rather than "traditional" pre-ISO C dialects, is assumed. 

The C library includes several header files, each of which provides definitions and declarations for a group of related facilities; this information is used by the C compiler when processing your program. For example, the header file stdio.h declares facilities for performing input and output, and the header file string.h declares string processing utilities. The organization of this manual generally follows the same division as the header files. 

If you are reading this manual for the first time, you should read all of the introductory material and skim the remaining chapters. There are a lot of functions in the C library and it's not realistic to expect that you will be able to remember exactly how to use each and every one of them. It's more important to become generally familiar with the kinds of facilities that the library provides, so that when you are writing your programs you can recognize when to make use of library functions, and where in this manual you can find more specific information about them.

C99 Variable-Size Arrays 
Previous:  Disadvantages of Alloca , Up:  Variable Size Automatic 




C99 Variable-Size Arrays

In C99, you can replace most uses of alloca with an array of variable size. Here is how open2 would look then:

     int open2 (char *str1, char *str2, int flags, int mode)
     {
       char name[strlen (str1) + strlen (str2) + 1];
       stpcpy (stpcpy (name, str1), str2);
       return open (name, flags, mode);
     }

But alloca is not always equivalent to a variable-sized array, for several reasons:

· A variable size array's space is freed at the end of the scope of the name of the array. The space allocated with alloca remains until the end of the function. 
· It is possible to use alloca within a loop, allocating an additional block on each iteration. This is impossible with variable-sized arrays.

Note: If you mix use of alloca and variable-sized arrays within one function, exiting a scope in which a variable-sized array was declared frees all blocks allocated with alloca during the execution of that scope.

Handler Returns 
Next:  Termination in Handler , Up:  Defining Handlers 




Signal Handlers that Return

Handlers which return normally are usually used for signals such as SIGALRM and the I/O and interprocess communication signals. But a handler for SIGINT might also return normally after setting a flag that tells the program to exit at a convenient time. 

It is not safe to return normally from the handler for a program error signal, because the behavior of the program when the handler function returns is not defined after a program error. See  Program Error Signals . 

Handlers that return normally must modify some global variable in order to have any effect. Typically, the variable is one that is examined periodically by the program during normal operation. Its data type should be sig_atomic_t for reasons described in  Atomic Data Access . 

Here is a simple example of such a program. It executes the body of the loop until it has noticed that a SIGALRM signal has arrived. This technique is useful because it allows the iteration in progress when the signal arrives to complete before the loop exits.

     #include <signal.h>
     #include <stdio.h>
     #include <stdlib.h>
     
     /* This flag controls termination of the main loop. */
     volatile sig_atomic_t keep_going = 1;
     
     /* The signal handler just clears the flag and re-enables itself. */
     void
     catch_alarm (int sig)
     {
       keep_going = 0;
       signal (sig, catch_alarm);
     }
     
     void
     do_stuff (void)
     {
       puts ("Doing stuff while waiting for alarm....");
     }
     
     int
     main (void)
     {
       /* Establish a handler for SIGALRM signals. */
       signal (SIGALRM, catch_alarm);
     
       /* Set an alarm to go off in a little while. */
       alarm (2);
     
       /* Check the flag once in a while to see when to quit. */
       while (keep_going)
         do_stuff ();
     
       return EXIT_SUCCESS;
     }

Header Files 
Next:  Macro Definitions 




Header Files

Libraries for use by C programs really consist of two parts: header files that define types and macros and declare variables and functions; and the actual library or archive that contains the definitions of the variables and functions. 

(Recall that in C, a declaration merely provides information that a function or variable exists and gives its type. For a function declaration, information about the types of its arguments might be provided as well. The purpose of declarations is to allow the compiler to correctly process references to the declared variables and functions. A definition, on the other hand, actually allocates storage for a variable or says what a function does.) In order to use the facilities in the C library, you should be sure that your program source files include the appropriate header files. This is so that the compiler has declarations of these facilities available and can correctly process references to them. Once your program has been compiled, the linker resolves these references to the actual definitions provided in the archive file. 

Header files are included into a program source file by the `#include' preprocessor directive. The C language supports two forms of this directive; the first,

     #include "header"

is typically used to include a header file header that you write yourself; this would contain definitions and declarations describing the interfaces between the different parts of your particular application. By contrast,

     #include <file.h>

is typically used to include a header file file.h that contains definitions and declarations for a standard library. This file would normally be installed in a standard place by your system administrator. You should use this second form for the C library header files. 

Typically, `#include' directives are placed at the top of the C source file, before any other code. If you begin your source files with some comments explaining what the code in the file does (a good idea), put the `#include' directives immediately afterwards.

The C library provides several header files, each of which contains the type and macro definitions and variable and function declarations for a group of related facilities. This means that your programs may need to include several header files, depending on exactly which facilities you are using. 

Some library header files include other library header files automatically. However, as a matter of programming style, you should not rely on this; it is better to explicitly include all the header files required for the library facilities you are using. The C library header files have been written in such a way that it doesn't matter if a header file is accidentally included more than once; including a header file a second time has no effect. Likewise, if your program needs to include multiple header files, the order in which they are included doesn't matter. 

Compatibility Note: Inclusion of standard header files in any order and any number of times works in any ISO C implementation. However, this has traditionally not been the case in many older C implementations. 

Strictly speaking, you don't have to include a header file to use a function it declares; you could declare the function explicitly yourself, according to the specifications in this manual. But it is usually better to include the header file because it may define types and macros that are not otherwise available and because it may define more efficient macro replacements for some functions. It is also a sure way to have the correct declaration.

How Many Arguments {keepn}
Next:  Calling Variadics , Previous: Receiving Arguments  ,Up:  How Variadic 


How Many Arguments

There is no general way for a function to determine the number and type of the optional arguments it was called with. So whoever designs the function typically designs a convention for the caller to specify the number and type of arguments. It is up to you to define an appropriate calling convention for each variadic function, and write all calls accordingly. 

One kind of calling convention is to pass the number of optional arguments as one of the fixed arguments. This convention works provided all of the optional arguments are of the same type. 

A similar alternative is to have one of the required arguments be a bit mask, with a bit for each possible purpose for which an optional argument might be supplied. You would test the bits in a predefined sequence; if the bit is set, fetch the value of the next argument, otherwise use a default value. 

A required argument can be used as a pattern to specify both the number and types of the optional arguments. The format string argument to printf is one example of this (see  Formatted Output Functions ). 

Another possibility is to pass an "end marker" value as the last optional argument. For example, for a function that manipulates an arbitrary number of pointer arguments, a null pointer might indicate the end of the argument list. (This assumes that a null pointer isn't otherwise meaningful to the function.) The execl function works in just this way; see  Executing a File .

How Unread 
Previous:  Unreading Idea , Up:  Unreading 




Using ungetc To Do Unreading

The function to unread a character is called ungetc, because it reverses the action of getc.

-- Function: int ungetc (int c, FILE *stream)

The ungetc function pushes back the character c onto the input stream stream. So the next input from stream will read c before anything else. 

If c is EOF, ungetc does nothing and just returns EOF. This lets you call ungetc with the return value of getc without needing to check for an error from getc. 

The character that you push back doesn't have to be the same as the last character that was actually read from the stream. In fact, it isn't necessary to actually read any characters from the stream before unreading them with ungetc! But that is a strange way to write a program; usually ungetc is used only to unread a character that was just read from the same stream. 

The C library supports pushing back multiple characters; then reading from the stream retrieves the characters in the reverse order that they were pushed. 

Pushing back characters doesn't alter the file; only the internal buffering for the stream is affected. If a file positioning function (such as fseek, fseeko or rewind; see  File Positioning ) is called, any pending pushed-back characters are discarded. 

Unreading a character on a stream that is at end of file clears the end-of-file indicator for the stream, because it makes the character of input available. After you read that character, trying to read again will encounter end of file.

-- Function: wint_t ungetwc (wint_t wc, FILE *stream)

The ungetwc function behaves just like ungetc just that it pushes back a wide character.

Here is an example showing the use of getc and ungetc to skip over whitespace characters. When this function reaches a non-whitespace character, it unreads that character to be seen again on the next read operation on the stream.

     #include <stdio.h>
     #include <ctype.h>
     
     void
     skip_whitespace (FILE *stream)
     {
       int c;
       do
         /* No need to check for EOF because it is not
            isspace, and ungetc ignores EOF.  */
         c = getc (stream);
       while (isspace (c));
       ungetc (c, stream);
     }

How Variadic 
Next:  Variadic Example , Previous:  Why Variadic , Up:  Variadic Functions 




How Variadic Functions are Defined and Used

Defining and using a variadic function involves three steps:

· Define the function as variadic, using an ellipsis (`...') in the argument list, and using special macros to access the variable arguments. See  Receiving Arguments . 
· Declare the function as variadic, using a prototype with an ellipsis (`...'), in all the files which call it. See  Variadic Prototypes . 
· Call the function by writing the fixed arguments followed by the additional variable arguments. See  Calling Variadics .

·  Variadic Prototypes : How to make a prototype for a function with variable arguments.
·  Receiving Arguments : Steps you must follow to access the optional argument values.
·  How Many Arguments : How to decide whether there are more arguments.
·  Calling Variadics : Things you need to know about calling variable arguments functions.
·  Argument Macros : Detailed specification of the macros for accessing variable arguments.
· 
Hyperbolic Functions 
Next:  Special Functions , Previous:  Exponents and Logarithms , Up:  Mathematics 




Hyperbolic Functions

The functions in this section are related to the exponential functions; see  Exponents and Logarithms .

-- Function: double sinh (double x)

-- Function: float sinhf (float x)

-- Function: long double sinhl (long double x)

These functions return the hyperbolic sine of x, defined mathematically as (exp (x) - exp (-x)) / 2. They may signal overflow if x is too large.

-- Function: double cosh (double x)

-- Function: float coshf (float x)

-- Function: long double coshl (long double x)

These function return the hyperbolic cosine of x, defined mathematically as (exp (x) + exp (-x)) / 2. They may signal overflow if x is too large.

-- Function: double tanh (double x)

-- Function: float tanhf (float x)

-- Function: long double tanhl (long double x)

These functions return the hyperbolic tangent of x, defined mathematically as sinh (x) / cosh (x). They may signal overflow if x is too large.

There are counterparts for the hyperbolic functions which take complex arguments.

-- Function: complex double csinh (complex double z)

-- Function: complex float csinhf (complex float z)

-- Function: complex long double csinhl (complex long double z)

These functions return the complex hyperbolic sine of z, defined mathematically as (exp (z) - exp (-z)) / 2.

-- Function: complex double ccosh (complex double z)

-- Function: complex float ccoshf (complex float z)

-- Function: complex long double ccoshl (complex long double z)

These functions return the complex hyperbolic cosine of z, defined mathematically as (exp (z) + exp (-z)) / 2.

-- Function: complex double ctanh (complex double z)

-- Function: complex float ctanhf (complex float z)

-- Function: complex long double ctanhl (complex long double z)

These functions return the complex hyperbolic tangent of z, defined mathematically as csinh (z) / ccosh (z).

-- Function: double asinh (double x)

-- Function: float asinhf (float x)

-- Function: long double asinhl (long double x)

These functions return the inverse hyperbolic sine of x--the value whose hyperbolic sine is x.

-- Function: double acosh (double x)

-- Function: float acoshf (float x)

-- Function: long double acoshl (long double x)

These functions return the inverse hyperbolic cosine of x--the value whose hyperbolic cosine is x. If x is less than 1, acosh signals a domain error.

-- Function: double atanh (double x)

-- Function: float atanhf (float x)

-- Function: long double atanhl (long double x)

These functions return the inverse hyperbolic tangent of x--the value whose hyperbolic tangent is x. If the absolute value of x is greater than 1, atanh signals a domain error; if it is equal to 1, atanh returns infinity.

-- Function: complex double casinh (complex double z)

-- Function: complex float casinhf (complex float z)

-- Function: complex long double casinhl (complex long double z)

These functions return the inverse complex hyperbolic sine of z--the value whose complex hyperbolic sine is z.

-- Function: complex double cacosh (complex double z)

-- Function: complex float cacoshf (complex float z)

-- Function: complex long double cacoshl (complex long double z)

These functions return the inverse complex hyperbolic cosine of z--the value whose complex hyperbolic cosine is z. Unlike the real-valued functions, there are no restrictions on the value of z.

-- Function: complex double catanh (complex double z)

-- Function: complex float catanhf (complex float z)

-- Function: complex long double catanhl (complex long double z)

These functions return the inverse complex hyperbolic tangent of z--the value whose complex hyperbolic tangent is z. Unlike the real-valued functions, there are no restrictions on the value of z.

IEEE Floating Point 
Previous:  Floating Point Parameters , Up:  Floating Type Macros 




IEEE Floating Point

Here is an example showing how the floating type measurements come out for the most common floating point representation, specified by the IEEE Standard for Binary Floating Point Arithmetic (ANSI/IEEE Std 754-1985). Nearly all computers designed since the 1980s use this format. 

The IEEE single-precision float representation uses a base of 2. There is a sign bit, a mantissa with 23 bits plus one hidden bit (so the total precision is 24 base-2 digits), and an 8-bit exponent that can represent values in the range -125 to 128, inclusive. 

So, for an implementation that uses this representation for the float data type, appropriate values for the corresponding parameters are:

     FLT_RADIX                             2
     FLT_MANT_DIG                         24
     FLT_DIG                               6
     FLT_MIN_EXP                        -125
     FLT_MIN_10_EXP                      -37
     FLT_MAX_EXP                         128
     FLT_MAX_10_EXP                      +38
     FLT_MIN                 1.17549435E-38F
     FLT_MAX                 3.40282347E+38F
     FLT_EPSILON             1.19209290E-07F

Here are the values for the double data type:

     DBL_MANT_DIG                         53
     DBL_DIG                              15
     DBL_MIN_EXP                       -1021
     DBL_MIN_10_EXP                     -307
     DBL_MAX_EXP                        1024
     DBL_MAX_10_EXP                      308
     DBL_MAX         1.7976931348623157E+308
     DBL_MIN         2.2250738585072014E-308
     DBL_EPSILON     2.2204460492503131E-016

Important Data Types 
Next:  Data Type Measurements , Previous:  Null Pointer Constant , Up:  Language Features 




Important Data Types

The result of subtracting two pointers in C is always an integer, but the precise data type varies from C compiler to C compiler. Likewise, the data type of the result of sizeof also varies between compilers. ISO defines standard aliases for these two types, so you can refer to them in a portable fashion. They are defined in the header file stddef.h.

-- Data Type: ptrdiff_t

This is the signed integer type of the result of subtracting two pointers. For example, with the declaration char *p1, *p2;, the expression p2 - p1 is of type ptrdiff_t. This will probably be one of the standard signed integer types (short int, int or long int), but might be a nonstandard type that exists only for this purpose.

-- Data Type: size_t

This is an unsigned integer type used to represent the sizes of objects. The result of the sizeof operator is of this type, and functions such as malloc (see  Unconstrained Allocation ) and memcpy (see  Copying and Concatenation ) accept arguments of this type to specify object sizes. 

Usage Note: size_t is the preferred way to declare any arguments or variables that hold the size of an object.

In this system size_t is equivalent to unsigned int.

Compatibility Note: Implementations of C before the advent of ISO C generally used unsigned int for representing object sizes and int for pointer subtraction results. They did not necessarily define either size_t or ptrdiff_t. Unix systems did define size_t, in sys/types.h, but the definition was usually a signed type.

Infinity and NaN 
Next:  Status bit operations , Previous:  FP Exceptions , Up:  Floating Point Errors 




Infinity and NaN

IEEE 754 floating point numbers can represent positive or negative infinity, and NaN (not a number). These three values arise from calculations whose result is undefined or cannot be represented accurately. You can also deliberately set a floating-point variable to any of them, which is sometimes useful. Some examples of calculations that produce infinity or NaN:

     1/0 = µ;
     log (0) = -µ;
     sqrt (-1) = NaN

When a calculation produces any of these values, an exception also occurs; see  FP Exceptions . 

The basic operations and math functions all accept infinity and NaN and produce sensible output. Infinities propagate through calculations as one would expect: for example, 2 + µ; = µ;, 4/µ; = 0, atan (µ) = p/2. NaN, on the other hand, infects any calculation that involves it. Unless the calculation would produce the same result no matter what real value replaced NaN, the result is NaN. 

In comparison operations, positive infinity is larger than all values except itself and NaN, and negative infinity is smaller than all values except itself and NaN. NaN is unordered: it is not equal to, greater than, or less than anything, including itself. x == x is false if the value of x is NaN. You can use this to test whether a value is NaN or not, but the recommended way to test for NaN is with the isnan function (see  Floating Point Classes ). In addition, <, >, <=, and >= will raise an exception when applied to NaNs. 

math.h defines macros that allow you to explicitly set a variable to infinity or NaN.

-- Macro: float INFINITY

An expression representing positive infinity. It is equal to the value produced by mathematical operations like 1.0 / 0.0. -INFINITY represents negative infinity. 

You can test whether a floating-point value is infinite by comparing it to this macro. However, this is not recommended; you should use the isfinite macro instead. See  Floating Point Classes . 

This macro was introduced in the ISO C99 standard.

-- Macro: float NAN

An expression representing a value which is "not a number". This macro is available only on machines that support the "not a number" value--that is to say, on all machines that support IEEE floating point. 

You can use `#ifdef NAN' to test whether the machine supports NaN. 

IEEE 754 also allows for another unusual value: negative zero. This value is produced when you divide a positive number by negative infinity, or when a negative result is smaller than the limits of representation. Negative zero behaves identically to zero in all calculations, unless you explicitly test the sign bit with signbit or copysign.

Input Conversion Syntax 
Next:  Table of Input Conversions , Previous:  Formatted Input Basics , Up:  Formatted Input 




Input Conversion Syntax

A scanf template string is a string that contains ordinary multibyte characters interspersed with conversion specifications that start with `%'. 

Any whitespace character (as defined by the isspace function; see  Classification of Characters ) in the template causes any number of whitespace characters in the input stream to be read and discarded. The whitespace characters that are matched need not be exactly the same whitespace characters that appear in the template string. For example, write ` , ' in the template to recognize a comma with optional whitespace before and after. 

Other characters in the template string that are not part of conversion specifications must match characters in the input stream exactly; if this is not the case, a matching failure occurs. 

The conversion specifications in a scanf template string have the general form:

     % flags width type conversion

In more detail, an input conversion specification consists of an initial `%' character followed in sequence by:

· An optional flag character `*', which says to ignore the text read for this specification. When scanf finds a conversion specification that uses this flag, it reads input as directed by the rest of the conversion specification, but it discards this input, does not use a pointer argument, and does not increment the count of successful assignments.
· An optional decimal integer that specifies the maximum field width. Reading of characters from the input stream stops either when this maximum is reached or when a non-matching character is found, whichever happens first. Most conversions discard initial whitespace characters (those that don't are explicitly documented), and these discarded characters don't count towards the maximum field width. String input conversions store a null character to mark the end of the input; the maximum field width does not include this terminator.
· An optional type modifier character. For example, you can specify a type modifier of `l' with integer conversions such as `%d' to specify that the argument is a pointer to a long int rather than a pointer to an int.
· A character that specifies the conversion to be applied.

The exact options that are permitted and how they are interpreted vary between the different conversion specifiers. See the descriptions of the individual conversions for information about the particular options that they allow. 

Integer Conversions 
Next:  Floating-Point Conversions , Previous:  Table of Output Conversions , Up:  Formatted Output 




Integer Conversions

This section describes the options for the `%d', `%i', `%o', `%u', `%x', and `%X' conversion specifications. These conversions print integers in various formats. 

The `%d' and `%i' conversion specifications both print an int argument as a signed decimal number; while `%o', `%u', and `%x' print the argument as an unsigned octal, decimal, or hexadecimal number (respectively). The `%X' conversion specification is just like `%x' except that it uses the characters `ABCDEF' as digits instead of `abcdef'. 

The following flags are meaningful:

`-'
Left-justify the result in the field (instead of the normal right-justification). 
`+'
For the signed `%d' and `%i' conversions, print a plus sign if the value is positive. 
` '
For the signed `%d' and `%i' conversions, if the result doesn't start with a plus or minus sign, prefix it with a space character instead. Since the `+' flag ensures that the result includes a sign, this flag is ignored if you supply both of them. 
`#'
For the `%o' conversion, this forces the leading digit to be `0', as if by increasing the precision. For `%x' or `%X', this prefixes a leading `0x' or `0X' (respectively) to the result. This doesn't do anything useful for the `%d', `%i', or `%u' conversions. Using this flag produces output which can be parsed by the strtoul function (see  Parsing of Integers ) and scanf with the `%i' conversion (see  Numeric Input Conversions ). 
`0'
Pad the field with zeros instead of spaces. The zeros are placed after any indication of sign or base. This flag is ignored if the `-' flag is also specified, or if a precision is specified.

If a precision is supplied, it specifies the minimum number of digits to appear; leading zeros are produced if necessary. If you don't specify a precision, the number is printed with as many digits as it needs. If you convert a value of zero with an explicit precision of zero, then no characters at all are produced. 

Without a type modifier, the corresponding argument is treated as an int (for the signed conversions `%i' and `%d') or unsigned int (for the unsigned conversions `%o', `%u', `%x', and `%X'). Recall that since printf and friends are variadic, any char and short arguments are automatically converted to int by the default argument promotions. For arguments of other integer types, you can use these modifiers:

`hh'
Specifies that the argument is a signed char or unsigned char, as appropriate. A char argument is converted to an int or unsigned int by the default argument promotions anyway, but the `h' modifier says to convert it back to a char again. 

This modifier was introduced in ISO C99. 
`h'
Specifies that the argument is a short int or unsigned short int, as appropriate. A short argument is converted to an int or unsigned int by the default argument promotions anyway, but the `h' modifier says to convert it back to a short again. 
`j'
Specifies that the argument is a intmax_t or uintmax_t, as appropriate. 

This modifier was introduced in ISO C99. 
`l'
Specifies that the argument is a long int or unsigned long int, as appropriate. Two `l' characters is like the `L' modifier, below. 

If used with `%c' or `%s' the corresponding parameter is considered as a wide character or wide character string respectively. This use of `l' was introduced in Amendment 1 to ISO C90. 
`ll'
Specifies that the argument is a long long int.
`t'
Specifies that the argument is a ptrdiff_t. 

This modifier was introduced in ISO C99. 
`z'
`Z'
Specifies that the argument is a size_t. 

`z' was introduced in ISO C99. `Z' is a GNU extension predating this addition and should not be used in new code.

Here is an example. Using the template string:

     "|%5d|%-5d|%+5d|%+-5d|% 5d|%05d|%5.0d|%5.2d|%d|\n"

to print numbers using the different options for the `%d' conversion gives results like:

     |    0|0    |   +0|+0   |    0|00000|     |   00|0|
     |    1|1    |   +1|+1   |    1|00001|    1|   01|1|
     |   -1|-1   |   -1|-1   |   -1|-0001|   -1|  -01|-1|
     |100000|100000|+100000|+100000| 100000|100000|100000|100000|100000|

In particular, notice what happens in the last case where the number is too large to fit in the minimum field width specified. 

Here are some more examples showing how unsigned integers print under various format options, using the template string:

     "|%5u|%5o|%5x|%5X|%#5o|%#5x|%#5X|%#10.8x|\n"

     |    0|    0|    0|    0|    0|    0|    0|  00000000|
     |    1|    1|    1|    1|   01|  0x1|  0X1|0x00000001|
     |100000|303240|186a0|186A0|0303240|0x186a0|0X186A0|0x000186a0|

Integer Division 
Next:  Floating Point Numbers , Previous:  Integers , Up:  Arithmetic 




Integer Division

This section describes functions for performing integer division. These functions are redundant when CC386 is used, because in this compiler the `/' operator always rounds towards zero. But in other C implementations, `/' may round differently with negative arguments. div and ldiv are useful because they specify how to round the quotient: towards zero. The remainder has the same sign as the numerator. 

These functions are specified to return a result r such that the value r.quot*denominator + r.rem equals numerator. 

To use these facilities, you should include the header file stdlib.h in your program.
-- Data Type: div_t

This is a structure type used to hold the result returned by the div function. It has the following members:

int quot
The quotient from the division. 
int rem
The remainder from the division.

-- Function: div_t div (int numerator, int denominator)

This function div computes the quotient and remainder from the division of numerator by denominator, returning the result in a structure of type div_t. 

If the result cannot be represented (as in a division by zero), the behavior is undefined. 

Here is an example, albeit not a very useful one. 

          div_t result;
          result = div (20, -6);
     
Now result.quot is -3 and result.rem is 2.

-- Data Type: ldiv_t

This is a structure type used to hold the result returned by the ldiv function. It has the following members:

long int quot
The quotient from the division. 
long int rem
The remainder from the division.

(This is identical to div_t except that the components are of type long int rather than int.)

-- Function: ldiv_t ldiv (long int numerator, long int denominator)

The ldiv function is similar to div, except that the arguments are of type long int and the result is returned as a structure of type ldiv_t.

-- Data Type: lldiv_t

This is a structure type used to hold the result returned by the lldiv function. It has the following members:

long long int quot
The quotient from the division. 
long long int rem
The remainder from the division.

(This is identical to div_t except that the components are of type long long int rather than int.)

-- Function: lldiv_t lldiv (long long int numerator, long long int denominator)

The lldiv function is like the div function, but the arguments are of type long long int and the result is returned as a structure of type lldiv_t. 

The lldiv function was added in ISO C99.

-- Data Type: imaxdiv_t

This is a structure type used to hold the result returned by the imaxdiv function. It has the following members:

intmax_t quot
The quotient from the division. 
intmax_t rem
The remainder from the division.

(This is identical to div_t except that the components are of type intmax_t rather than int.) 

See  Integers  for a description of the intmax_t type.

-- Function: imaxdiv_t imaxdiv (intmax_t numerator, intmax_t denominator)

The imaxdiv function is like the div function, but the arguments are of type intmax_t and the result is returned as a structure of type imaxdiv_t. 

See  Integers  for a description of the intmax_t type. 

The imaxdiv function was added in ISO C99.

Integers
Next:  Integer Division , Up:  Arithmetic 




Integers

The C language defines several integer data types: integer, short integer, long integer, long long  integer, and character, all in both signed and unsigned varieties. The C integer types were intended to allow code to be portable among machines with different inherent data sizes (word sizes), so each type may have different ranges on different machines. The problem with this is that a program often needs to be written for a particular range of integers, and sometimes must be written for a particular size of storage, regardless of what machine the program runs on. 

To address this problem, the C library contains C type definitions you can use to declare integers that meet your exact needs. Because the C library header files are customized to a specific machine, your program source code doesn't have to be. 

These typedefs are in stdint.h. If you require that an integer be represented in exactly N bits, use one of the following types, with the obvious mapping to bit size and signedness:

· int8_t
· int16_t
· int32_t
· int64_t
· uint8_t
· uint16_t
· uint32_t
· uint64_t

If your C compiler and target machine do not allow integers of a certain size, the corresponding above type does not exist. 

If you don't need a specific storage size, but want the smallest data structure with at least N bits, use one of these:

· int_least8_t
· int_least16_t
· int_least32_t
· int_least64_t
· uint_least8_t
· uint_least16_t
· uint_least32_t
· uint_least64_t

If you don't need a specific storage size, but want the data structure that allows the fastest access while having at least N bits (and among data structures with the same access speed, the smallest one), use one of these:

· int_fast8_t
· int_fast16_t
· int_fast32_t
· int_fast64_t
· uint_fast8_t
· uint_fast16_t
· uint_fast32_t
· uint_fast64_t

If you want an integer with the widest range possible on the platform on which it is being used, use one of the following. If you use these, you should write code that takes into account the variable size and range of the integer.

· intmax_t
· uintmax_t

The C library also provides macros that tell you the maximum and minimum possible values for each integer data type. The macro names follow these examples: INT32_MAX, UINT8_MAX, INT_FAST32_MIN, INT_LEAST64_MIN, UINTMAX_MAX, INTMAX_MAX, INTMAX_MIN. Note that there are no macros for unsigned integer minima. These are always zero. There are similar macros for use with C's built in integer types which should come with your C compiler. These are described in  Data Type Measurements . 

Don't forget you can use the C sizeof function with any of these data types to get the number of bytes of storage each uses.

Introduction
Next:  Error Reporting , Previous:  Top , Up:  Top 




Introduction

The C language provides no built-in facilities for performing such common operations as input/output, memory management, string manipulation, and the like. Instead, these facilities are defined in a standard library, which you compile and link with your programs. The C library, described in this document, defines all of the library functions that are specified by the ISO C standard.

The purpose of this manual is to tell you how to use the facilities of the C library. We have mentioned which features belong to which standards to help you identify things that are potentially non-portable to other systems. But the emphasis in this manual is not on strict portability.

·  Getting Started : What this manual is for and how to use it.
·  Roadmap to the Manual : Overview of the remaining chapters in this manual.

Inverse Trig Functions 
Next:  Exponents and Logarithms , Previous:  Trig Functions , Up:  Mathematics 




Inverse Trigonometric Functions

These are the usual arc sine, arc cosine and arc tangent functions, which are the inverses of the sine, cosine and tangent functions respectively.

-- Function: double asin (double x)

-- Function: float asinf (float x)

-- Function: long double asinl (long double x)

These functions compute the arc sine of x--that is, the value whose sine is x. The value is in units of radians. Mathematically, there are infinitely many such values; the one actually returned is the one between -pi/2 and pi/2 (inclusive). 

The arc sine function is defined mathematically only over the domain -1 to 1. If x is outside the domain, asin signals a domain error.

-- Function: double acos (double x)

-- Function: float acosf (float x)

-- Function: long double acosl (long double x)

These functions compute the arc cosine of x--that is, the value whose cosine is x. The value is in units of radians. Mathematically, there are infinitely many such values; the one actually returned is the one between 0 and pi (inclusive). 

The arc cosine function is defined mathematically only over the domain -1 to 1. If x is outside the domain, acos signals a domain error.

-- Function: double atan (double x)

-- Function: float atanf (float x)

-- Function: long double atanl (long double x)

These functions compute the arc tangent of x--that is, the value whose tangent is x. The value is in units of radians. Mathematically, there are infinitely many such values; the one actually returned is the one between -pi/2 and pi/2 (inclusive).

-- Function: double atan2 (double y, double x)

-- Function: float atan2f (float y, float x)

-- Function: long double atan2l (long double y, long double x)

This function computes the arc tangent of y/x, but the signs of both arguments are used to determine the quadrant of the result, and x is permitted to be zero. The return value is given in radians and is in the range -pi to pi, inclusive. 

If x and y are coordinates of a point in the plane, atan2 returns the signed angle between the line from the origin to that point and the x-axis. Thus, atan2 is useful for converting Cartesian coordinates to polar coordinates. (To compute the radial coordinate, use hypot; see  Exponents and Logarithms .)

If both x and y are zero, atan2 returns zero.

ISO C99 defines complex versions of the inverse trig functions.

-- Function: complex double casin (complex double z)

-- Function: complex float casinf (complex float z)

-- Function: complex long double casinl (complex long double z)

These functions compute the complex arc sine of z--that is, the value whose sine is z. The value returned is in radians. 

Unlike the real-valued functions, casin is defined for all values of z.

-- Function: complex double cacos (complex double z)

-- Function: complex float cacosf (complex float z)

-- Function: complex long double cacosl (complex long double z)

These functions compute the complex arc cosine of z--that is, the value whose cosine is z. The value returned is in radians. 

Unlike the real-valued functions, cacos is defined for all values of z.

-- Function: complex double catan (complex double z)

-- Function: complex float catanf (complex float z)

-- Function: complex long double catanl (complex long double z)

These functions compute the complex arc tangent of z--that is, the value whose tangent is z. The value is in units of radians.

ISO C 




ISO C

The C library is compatible with the C standard adopted by the American National Standards Institute (ANSI): American National Standard X3.159-1989--"ANSI C" and later by the International Standardization Organization (ISO): ISO/IEC 9899:1990, "Programming languages--C". We here refer to the standard as ISO C since this is the more general standard in respect of ratification. The header files and library facilities that make up the library are a superset of those specified by the ISO C standard. 

If you are concerned about strict adherence to the ISO C standard, you should use the `+A' option when you compile your programs with the C compiler. This tells the compiler to define only ISO standard features from the library header files, unless you explicitly ask for additional features. 

Being able to restrict the library to include only ISO C features is important because ISO C puts limitations on what names can be defined by the library implementation, and some extensions don't fit these limitations. See  Reserved Names , for more information about these restrictions. 

This manual does not attempt to give you complete details on the differences between ISO C and older dialects. It gives advice on how to write programs to work portably under multiple C dialects, but does not aim for completeness.

ISO Random 
Up:  Pseudo-Random Numbers 




ISO C Random Number Functions

This section describes the random number functions that are part of the ISO C standard. 

To use these facilities, you should include the header file stdlib.h in your program.

-- Macro: int RAND_MAX

The value of this macro is an integer constant representing the largest value the rand function can return. In this library, it is 32767.  In other libraries it may be higher.

-- Function: int rand (void)

The rand function returns the next pseudo-random number in the series. The value ranges from 0 to RAND_MAX.

-- Function: void srand (unsigned int seed)

This function establishes seed as the seed for a new series of pseudo-random numbers. If you call rand before a seed has been established with srand, it uses the value 1 as a default seed. 

To produce a different pseudo-random series each time your program is run, do srand (time (0)).


I/O Concepts 
Next:  File Names , Up:  I/O Overview 




Input/Output Concepts

Before you can read or write the contents of a file, you must establish a connection or communications channel to the file. This process is called opening the file. You can open a file for reading, writing, or both. The connection to an open file is represented either as a stream or as a file descriptor. You pass this as an argument to the functions that do the actual read or write operations, to tell them which file to operate on. Certain functions expect streams, and others are designed to operate on file descriptors. 

When you have finished reading to or writing from the file, you can terminate the connection by closing the file. Once you have closed a stream or file descriptor, you cannot do any more input or output operations on it.

·  Streams and File Descriptors : The GNU Library provides two ways to access the contents of files.
·  File Position : The number of bytes from the beginning of the file.

I/O on Streams 
Next:  Low-Level I/O , Previous:  I/O Overview , Up:  Top 




Input/Output on Streams

This chapter describes the functions for creating streams and performing input and output operations on them. As discussed in  I/O Overview , a stream is a fairly abstract, high-level concept representing a communications channel to a file, device, or process.

·  Streams : About the data type representing a stream.
·  Standard Streams : Streams to the standard input and output devices are created for you.
·  Opening Streams : How to create a stream to talk to a file.
·  Closing Streams : Close a stream when you are finished with it.
·  Streams and I18N : Streams in internationalized applications.
·  Simple Output : Unformatted output by characters and lines.
·  Character Input : Unformatted input by characters and words.
·  Unreading : Peeking ahead/pushing back input just read.
·  Line Input : Reading lines of data.
·  Block Input/Output : Input and output operations on blocks of data.
·  Formatted Output : printf and related functions.
·  Formatted Input : scanf and related functions.
·  EOF and Errors : How you can tell if an I/O error happens.
·  Error Recovery : What you can do about errors.
·  Binary Streams : Some systems distinguish between text files and binary files.
·  File Positioning : About random-access streams.
·  Portable Positioning : Random access on peculiar ISO C systems.
·  Stream Buffering : How to control buffering of streams.
I/O Overview 
Next:  I/O on Streams , Up:  Top 




Input/Output Overview

Most programs need to do either input (reading data) or output (writing data), or most frequently both, in order to do anything useful. The C library provides such a large selection of input and output functions that the hardest part is often deciding which function is most appropriate! 

This chapter introduces concepts and terminology relating to input and output. Other chapters relating to the I/O facilities are:

·  I/O on Streams , which covers the high-level functions that operate on streams, including formatted input and output. 
·  Low-Level I/O , which covers the basic I/O and control functions on file descriptors. 
·  File System Interface , which covers functions for operating on directories and for manipulating file attributes such as access modes and ownership. 
·  I/O Concepts : Some basic information and terminology.
·  File Names : How to refer to a file.

I/O Primitives 
Next:  File Position Primitive , Previous:  Opening and Closing Files , Up:  Low-Level I/O 




Input and Output Primitives

This section describes the functions for performing primitive input and output operations on file descriptors: read, write, and lseek. These functions are declared in the header file unistd.h.

-- Function: int read (int filedes, void *buffer, size_t size)

The read function reads up to size bytes from the file with descriptor filedes, storing the results in the buffer. (This is not necessarily a character string, and no terminating null character is added.) 

The return value is the number of bytes actually read. This might be less than size; for example, if there aren't that many bytes left in the file or if there aren't that many bytes immediately available. The exact behavior depends on what kind of file it is. Note that reading less than size bytes is not an error. 

A value of zero indicates end-of-file (except if the value of the size argument is also zero). This is not considered an error. If you keep calling read while at end-of-file, it will keep returning zero and doing nothing else. 

If read returns at least one character, there is no way you can tell whether end-of-file was reached. But if you did reach the end, the next read will return zero. 

In case of an error, read returns -1. The following errno error conditions are defined for this function:

EAGAIN
Normally, when no input is immediately available, read waits for some input. But if the O_NONBLOCK flag is set for the file (see  File Status Flags ), read returns immediately without reading any data, and reports this error. 

Compatibility Note: Most versions of BSD Unix use a different error code for this: EWOULDBLOCK. In the GNU library, EWOULDBLOCK is an alias for EAGAIN, so it doesn't matter which name you use. 

On some systems, reading a large amount of data from a character special file can also fail with EAGAIN if the kernel cannot find enough physical memory to lock down the user's pages. This is limited to devices that transfer with direct memory access into the user's memory, which means it does not include terminals, since they always use separate buffers inside the kernel. This problem never happens in the GNU system. 

Any condition that could result in EAGAIN can instead result in a successful read which returns fewer bytes than requested. Calling read again immediately would result in EAGAIN. 
EBADF
The filedes argument is not a valid file descriptor, or is not open for reading. 
EINTR
read was interrupted by a signal while it was waiting for input. See  Interrupted Primitives . A signal will not necessary cause read to return EINTR; it may instead result in a successful read which returns fewer bytes than requested. 
EIO
For many devices, and for disk files, this error code indicates a hardware error. 

EIO also occurs when a background process tries to read from the controlling terminal, and the normal action of stopping the process by sending it a SIGTTIN signal isn't working. This might happen if the signal is being blocked or ignored, or because the process group is orphaned. See  Job Control , for more information about job control, and  Signal Handling , for information about signals.

-- Function: int write (int filedes, const void *buffer, size_t size)

The write function writes up to size bytes from buffer to the file with descriptor filedes. The data in buffer is not necessarily a character string and a null character is output like any other character. 

The return value is the number of bytes actually written. This may be size, but can always be smaller. Your program should always call write in a loop, iterating until all the data is written. 

Once write returns, the data is enqueued to be written and can be read back right away, but it is not necessarily written out to permanent storage immediately. You can use fsync when you need to be sure your data has been permanently stored before continuing. (It is more efficient for the system to batch up consecutive writes and do them all at once when convenient. Normally they will always be written to disk within a minute or less.) Modern systems provide another function fdatasync which guarantees integrity only for the file data and is therefore faster. You can use the O_FSYNC open mode to make write always store the data to disk before returning; see  Operating Modes . 

In the case of an error, write returns -1. The following errno error conditions are defined for this function:

EAGAIN
Normally, write blocks until the write operation is complete. But if the O_NONBLOCK flag is set for the file (see  Control Operations ), it returns immediately without writing any data and reports this error. An example of a situation that might cause the process to block on output is writing to a terminal device that supports flow control, where output has been suspended by receipt of a STOP character. 

Compatibility Note: Most versions of BSD Unix use a different error code for this: EWOULDBLOCK. In the GNU library, EWOULDBLOCK is an alias for EAGAIN, so it doesn't matter which name you use. 

On some systems, writing a large amount of data from a character special file can also fail with EAGAIN if the kernel cannot find enough physical memory to lock down the user's pages. This is limited to devices that transfer with direct memory access into the user's memory, which means it does not include terminals, since they always use separate buffers inside the kernel. This problem does not arise in the GNU system. 
EBADF
The filedes argument is not a valid file descriptor, or is not open for writing. 
EFBIG
The size of the file would become larger than the implementation can support. 
EINTR
The write operation was interrupted by a signal while it was blocked waiting for completion. A signal will not necessarily cause write to return EINTR; it may instead result in a successful write which writes fewer bytes than requested. See  Interrupted Primitives . 
EIO
For many devices, and for disk files, this error code indicates a hardware error. 
ENOSPC
The device containing the file is full. 
EPIPE
This error is returned when you try to write to a pipe or FIFO that isn't open for reading by any process. When this happens, a SIGPIPE signal is also sent to the process; see  Signal Handling .
Keeping the state 
Next:  Converting a Character , Previous:  Selecting the Conversion , Up:  Restartable multibyte conversion 




Representing the state of the conversion

In the introduction of this chapter it was said that certain character sets use a stateful encoding. That is, the encoded values depend in some way on the previous bytes in the text. 

Since the conversion functions allow converting a text in more than one step we must have a way to pass this information from one call of the functions to another.

-- Data type: mbstate_t

A variable of type mbstate_t can contain all the information about the shift state needed from one call to a conversion function to another. 

mbstate_t is defined in wchar.h. It was introduced in Amendment 1 to ISO C90.

To use objects of type mbstate_t the programmer has to define such objects (normally as local variables on the stack) and pass a pointer to the object to the conversion functions. This way the conversion function can update the object if the current multibyte character set is stateful. 

There is no specific function or initializer to put the state object in any specific state. The rules are that the object should always represent the initial state before the first use, and this is achieved by clearing the whole variable with code such as follows:

     {
       mbstate_t state;
       memset (&state, '\0', sizeof (state));
       /* from now on state can be used.  */
       ...
     }

When using the conversion functions to generate output it is often necessary to test whether the current state corresponds to the initial state. This is necessary, for example, to decide whether to emit escape sequences to set the state to the initial state at certain sequence points. Communication protocols often require this.

-- Function: int mbsinit (const mbstate_t *ps)

The mbsinit function determines whether the state object pointed to by ps is in the initial state. If ps is a null pointer or the object is in the initial state the return value is nonzero. Otherwise it is zero. 

mbsinit was introduced in Amendment 1 to ISO C90 and is declared in wchar.h.

Code using mbsinit often looks similar to this:

     {
       mbstate_t state;
       memset (&state, '\0', sizeof (state));
       /* Use state.  */
       ...
       if (! mbsinit (&state))
         {
           /* Emit code to return to initial state.  */
           const wchar_t empty[] = L"";
           const wchar_t *srcp = empty;
           wcsrtombs (outbuf, &srcp, outbuflen, &state);
         }
       ...
     }

The code to emit the escape sequence to get back to the initial state is interesting. The wcsrtombs function can be used to determine the necessary output code (see  Converting Strings ). Please note that on GNU systems it is not necessary to perform this extra action for the conversion from multibyte text to wide character text since the wide character encoding is not stateful. But there is nothing mentioned in any standard that prohibits making wchar_t using a stateful encoding.

Kinds of Signals 
Next:  Signal Generation , Up:  Concepts of Signals 




Some Kinds of Signals

A signal reports the occurrence of an exceptional event. These are some of the events that can cause (or generate, or raise) a signal:

· A program error such as dividing by zero or issuing an address outside the valid range. 
· A user request to interrupt or terminate the program. Most environments are set up to let a user suspend the program by typing C-z, or terminate it with C-c. Whatever key sequence is used, the operating system sends the proper signal to interrupt the process. 
· The termination of a child process. 
· Expiration of a timer or alarm. 
· A call to kill or raise by the same process. 
· A call to kill from another process. Signals are a limited but useful form of interprocess communication. 

Each of these kinds of events (excepting explicit calls to kill and raise) generates its own particular kind of signal. The various kinds of signals are listed and described in detail in  Standard Signals .

Language Features 
Next:  Free Manuals , Up:  Top 




Appendix A C Language Facilities in the Library

Some of the facilities implemented by the C library really should be thought of as parts of the C language itself. These facilities ought to be documented in the C Language Manual, not in the library manual; but since we don't have the language manual yet, and documentation for these features has been written, we are publishing it here.

·  Consistency Checking : Using assert to abort if something ``impossible'' happens.
·  Variadic Functions : Defining functions with varying numbers of args.
·  Null Pointer Constant : The macro NULL.
·  Important Data Types : Data types for object sizes.
·  Data Type Measurements : Parameters of data type representations.

Line Input 
Next:  Unreading , Previous:  Character Input , Up:  I/O on Streams 




Line-Oriented Input

Since many programs interpret input on the basis of lines, it is convenient to have functions to read a line of text from a stream. 

     
-- Function: char * fgets (char *s, int count, FILE *stream)

The fgets function reads characters from the stream stream up to and including a newline character and stores them in the string s, adding a null character to mark the end of the string. You must supply count characters worth of space in s, but the number of characters read is at most count - 1. The extra character space is used to hold the null character at the end of the string. 

If the system is already at end of file when you call fgets, then the contents of the array s are unchanged and a null pointer is returned. A null pointer is also returned if a read error occurs. Otherwise, the return value is the pointer s. 

Warning: If the input data has a null character, you can't tell. So don't use fgets unless you know the data cannot contain a null. Don't use it to read files edited by the user because, if the user inserts a null character, you should either handle it properly or print a clear error message. We recommend using getline instead of fgets.

-- Function: wchar_t * fgetws (wchar_t *ws, int count, FILE *stream)

The fgetws function reads wide characters from the stream stream up to and including a newline character and stores them in the string ws, adding a null wide character to mark the end of the string. You must supply count wide characters worth of space in ws, but the number of characters read is at most count - 1. The extra character space is used to hold the null wide character at the end of the string. 

If the system is already at end of file when you call fgetws, then the contents of the array ws are unchanged and a null pointer is returned. A null pointer is also returned if a read error occurs. Otherwise, the return value is the pointer ws. 

Warning: If the input data has a null wide character (which are null bytes in the input stream), you can't tell. So don't use fgetws unless you know the data cannot contain a null. Don't use it to read files edited by the user because, if the user inserts a null character, you should either handle it properly or print a clear error message.

-- Deprecated function: char * gets (char *s)

The function gets reads characters from the stream stdin up to the next newline character, and stores them in the string s. The newline character is discarded (note that this differs from the behavior of fgets, which copies the newline character into the string). If gets encounters a read error or end-of-file, it returns a null pointer; otherwise it returns s. 

Warning: The gets function is very dangerous because it provides no protection against overflowing the string s. The C library includes it for compatibility only.


Locale Categories 
Next:  Setting the Locale , Previous:  Choosing Locale , Up:  Locales 




Categories of Activities that Locales Affect

The purposes that locales serve are grouped into categories, so that a user or a program can choose the locale for each category independently. Here is a table of categories; each name is both an environment variable that a user can set, and a macro name that you can use as an argument to setlocale.

LC_COLLATE
This category applies to collation of strings (functions strcoll and strxfrm); see  Collation Functions .
LC_CTYPE
This category applies to classification and conversion of characters, and to multibyte and wide characters; see  Character Handling , and  Character Set Handling .
LC_MONETARY
This category applies to formatting monetary values; see  General Numeric .
LC_NUMERIC
This category applies to formatting numeric values that are not monetary; see  General Numeric .
LC_TIME
This category applies to formatting date and time values; see  Formatting Calendar Time .
LC_MESSAGES
This category applies to selecting the language used in the user interface for message translation and contains regular expressions for affirmative and negative responses.
LC_ALL
This is not an environment variable; it is only a macro that you can use with setlocale to set a single locale for all purposes. Setting this environment variable overwrites all selections by the other LC_* variables or LANG.
LANG
If this environment variable is defined, its value specifies the locale to use for all purposes except as overridden by the variables above.

Locale Information 
Next:  Yes-or-No Questions , Previous:  Standard Locales , Up:  Locales 




Accessing Locale Information

There are several ways to access locale information. The simplest way is to let the C library itself do the work. Several of the functions in this library implicitly access the locale data, and use what information is provided by the currently selected locale. This is how the locale model is meant to work normally. 

As an example take the strftime function, which is meant to nicely format date and time information (see  Formatting Calendar Time ). Part of the standard information contained in the LC_TIME category is the names of the months. Instead of requiring the programmer to take care of providing the translations the strftime function does this all by itself. %A in the format string is replaced by the appropriate weekday name of the locale currently selected by LC_TIME. This is an easy example, and wherever possible functions do things automatically in this way. 

But there are quite often situations when there is simply no function to perform the task, or it is simply not possible to do the work automatically. For these cases it is necessary to access the information in the locale directly. To do this the C library provides two functions: localeconv and nl_langinfo. The former is part of ISO C and therefore portable, but has a brain-damaged interface. The second is part of the Unix interface and is portable in as far as the system follows the Unix standards.

·  The Lame Way to Locale Data : ISO C's localeconv.

 Locales
Next:  Searching and Sorting , Previous:  Character Set Handling , Up:  Top 




Locales and Internationalization

Different countries and cultures have varying conventions for how to communicate. These conventions range from very simple ones, such as the format for representing dates and times, to very complex ones, such as the language spoken. 

Internationalization of software means programming it to be able to adapt to the user's favorite conventions. In ISO C, internationalization works by means of locales. Each locale specifies a collection of conventions, one convention for each purpose. The user chooses a set of conventions by specifying a locale (via environment variables). 

All programs inherit the chosen locale as part of their environment. Provided the programs are written to obey the choice of locale, they will follow the conventions preferred by the user.

·  Effects of Locale : Actions affected by the choice of locale.
·  Choosing Locale : How the user specifies a locale.
·  Locale Categories : Different purposes for which you can select a locale.
·  Setting the Locale : How a program specifies the locale with library functions.
·  Standard Locales : Locale names available on all systems.
·  Locale Information : How to access the information for the locale.
·  Yes-or-No Questions : Check a Response against the locale.

Longjmp in Handler 
Next:  Signals in Handler , Previous:  Termination in Handler , Up:  Defining Handlers 




Nonlocal Control Transfer in Handlers

You can do a nonlocal transfer of control out of a signal handler using the setjmp and longjmp facilities (see  Non-Local Exits ). 

When the handler does a nonlocal control transfer, the part of the program that was running will not continue. If this part of the program was in the middle of updating an important data structure, the data structure will remain inconsistent. Since the program does not terminate, the inconsistency is likely to be noticed later on. 

There are two ways to avoid this problem. One is to block the signal for the parts of the program that update important data structures. Blocking the signal delays its delivery until it is unblocked, once the critical updating is finished. See  Blocking Signals . 

The other way to re-initialize the crucial data structures in the signal handler, or make their values consistent. 

Here is a rather schematic example showing the reinitialization of one global variable.

     #include <signal.h>
     #include <setjmp.h>
     
     jmp_buf return_to_top_level;
     
     volatile sig_atomic_t waiting_for_input;
     
     void
     handle_sigint (int signum)
     {
       /* We may have been waiting for input when the signal arrived,
          but we are no longer waiting once we transfer control. */
       waiting_for_input = 0;
       longjmp (return_to_top_level, 1);
     }
     
     int
     main (void)
     {
       ...
       signal (SIGINT, sigint_handler);
       ...
       while (1) {
         prepare_for_command ();
         if (setjmp (return_to_top_level) == 0)
           read_and_execute_command ();
       }
     }
     
     /* Imagine this is a subroutine used by various commands. */
     char *
     read_data ()
     {
       if (input_from_terminal) {
         waiting_for_input = 1;
         ...
         waiting_for_input = 0;
       } else {
         ...
       }
     }

Low-Level I/O 
Next:  File System Interface , Previous:  I/O on Streams , Up:  Top 




Low-Level Input/Output

This chapter describes functions for performing low-level input/output operations on file descriptors. These functions include the primitives for the higher-level I/O functions described in  I/O on Streams , as well as functions for performing low-level control operations for which there are no equivalents on streams. 

Stream-level I/O is more flexible and usually more convenient; therefore, programmers generally use the descriptor-level functions only when necessary. These are some of the usual reasons:

· For reading binary files in large chunks. 
· For reading an entire file into core before parsing it. 
· To perform operations other than data transfer, which can only be done with a descriptor. (You can use fileno to get the descriptor corresponding to a stream.) 
· To pass descriptors to a child process. (The child can create its own stream to use a descriptor that it inherits, but cannot inherit a stream directly.)

·  Opening and Closing Files : How to open and close file descriptors.
·  I/O Primitives : Reading and writing data.
·  File Position Primitive : Setting a descriptor's file position.
·  Descriptors and Streams : Converting descriptor to stream or vice-versa.
· Duplicating Descriptors : Fcntl commands for duplicating file descriptors.
·  File Status Flags : Fcntl commands for manipulating flags associated with open files.
Macro Definitions 
Next:  Reserved Names , Previous:  Header Files 




Macro Definitions of Functions

If we describe something as a function in this manual, it may have a macro definition as well. This normally has no effect on how your program runs--the macro definition does the same thing as the function would. In particular, macro equivalents for library functions evaluate arguments exactly once, in the same way that a function call would. The main reason for these macro definitions is that sometimes they can produce an inline expansion that is considerably faster than an actual function call. 

Taking the address of a library function works even if it is also defined as a macro. This is because, in this context, the name of the function isn't followed by the left parenthesis that is syntactically necessary to recognize a macro call. 

You might occasionally want to avoid using the macro definition of a function--perhaps to make your program easier to debug. There are two ways you can do this:

· You can avoid a macro definition in a specific use by enclosing the name of the function in parentheses. This works because the name of the function doesn't appear in a syntactic context where it is recognizable as a macro call. 
· You can suppress any macro definition for a whole source file by using the `#undef' preprocessor directive, unless otherwise stated explicitly in the description of that facility.

For example, suppose the header file stdlib.h declares a function named abs with

     extern int abs (int);

and also provides a macro definition for abs. Then, in:

     #include <stdlib.h>
     int f (int *i) { return abs (++*i); }

the reference to abs might refer to either a macro or a function. On the other hand, in each of the following examples the reference is to a function and not a macro.

     #include <stdlib.h>
     int g (int *i) { return (abs) (++*i); }
     
     #undef abs
     int h (int *i) { return abs (++*i); }

Since macro definitions that double for a function behave in exactly the same way as the actual function version, there is usually no need for any of these methods. In fact, removing macro definitions usually just makes your program slower.

Malloc Examples 
Next:  Freeing after Malloc , Previous:  Basic Allocation , Up:  Unconstrained Allocation 




Examples of malloc

If no more space is available, malloc returns a null pointer. You should check the value of every call to malloc. It is useful to write a subroutine that calls malloc and reports an error if the value is a null pointer, returning only if the value is nonzero. This function is conventionally called xmalloc. Here it is:

     void *
     xmalloc (size_t size)
     {
       register void *value = malloc (size);
       if (value == 0)
         fatal ("virtual memory exhausted");
       return value;
     }

Here is a real example of using malloc (by way of xmalloc). The function savestring will copy a sequence of characters into a newly allocated null-terminated string:

     char *
     savestring (const char *ptr, size_t len)
     {
       register char *value = (char *) xmalloc (len + 1);
       value[len] = '\0';
       return (char *) memcpy (value, ptr, len);
     }

The block that malloc gives you is guaranteed to be aligned so that it can hold any type of data. In this system, the address is always a multiple of four on most systems.

Note that the memory located after the end of the block is likely to be in use for something else; perhaps a block already allocated by another call to malloc. If you attempt to treat the block as longer than you asked for it to be, you are liable to destroy the data that malloc uses to keep track of its blocks, or you may destroy the contents of another block. If you have already allocated a block and discover you want it to be bigger, use realloc (see  Changing Block Size ).

Math Error Reporting 
Previous:  Status bit operations , Up:  Floating Point Errors 




Error Reporting by Mathematical Functions

Many of the math functions are defined only over a subset of the real or complex numbers. Even if they are mathematically defined, their result may be larger or smaller than the range representable by their return type. These are known as domain errors, overflows, and underflows, respectively. Math functions do several things when one of these errors occurs. In this manual we will refer to the complete response as signalling a domain error, overflow, or underflow. 

When a math function suffers a domain error, it raises the invalid exception and returns NaN. It also sets errno to EDOM; this is for compatibility with old systems that do not support IEEE 754 exception handling. Likewise, when overflow occurs, math functions raise the overflow exception and return &infin; or -&infin; as appropriate. They also set errno to ERANGE. When underflow occurs, the underflow exception is raised, and zero (appropriately signed) is returned. errno may be set to ERANGE, but this is not guaranteed. 

Some of the math functions are defined mathematically to result in a complex value over parts of their domains. The most familiar example of this is taking the square root of a negative number. The complex math functions, such as csqrt, will return the appropriate complex value in this case. The real-valued functions, such as sqrt, will signal a domain error. 

Some older hardware does not support infinities. On that hardware, overflows instead return a particular very large number (usually the largest representable number). math.h defines macros you can use to test for overflow on both old and new hardware.
-- Macro: double HUGE_VAL

-- Macro: float HUGE_VALF

-- Macro: long double HUGE_VALL

An expression representing a particular very large number. On machines that use IEEE 754 floating point format, HUGE_VAL is infinity. On other machines, it's typically the largest positive number that can be represented. 

Mathematical functions return the appropriately typed version of HUGE_VAL or -HUGE_VAL when the result is too large to be represented.

Mathematical Constants 
Next:  Trig Functions , Up:  Mathematics 




Predefined Mathematical Constants

The header math.h defines several useful mathematical constants. All values are defined as preprocessor macros starting with M_. The values provided are:

M_E
The base of natural logarithms.
M_LOG2E
The logarithm to base 2 of M_E.
M_LOG10E
The logarithm to base 10 of M_E.
M_LN2
The natural logarithm of 2.
M_LN10
The natural logarithm of 10.
M_PI
Pi, the ratio of a circle's circumference to its diameter.
M_PI_2
Pi divided by two.
M_PI_4
Pi divided by four.
M_1_PI
The reciprocal of pi (1/pi)
M_2_PI
Two times the reciprocal of pi.
M_2_SQRTPI
Two times the reciprocal of the square root of pi.
M_SQRT2
The square root of two.
M_SQRT1_2
The reciprocal of the square root of two (also the square root of 1/2).

Mathematics
Next:  Arithmetic , Previous:  File System Interface , Up:  Top 




Mathematics

This chapter contains information about functions for performing mathematical computations, such as trigonometric functions. Most of these functions have prototypes declared in the header file math.h. The complex-valued functions are defined in complex.h. All mathematical functions which take a floating-point argument have three variants, one each for double, float, and long double arguments. The double versions are mostly defined in ISO C89. The float and long double versions are from the numeric extensions to C included in ISO C99. 

Which of the three versions of a function should be used depends on the situation. For most calculations, the float functions are the fastest. On the other hand, the long double functions have the highest precision. double is somewhere in between. It is usually wise to pick the narrowest type that can accommodate your data. Not all machines have a distinct long double type; it may be the same as double.

·  Mathematical Constants : Precise numeric values for often-used constants.
·  Trig Functions : Sine, cosine, tangent, and friends.
·  Inverse Trig Functions : Arcsine, arccosine, etc.
·  Exponents and Logarithms : Also pow and sqrt.
·  Hyperbolic Functions : sinh, cosh, tanh, etc.
·  Special Functions : Bessel, gamma, erf.
·  Pseudo-Random Numbers : Functions for generating pseudo-random numbers.
Memory Allocation and C 
Next:  Unconstrained Allocation , Up:  Memory Allocation 




Memory Allocation in C Programs

The C language supports two kinds of memory allocation through the variables in C programs:

· Static allocation is what happens when you declare a static or global variable. Each static or global variable defines one block of space, of a fixed size. The space is allocated once, when your program is started (part of the exec operation), and is never freed.
· Automatic allocation happens when you declare an automatic variable, such as a function argument or a local variable. The space for an automatic variable is allocated when the compound statement containing the declaration is entered, and is freed when that compound statement is exited. In C99 he size of the automatic storage can be an expression that varies. In earlier C implementations, it must be a constant.

A third important kind of memory allocation, dynamic allocation, is not supported by C variables but is available via C library functions.

Dynamic Memory Allocation

Dynamic memory allocation is a technique in which programs determine as they are running where to store some information. You need dynamic allocation when the amount of memory you need, or how long you continue to need it, depends on factors that are not known before the program runs. 

For example, you may need a block to store a line read from an input file; since there is no limit to how long a line can be, you must allocate the memory dynamically and make it dynamically larger as you read more of the line. 

Or, you may need a block for each record or each definition in the input data; since you can't know in advance how many there will be, you must allocate a new block for each record or definition as you read it. 

When you use dynamic allocation, the allocation of a block of memory is an action that the program requests explicitly. You call a function or macro when you want to allocate space, and specify the size with an argument. If you want to free the space, you do so by calling another function or macro. You can do these things whenever you want, as often as you want. 

Dynamic allocation is not supported by C variables; there is no storage class "dynamic", and there can never be a C variable whose value is stored in dynamically allocated space. The only way to get dynamically allocated memory is via a system call (which is generally via a C library function call), and the only way to refer to dynamically allocated space is through a pointer. Because it is less convenient, and because the actual process of dynamic allocation requires more computation time, programmers generally use dynamic allocation only when neither static nor automatic allocation will serve. 

For example, if you want to allocate dynamically some space to hold a struct foobar, you cannot declare a variable of type struct foobar whose contents are the dynamically allocated space. But you can declare a variable of pointer type struct foobar * and assign it the address of the space. Then you can use the operators `*' and `->' on this pointer variable to refer to the contents of the space:

     {
       struct foobar *ptr
          = (struct foobar *) malloc (sizeof (struct foobar));
       ptr->name = x;
       ptr->next = current_foobar;
       current_foobar = ptr;
     }

Memory Allocation 
Up:  Memory 




Allocating Storage For Program Data

This section covers how ordinary programs manage storage for their data, including the famous malloc function and some fancier facilities special to the C library and CC386 Compiler.

·  Memory Allocation and C : How to get different kinds of allocation in C.
·  Unconstrained Allocation : The malloc facility allows fully general dynamic allocation.
·  Variable Size Automatic : Allocation of variable-sized blocks of automatic storage that are freed when the calling function returns.

Memory
Next:  Character Handling , Previous:  Error Reporting , Up:  Top 




Virtual Memory Allocation And Paging

This chapter describes how processes manage and use memory in a system that uses the C library. 

The C Library has several functions for dynamically allocating virtual memory in various ways.

·  Memory Allocation : Allocating storage for your program data

· Memory mapped I/O is not discussed in this document.

Misc FP Arithmetic 
Previous:  FP Comparison Functions , Up:  Arithmetic Functions 




Miscellaneous FP arithmetic functions

The functions in this section perform miscellaneous but common operations that are awkward to express with C operators. On some processors these functions can use special machine instructions to perform these operations faster than the equivalent C code.

-- Function: double fmin (double x, double y)

-- Function: float fminf (float x, float y)

-- Function: long double fminl (long double x, long double y)

The fmin function returns the lesser of the two values x and y. It is similar to the expression 

          ((x) < (y) ? (x) : (y))
     
except that x and y are only evaluated once. 

If an argument is NaN, the other argument is returned. If both arguments are NaN, NaN is returned.

-- Function: double fmax (double x, double y)

-- Function: float fmaxf (float x, float y)

-- Function: long double fmaxl (long double x, long double y)

The fmax function returns the greater of the two values x and y. 

If an argument is NaN, the other argument is returned. If both arguments are NaN, NaN is returned.

-- Function: double fdim (double x, double y)

-- Function: float fdimf (float x, float y)

-- Function: long double fdiml (long double x, long double y)

The fdim function returns the positive difference between x and y. The positive difference is x - y if x is greater than y, and 0 otherwise. 

If x, y, or both are NaN, NaN is returned.

-- Function: double fma (double x, double y, double z)

-- Function: float fmaf (float x, float y, float z)

-- Function: long double fmal (long double x, long double y, long double z)

The fma function performs floating-point multiply-add. This is the operation (x * y) + z, but the intermediate result is not rounded to the destination type. This can sometimes improve the precision of a calculation. 

This function was introduced because some processors have a special instruction to perform multiply-add. The C compiler cannot use it directly, because the expression `x*y + z' is defined to round the intermediate result. fma lets you choose when you want to round only once. 

On processors which do not implement multiply-add in hardware, fma can be very slow since it must avoid intermediate rounding. math.h defines the symbols FP_FAST_FMA, FP_FAST_FMAF, and FP_FAST_FMAL when the corresponding version of fma is no slower than the expression `x*y + z'.

Miscellaneous Signals 
Previous:  Program Error Signals , Up:  Standard Signals 




Miscellaneous Signals

These signals are used for various other purposes. In general, they will not affect your program unless it explicitly uses them for something.

-- Macro: int SIGUSR1

-- Macro: int SIGUSR2

The SIGUSR1 and SIGUSR2 signals are set aside for you to use any way you want. They're useful for simple interprocess communication, if you write a signal handler for them in the program that receives the signal. 

The default action is to terminate the process.


Multibyte Conversion Example 
Previous:  Converting Strings , Up:  Restartable multibyte conversion 




A Complete Multibyte Conversion Example

The example programs given in the last sections are only brief and do not contain all the error checking, etc. Presented here is a complete and documented example. It features the mbrtowc function but it should be easy to derive versions using the other functions.

     int
     file_mbsrtowcs (int input, int output)
     {
       /* Note the use of MB_LEN_MAX.
          MB_CUR_MAX cannot portably be used here.  */
       char buffer[BUFSIZ + MB_LEN_MAX];
       mbstate_t state;
       int filled = 0;
       int eof = 0;
     
       /* Initialize the state.  */
       memset (&state, '\0', sizeof (state));
     
       while (!eof)
         {
           ssize_t nread;
           ssize_t nwrite;
           char *inp = buffer;
           wchar_t outbuf[BUFSIZ];
           wchar_t *outp = outbuf;
     
           /* Fill up the buffer from the input file.  */
           nread = read (input, buffer + filled, BUFSIZ);
           if (nread < 0)
             {
               perror ("read");
               return 0;
             }
           /* If we reach end of file, make a note to read no more. */
           if (nread == 0)
             eof = 1;
     
           /* filled is now the number of bytes in buffer. */
           filled += nread;
     
           /* Convert those bytes to wide characters--as many as we can. */
           while (1)
             {
               size_t thislen = mbrtowc (outp, inp, filled, &state);
               /* Stop converting at invalid character;
                  this can mean we have read just the first part
                  of a valid character.  */
               if (thislen == (size_t) -1)
                 break;
               /* We want to handle embedded NUL bytes
                  but the return value is 0.  Correct this.  */
               if (thislen == 0)
                 thislen = 1;
               /* Advance past this character. */
               inp += thislen;
               filled -= thislen;
               ++outp;
             }
     
           /* Write the wide characters we just made.  */
           nwrite = write (output, outbuf,
                           (outp - outbuf) * sizeof (wchar_t));
           if (nwrite < 0)
             {
               perror ("write");
               return 0;
             }
     
           /* See if we have a real invalid character. */
           if ((eof && filled > 0) || filled >= MB_CUR_MAX)
             {
               error (0, 0, "invalid multibyte character");
               return 0;
             }
     
           /* If any characters must be carried forward,
              put them at the beginning of buffer. */
           if (filled > 0)
             memmove (inp, buffer, filled);
         }
     
       return 1;
     }

Nonreentrancy
Next:  Atomic Data Access , Previous:  Signals in Handler , Up:  Defining Handlers 




Signal Handling and Nonreentrant Functions

Handler functions usually don't do very much. The best practice is to write a handler that does nothing but set an external variable that the program checks regularly, and leave all serious work to the program. This is best because the handler can be called asynchronously, at unpredictable times--perhaps in the middle of a primitive function, or even between the beginning and the end of a C operator that requires multiple instructions. The data structures being manipulated might therefore be in an inconsistent state when the handler function is invoked. Even copying one int variable into another can take two instructions on most machines. 

This means you have to be very careful about what you do in a signal handler.

· If your handler needs to access any global variables from your program, declare those variables volatile. This tells the compiler that the value of the variable might change asynchronously, and inhibits certain optimizations that would be invalidated by such modifications. 
· If you call a function in the handler, make sure it is reentrant with respect to signals, or else make sure that the signal cannot interrupt a call to a related function.

A function can be non-reentrant if it uses memory that is not on the stack.

· If a function uses a static variable or a global variable, or a dynamically-allocated object that it finds for itself, then it is non-reentrant and any two calls to the function can interfere. 

For example, suppose that the signal handler uses gethostbyname. This function returns its value in a static object, reusing the same object each time. If the signal happens to arrive during a call to gethostbyname, or even after one (while the program is still using the value), it will clobber the value that the program asked for. 

However, if the program does not use gethostbyname or any other function that returns information in the same object, or if it always blocks signals around each use, then you are safe. 

There are a large number of library functions that return values in a fixed object, always reusing the same object in this fashion, and all of them cause the same problem. Function descriptions in this manual always mention this behavior. 
· If a function uses and modifies an object that you supply, then it is potentially non-reentrant; two calls can interfere if they use the same object. 

This case arises when you do I/O using streams. Suppose that the signal handler prints a message with fprintf. Suppose that the program was in the middle of an fprintf call using the same stream when the signal was delivered. Both the signal handler's message and the program's data could be corrupted, because both calls operate on the same data structure--the stream itself. 

However, if you know that the stream that the handler uses cannot possibly be used by the program at a time when signals can arrive, then you are safe. It is no problem if the program uses some other stream. 
· On most systems, malloc and free are not reentrant, because they use a static data structure which records what memory blocks are free. As a result, no library functions that allocate or free memory are reentrant. This includes functions that allocate space to store a result. 

The best way to avoid the need to allocate memory in a handler is to allocate in advance space for signal handlers to use. 

The best way to avoid freeing memory in a handler is to flag or record the objects to be freed, and have the program check from time to time whether anything is waiting to be freed. But this must be done with care, because placing an object on a chain is not atomic, and if it is interrupted by another signal handler that does the same thing, you could "lose" one of the objects. 
· Any function that modifies errno is non-reentrant, but you can correct for this: in the handler, save the original value of errno and restore it before returning normally. This prevents errors that occur within the signal handler from being confused with errors from system calls at the point the program is interrupted to run the handler. 

This technique is generally applicable; if you want to call in a handler a function that modifies a particular object in memory, you can make this safe by saving and restoring that object. 
· Merely reading from a memory object is safe provided that you can deal with any of the values that might appear in the object at a time when the signal can be delivered. Keep in mind that assignment to some data types requires more than one instruction, which means that the handler could run "in the middle of" an assignment to the variable if its type is not atomic. See  Atomic Data Access . 
· Merely writing into a memory object is safe as long as a sudden change in the value, at any time when the handler might run, will not disturb anything.

Non-atomic Example 
Next:  Atomic Types , Up:  Atomic Data Access 




Problems with Non-Atomic Access

Here is an example which shows what can happen if a signal handler runs in the middle of modifying a variable. (Interrupting the reading of a variable can also lead to paradoxical results, but here we only show writing.)

     #include <signal.h>
     #include <stdio.h>
     
     struct two_words { int a, b; } memory;
     
     void
     handler(int signum)
     {
        printf ("%d,%d\n", memory.a, memory.b);
        alarm (1);
     }
     
     int
     main (void)
     {
        static struct two_words zeros = { 0, 0 }, ones = { 1, 1 };
        signal (SIGALRM, handler);
        memory = zeros;
        alarm (1);
        while (1)
          {
            memory = zeros;
            memory = ones;
          }
     }

This program fills memory with zeros, ones, zeros, ones, alternating forever; meanwhile, once per second, the alarm signal handler prints the current contents. (Calling printf in the handler is safe in this program because it is certainly not being called outside the handler when the signal happens.) 

Clearly, this program can print a pair of zeros or a pair of ones. But that's not all it can do! On most machines, it takes several instructions to store a new value in memory, and the value is stored one word at a time. If the signal is delivered in between these instructions, the handler might find that memory.a is zero and memory.b is one (or vice versa). 

On some machines it may be possible to store a new value in memory with just one instruction that cannot be interrupted. On these machines, the handler will always print two zeros or two ones.

Non-Local Details 
Previous:  Non-Local Intro , Up:  Non-Local Exits 




Details of Non-Local Exits

Here are the details on the functions and data structures used for performing non-local exits. These facilities are declared in setjmp.h.

-- Data Type: jmp_buf

Objects of type jmp_buf hold the state information to be restored by a non-local exit. The contents of a jmp_buf identify a specific place to return to.

-- Macro: int setjmp (jmp_buf state)

When called normally, setjmp stores information about the execution state of the program in state and returns zero. If longjmp is later used to perform a non-local exit to this state, setjmp returns a nonzero value.

-- Function: void longjmp (jmp_buf state, int value)

This function restores current execution to the state saved in state, and continues execution from the call to setjmp that established that return point. Returning from setjmp by means of longjmp returns the value argument that was passed to longjmp, rather than 0. (But if value is given as 0, setjmp returns 1).

There are a lot of obscure but important restrictions on the use of setjmp and longjmp. Most of these restrictions are present because non-local exits require a fair amount of magic on the part of the C compiler and can interact with other parts of the language in strange ways. 

The setjmp function is actually a macro without an actual function definition, so you shouldn't try to `#undef' it or take its address. In addition, calls to setjmp are safe in only the following contexts:

· As the test expression of a selection or iteration statement (such as `if', `switch', or `while'). 
· As one operand of a equality or comparison operator that appears as the test expression of a selection or iteration statement. The other operand must be an integer constant expression. 
· As the operand of a unary `!' operator, that appears as the test expression of a selection or iteration statement. 
· By itself as an expression statement.

Return points are valid only during the dynamic extent of the function that called setjmp to establish them. If you longjmp to a return point that was established in a function that has already returned, unpredictable and disastrous things are likely to happen. 

You should use a nonzero value argument to longjmp. While longjmp refuses to pass back a zero argument as the return value from setjmp, this is intended as a safety net against accidental misuse and is not really good programming style. 

When you perform a non-local exit, accessible objects generally retain whatever values they had at the time longjmp was called. The exception is that the values of automatic variables local to the function containing the setjmp call that have been changed since the call to setjmp are indeterminate, unless you have declared them volatile.

Non-Local Exits 
Next:  Signal Handling , Previous: Date and Time, Up:  Top 




Non-Local Exits

Sometimes when your program detects an unusual situation inside a deeply nested set of function calls, you would like to be able to immediately return to an outer level of control. This section describes how you can do such non-local exits using the setjmp and longjmp functions.

·  Intro : When and how to use these facilities.
·  Details : Functions for non-local exits.
Non-Local Intro 
Next:  Non-Local Details , Up:  Non-Local Exits 




Introduction to Non-Local Exits

As an example of a situation where a non-local exit can be useful, suppose you have an interactive program that has a "main loop" that prompts for and executes commands. Suppose the "read" command reads input from a file, doing some lexical analysis and parsing of the input while processing it. If a low-level input error is detected, it would be useful to be able to return immediately to the "main loop" instead of having to make each of the lexical analysis, parsing, and processing phases all have to explicitly deal with error situations initially detected by nested calls. 

(On the other hand, if each of these phases has to do a substantial amount of cleanup when it exits--such as closing files, deallocating buffers or other data structures, and the like--then it can be more appropriate to do a normal return and have each phase do its own cleanup, because a non-local exit would bypass the intervening phases and their associated cleanup code entirely. Alternatively, you could use a non-local exit but do the cleanup explicitly either before or after returning to the "main loop".) 

In some ways, a non-local exit is similar to using the `return' statement to return from a function. But while `return' abandons only a single function call, transferring control back to the point at which it was called, a non-local exit can potentially abandon many levels of nested function calls. 

You identify return points for non-local exits by calling the function setjmp. This function saves information about the execution environment in which the call to setjmp appears in an object of type jmp_buf. Execution of the program continues normally after the call to setjmp, but if an exit is later made to this return point by calling longjmp with the corresponding jmp_buf object, control is transferred back to the point where setjmp was called. The return value from setjmp is used to distinguish between an ordinary return and a return made by a call to longjmp, so calls to setjmp usually appear in an `if' statement. 

Here is how the example program described above might be set up:

     #include <setjmp.h>
     #include <stdlib.h>
     #include <stdio.h>
     
     jmp_buf main_loop;
     
     void
     abort_to_main_loop (int status)
     {
       longjmp (main_loop, status);
     }
     
     int
     main (void)
     {
       while (1)
         if (setjmp (main_loop))
           puts ("Back at main loop....");
         else
           do_command ();
     }
     
     
     void
     do_command (void)
     {
       char buffer[128];
       if (fgets (buffer, 128, stdin) == NULL)
         abort_to_main_loop (-1);
       else
         exit (EXIT_SUCCESS);
     }

The function abort_to_main_loop causes an immediate transfer of control back to the main loop of the program, no matter where it is called from. 

The flow of control inside the main function may appear a little mysterious at first, but it is actually a common idiom with setjmp. A normal call to setjmp returns zero, so the "else" clause of the conditional is executed. If abort_to_main_loop is called somewhere within the execution of do_command, then it actually appears as if the same call to setjmp in main were returning a second time with a value of -1. 

So, the general pattern for using setjmp looks something like:

     if (setjmp (buffer))
       /* Code to clean up after premature return. */
       ...
     else
       /* Code to be executed normally after setting up the return point. */
       ...

Non-reentrant Character Conversion 
Next:  Non-reentrant String Conversion , Up:  Non-reentrant Conversion 




Non-reentrant Conversion of Single Characters

-- Function: int mbtowc (wchar_t *restrict result, const char *restrict string, size_t size)

The mbtowc ("multibyte to wide character") function when called with non-null string converts the first multibyte character beginning at string to its corresponding wide character code. It stores the result in *result. 

mbtowc never examines more than size bytes. (The idea is to supply for size the number of bytes of data you have in hand.) 

mbtowc with non-null string distinguishes three possibilities: the first size bytes at string start with valid multibyte characters, they start with an invalid byte sequence or just part of a character, or string points to an empty string (a null character). 

For a valid multibyte character, mbtowc converts it to a wide character and stores that in *result, and returns the number of bytes in that character (always at least 1 and never more than size). 

For an invalid byte sequence, mbtowc returns -1. For an empty string, it returns 0, also storing '\0' in *result. 

If the multibyte character code uses shift characters, then mbtowc maintains and updates a shift state as it scans. If you call mbtowc with a null pointer for string, that initializes the shift state to its standard initial value. It also returns nonzero if the multibyte character code in use actually has a shift state. See  Shift State .

-- Function: int wctomb (char *string, wchar_t wchar)

The wctomb ("wide character to multibyte") function converts the wide character code wchar to its corresponding multibyte character sequence, and stores the result in bytes starting at string. At most MB_CUR_MAX characters are stored. 

wctomb with non-null string distinguishes three possibilities for wchar: a valid wide character code (one that can be translated to a multibyte character), an invalid code, and L'\0'. 

Given a valid code, wctomb converts it to a multibyte character, storing the bytes starting at string. Then it returns the number of bytes in that character (always at least 1 and never more than MB_CUR_MAX). 

If wchar is an invalid wide character code, wctomb returns -1. If wchar is L'\0', it returns 0, also storing '\0' in *string. 

If the multibyte character code uses shift characters, then wctomb maintains and updates a shift state as it scans. If you call wctomb with a null pointer for string, that initializes the shift state to its standard initial value. It also returns nonzero if the multibyte character code in use actually has a shift state. See  Shift State . 

Calling this function with a wchar argument of zero when string is not null has the side-effect of reinitializing the stored shift state as well as storing the multibyte character '\0' and returning 0.

Similar to mbrlen there is also a non-reentrant function that computes the length of a multibyte character. It can be defined in terms of mbtowc.
-- Function: int mblen (const char *string, size_t size)

The mblen function with a non-null string argument returns the number of bytes that make up the multibyte character beginning at string, never examining more than size bytes. (The idea is to supply for size the number of bytes of data you have in hand.) 

The return value of mblen distinguishes three possibilities: the first size bytes at string start with valid multibyte characters, they start with an invalid byte sequence or just part of a character, or string points to an empty string (a null character). 

For a valid multibyte character, mblen returns the number of bytes in that character (always at least 1 and never more than size). For an invalid byte sequence, mblen returns -1. For an empty string, it returns 0. 

If the multibyte character code uses shift characters, then mblen maintains and updates a shift state as it scans. If you call mblen with a null pointer for string, that initializes the shift state to its standard initial value. It also returns a nonzero value if the multibyte character code in use actually has a shift state. See  Shift State . 

The function mblen is declared in stdlib.h.

Non-reentrant Conversion 
Previous:  Restartable multibyte conversion , Up:  Character Set Handling 




Non-reentrant Conversion Function

The functions described in the previous chapter are defined in Amendment 1 to ISO C90, but the original ISO C90 standard also contained functions for character set conversion. The reason that these original functions are not described first is that they are almost entirely useless. 

The problem is that all the conversion functions described in the original ISO C90 use a local state. Using a local state implies that multiple conversions at the same time (not only when using threads) cannot be done, and that you cannot first convert single characters and then strings since you cannot tell the conversion functions which state to use. 

These original functions are therefore usable only in a very limited set of situations. One must complete converting the entire string before starting a new one, and each string/text must be converted with the same function (there is no problem with the library itself; it is guaranteed that no library function changes the state of any of these functions). For the above reasons it is highly requested that the functions described in the previous section be used in place of non-reentrant conversion functions.

·  Non-reentrant Character Conversion : Non-reentrant Conversion of Single Characters.
·  Non-reentrant String Conversion : Non-reentrant Conversion of Strings.
·  Shift State : States in Non-reentrant Functions.

Non-reentrant String Conversion 
Next:  Shift State , Previous:  Non-reentrant Character Conversion , Up:  Non-reentrant Conversion 




Non-reentrant Conversion of Strings

For convenience the ISO C90 standard also defines functions to convert entire strings instead of single characters. These functions suffer from the same problems as their reentrant counterparts from Amendment 1 to ISO C90; see  Converting Strings .

-- Function: size_t mbstowcs (wchar_t *wstring, const char *string, size_t size)

The mbstowcs ("multibyte string to wide character string") function converts the null-terminated string of multibyte characters string to an array of wide character codes, storing not more than size wide characters into the array beginning at wstring. The terminating null character counts towards the size, so if size is less than the actual number of wide characters resulting from string, no terminating null character is stored. 

The conversion of characters from string begins in the initial shift state. 

If an invalid multibyte character sequence is found, the mbstowcs function returns a value of -1. Otherwise, it returns the number of wide characters stored in the array wstring. This number does not include the terminating null character, which is present if the number is less than size. 

Here is an example showing how to convert a string of multibyte characters, allocating enough space for the result. 

          wchar_t *
          mbstowcs_alloc (const char *string)
          {
            size_t size = strlen (string) + 1;
            wchar_t *buf = xmalloc (size * sizeof (wchar_t));
          
            size = mbstowcs (buf, string, size);
            if (size == (size_t) -1)
              return NULL;
            buf = xrealloc (buf, (size + 1) * sizeof (wchar_t));
            return buf;
          }
     
-- Function: size_t wcstombs (char *string, const wchar_t *wstring, size_t size)

The wcstombs ("wide character string to multibyte string") function converts the null-terminated wide character array wstring into a string containing multibyte characters, storing not more than size bytes starting at string, followed by a terminating null character if there is room. The conversion of characters begins in the initial shift state. 

The terminating null character counts towards the size, so if size is less than or equal to the number of bytes needed in wstring, no terminating null character is stored. 

If a code that does not correspond to a valid multibyte character is found, the wcstombs function returns a value of -1. Otherwise, the return value is the number of bytes stored in the array string. This number does not include the terminating null character, which is present if the number is less than size.

Normal Termination 
Next:  Exit Status , Up:  Program Termination 




Normal Termination

A process terminates normally when its program signals it is done by calling exit. Returning from main is equivalent to calling exit, and the value that main returns is used as the argument to exit.

-- Function: void exit (int status)

The exit function tells the system that the program is done, which causes it to terminate the process. 

status is the program's exit status, which becomes part of the process' termination status. This function does not return.

Normal termination causes the following actions:

1. Functions that were registered with the atexit function are called in the reverse order of their registration. This mechanism allows your application to specify its own "cleanup" actions to be performed at program termination. Typically, this is used to do things like saving program state information in a file, or unlocking locks in shared data bases. 
2. All open streams are closed, writing out any buffered output data. See  Closing Streams . In addition, temporary files opened with the tmpfile function are removed; see  Temporary Files . 
3. _exit is called, terminating the program.

Normalization Functions 
Next:  Rounding Functions , Previous:  Absolute Value , Up:  Arithmetic Functions 




Normalization Functions

The functions described in this section are primarily provided as a way to efficiently perform certain low-level manipulations on floating point numbers that are represented internally using a binary radix; see  Floating Point Concepts . These functions are required to have equivalent behavior even if the representation does not use a radix of 2, but of course they are unlikely to be particularly efficient in those cases. 


All these functions are declared in math.h.
-- Function: double frexp (double value, int *exponent)

-- Function: float frexpf (float value, int *exponent)

-- Function: long double frexpl (long double value, int *exponent)

These functions are used to split the number value into a normalized fraction and an exponent. 

If the argument value is not zero, the return value is value times a power of two, and is always in the range 1/2 (inclusive) to 1 (exclusive). The corresponding exponent is stored in *exponent; the return value multiplied by 2 raised to this exponent equals the original number value. 

For example, frexp (12.8, &exponent) returns 0.8 and stores 4 in exponent. 

If value is zero, then the return value is zero and zero is stored in *exponent.

-- Function: double ldexp (double value, int exponent)

-- Function: float ldexpf (float value, int exponent)

-- Function: long double ldexpl (long double value, int exponent)

These functions return the result of multiplying the floating-point number value by 2 raised to the power exponent. (It can be used to reassemble floating-point numbers that were taken apart by frexp.) 

For example, ldexp (0.8, 4) returns 12.8.

The following functions, which come from BSD, provide facilities equivalent to those of ldexp and frexp. See also the ISO C function logb which originally also appeared in BSD.
-- Function: double scalb (double value, int exponent)

-- Function: float scalbf (float value, int exponent)

-- Function: long double scalbl (long double value, int exponent)

The scalb function is the BSD name for ldexp.

-- Function: long long int scalbn (double x, int n)

-- Function: long long int scalbnf (float x, int n)

-- Function: long long int scalbnl (long double x, int n)

scalbn is identical to scalb, except that the exponent n is an int instead of a floating-point number.

-- Function: long long int scalbln (double x, long int n)

-- Function: long long int scalblnf (float x, long int n)

-- Function: long long int scalblnl (long double x, long int n)

scalbln is identical to scalb, except that the exponent n is a long int instead of a floating-point number.

-- Function: long long int significand (double x)

-- Function: long long int significandf (float x)

-- Function: long long int significandl (long double x)

significand returns the mantissa of x scaled to the range [1, 2). It is equivalent to scalb (x, (double) -ilogb (x)). 

This function exists mainly for use in certain standardized tests of IEEE 754 conformance.

Null Pointer Constant 
Next:  Important Data Types , Previous:  Variadic Functions , Up:  Language Features 




Null Pointer Constant

The null pointer constant is guaranteed not to point to any real object. You can assign it to any pointer variable since it has type void *. The preferred way to write a null pointer constant is with NULL.

-- Macro: void * NULL

This is a null pointer constant.

You can also use 0 or (void *)0 as a null pointer constant, but using NULL is cleaner because it makes the purpose of the constant more evident. 

If you use the null pointer constant as a function argument, then for complete portability you should make sure that the function has a prototype declaration. Otherwise, if the target machine has two different pointer representations, the compiler won't know which representation to use for that argument. You can avoid the problem by explicitly casting the constant to the proper pointer type, but we recommend instead adding a prototype for the function you are calling.

Numeric Input Conversions 
Next:  String Input Conversions , Previous:  Table of Input Conversions , Up:  Formatted Input 




Numeric Input Conversions

This section describes the scanf conversions for reading numeric values. 

The `%d' conversion matches an optionally signed integer in decimal radix. The syntax that is recognized is the same as that for the strtol function (see  Parsing of Integers ) with the value 10 for the base argument. 

The `%i' conversion matches an optionally signed integer in any of the formats that the C language defines for specifying an integer constant. The syntax that is recognized is the same as that for the strtol function (see  Parsing of Integers ) with the value 0 for the base argument. (You can print integers in this syntax with printf by using the `#' flag character with the `%x', `%o', or `%d' conversion. See  Integer Conversions .) 

For example, any of the strings `10', `0xa', or `012' could be read in as integers under the `%i' conversion. Each of these specifies a number with decimal value 10. 

The `%o', `%u', and `%x' conversions match unsigned integers in octal, decimal, and hexadecimal radices, respectively. The syntax that is recognized is the same as that for the strtoul function (see  Parsing of Integers ) with the appropriate value (8, 10, or 16) for the base argument. 

The `%X' conversion is identical to the `%x' conversion. They both permit either uppercase or lowercase letters to be used as digits. 

The default type of the corresponding argument for the %d and %i conversions is int *, and unsigned int * for the other integer conversions. You can use the following type modifiers to specify other sizes of integer:

`hh'
Specifies that the argument is a signed char * or unsigned char *. 

This modifier was introduced in ISO C99. 
`h'
Specifies that the argument is a short int * or unsigned short int *. 
`j'
Specifies that the argument is a intmax_t * or uintmax_t *. 

This modifier was introduced in ISO C99. 
`l'
Specifies that the argument is a long int * or unsigned long int *. Two `l' characters is like the `L' modifier, below. 

If used with `%c' or `%s' the corresponding parameter is considered as a pointer to a wide character or wide character string respectively. This use of `l' was introduced in Amendment 1 to ISO C90. 
`ll'
Specifies that the argument is a long long int * or unsigned long long int *. 
`t'
Specifies that the argument is a ptrdiff_t *. 

This modifier was introduced in ISO C99. 
`z'
Specifies that the argument is a size_t *. 

This modifier was introduced in ISO C99.

All of the `%e', `%f', `%g', `%E', and `%G' input conversions are interchangeable. They all match an optionally signed floating point number, in the same syntax as for the strtod function (see  Parsing of Floats ). 

For the floating-point input conversions, the default argument type is float *. (This is different from the corresponding output conversions, where the default type is double; remember that float arguments to printf are converted to double by the default argument promotions, but float * arguments are not promoted to double *.) You can specify other sizes of float using these type modifiers:

`l'
Specifies that the argument is of type double *. 
`L'
Specifies that the argument is of type long double *.

For all the above number parsing formats there is an additional optional flag `''. When this flag is given the scanf function expects the number represented in the input string to be formatted according to the grouping rules of the currently selected locale (see  General Numeric ). 

If the "C" or "POSIX" locale is selected there is no difference. But for a locale which specifies values for the appropriate fields in the locale the input must have the correct form in the input. Otherwise the longest prefix with a correct form is processed.

Opening and Closing Files 
Next:  I/O Primitives , Up:  Low-Level I/O 




Opening and Closing Files

This section describes the primitives for opening and closing files using file descriptors. The open and creat functions are declared in the header file fcntl.h, while close is declared in unistd.h.

-- Function: int open (const char *filename, int flags[, mode_t mode])

The open function creates and returns a new file descriptor for the file named by filename. Initially, the file position indicator for the file is at the beginning of the file. The argument mode is used only when a file is created, but it doesn't hurt to supply the argument in any case. 

The flags argument controls how the file is to be opened. This is a bit mask; you create the value by the bitwise OR of the appropriate parameters (using the `|' operator in C). See  File Status Flags , for the parameters available. 

The normal return value from open is a non-negative integer file descriptor. In the case of an error, a value of -1 is returned instead. In addition to the usual file name errors (see  File Name Errors ), the following errno error conditions are defined for this function:

EACCES
The file exists but is not readable/writable as requested by the flags argument, the file does not exist and the directory is unwritable so it cannot be created. 
EEXIST
Both O_CREAT and O_EXCL are set, and the named file already exists. 
EMFILE
           The process has too many files open. 
ENFILE
The entire system, or perhaps the file system which contains the directory, cannot support any additional open files at the moment. (This problem cannot happen on the GNU system.) 
ENOENT
The named file does not exist, and O_CREAT is not specified. 
ENOSPC
The directory or file system that would contain the new file cannot be extended, because there is no disk space left. 
ENXIO
O_NONBLOCK and O_WRONLY are both set in the flags argument, the file named by filename is a FIFO (see  Pipes and FIFOs ), and no process has the file open for reading. 
EROFS
The file resides on a read-only file system and any of O_WRONLY, O_RDWR, and O_TRUNC are set in the flags argument, or O_CREAT is set and the file does not already exist.

-- Obsolete function: int creat (const char *filename, mode_t mode)

This function is obsolete. The call: 

          creat (filename, mode)
     
is equivalent to: 

          open (filename, O_WRONLY | O_CREAT | O_TRUNC, mode)
     
-- Function: int close (int filedes)

The function close closes the file descriptor filedes. Closing a file has the following consequences:

· The file descriptor is deallocated. 
· Any record locks owned by the process on the file are unlocked. 
· When all file descriptors associated with a pipe or FIFO have been closed, any unread data is discarded.

This function is a cancellation point in multi-threaded programs. This is a problem if the thread allocates some resources (like memory, file descriptors, semaphores or whatever) at the time close is called. If the thread gets canceled these resources stay allocated until the program ends. To avoid this, calls to close should be protected using cancellation handlers. 

The normal return value from close is 0; a value of -1 is returned in case of failure. The following errno error conditions are defined for this function:

EBADF
The filedes argument is not a valid file descriptor. 
ENOSPC
EIO
EDQUOT
When the file is accessed by NFS, these errors from write can sometimes not be detected until close. See  I/O Primitives , for details on their meaning.

To close a stream, call fclose (see  Closing Streams ) instead of trying to close its underlying file descriptor with close. This flushes any buffered output and updates the stream object to indicate that it is closed.

Opening Streams 
Next:  Closing Streams , Previous:  Standard Streams , Up:  I/O on Streams 




Opening Streams

Opening a file with the fopen function creates a new stream and establishes a connection between the stream and a file. This may involve creating a new file. 

Everything described in this section is declared in the header file stdio.h.

-- Function: FILE * fopen (const char *filename, const char *opentype)

The fopen function opens a stream for I/O to the file filename, and returns a pointer to the stream. 

The opentype argument is a string that controls how the file is opened and specifies attributes of the resulting stream. It must begin with one of the following sequences of characters:

`r'
Open an existing file for reading only. 
`w'
Open the file for writing only. If the file already exists, it is truncated to zero length. Otherwise a new file is created. 
`a'
Open a file for append access; that is, writing at the end of file only. If the file already exists, its initial contents are unchanged and output to the stream is appended to the end of the file. Otherwise, a new, empty file is created. 
`r+'
Open an existing file for both reading and writing. The initial contents of the file are unchanged and the initial file position is at the beginning of the file. 
`w+'
Open a file for both reading and writing. If the file already exists, it is truncated to zero length. Otherwise, a new file is created. 
`a+'
Open or create file for both reading and appending. If the file exists, its initial contents are unchanged. Otherwise, a new file is created. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.

As you can see, `+' requests a stream that can do both input and output. The ISO standard says that when using such a stream, you must call fflush (see  Stream Buffering ) or a file positioning function such as fseek (see  File Positioning ) when switching from reading to writing or vice versa. Otherwise, internal buffers might not be emptied properly. 

Additional characters may appear after these to specify flags for the call. Always put the mode (`r', `w+', etc.) first; that is the only part you are guaranteed will be understood by all systems. 

The character `b' in opentype has a standard meaning; it requests a binary stream rather than a text stream. But this makes no difference in POSIX systems (including the GNU system). If both `+' and `b' are specified, they can appear in either order. See  Binary Streams . 

The stream is opened initially unoriented and the orientation is decided with the first file operation. If the first operation is a wide character operation, the stream is not only marked as wide-oriented, also the conversion functions to convert to the coded character set used for the current locale are loaded. This will not change anymore from this point on even if the locale selected for the LC_CTYPE category is changed. 

Any other characters in opentype are simply ignored. They may be meaningful in other systems. 

If the open fails, fopen returns a null pointer. 

You can have multiple streams (or file descriptors) pointing to the same file open at the same time. If you do only input, this works straightforwardly, but you must be careful if any output streams are included. See  Stream/Descriptor Precautions . This is equally true whether the streams are in one program (not usual) or in several programs (which can easily happen). 

-- Macro: int FOPEN_MAX

The value of this macro is an integer constant expression that represents the minimum number of streams that the implementation guarantees can be open simultaneously. You might be able to open more than this many streams, but that is not guaranteed. The value of this constant is at least eight, which includes the three standard streams stdin, stdout, and stderr. In POSIX.1 systems this value is determined by the OPEN_MAX parameter; see  General Limits . In BSD and GNU, it is controlled by the RLIMIT_NOFILE resource limit; see  Limits on Resources .

-- Function: FILE * freopen (const char *filename, const char *opentype, FILE *stream)

This function is like a combination of fclose and fopen. It first closes the stream referred to by stream, ignoring any errors that are detected in the process. (Because errors are ignored, you should not use freopen on an output stream if you have actually done any output using the stream.) Then the file named by filename is opened with mode opentype as for fopen, and associated with the same stream object stream. 

If the operation fails, a null pointer is returned; otherwise, freopen returns stream. 

freopen has traditionally been used to connect a standard stream such as stdin with a file of your own choice. This is useful in programs in which use of a standard stream for certain purposes is hard-coded. In this C library, you can simply close the standard streams and open new ones with fopen. But other systems lack this ability, so using freopen is more portable. 

Open-time Flags 
Next:  Operating Modes , Previous:  Access Modes , Up:  File Status Flags 




Open-time Flags

The open-time flags specify options affecting how open will behave. These options are not preserved once the file is open. See  Opening and Closing Files , for how to call open. 

There are two sorts of options specified by open-time flags.

· File name translation flags affect how open looks up the file name to locate the file, and whether the file can be created.
· Open-time action flags specify extra operations that open will perform on the file once it is open.

Here are the file name translation flags.

-- Macro: int O_CREAT

If set, the file will be created if it doesn't already exist.

-- Macro: int O_EXCL

If both O_CREAT and O_EXCL are set, then open fails if the specified file already exists. This is guaranteed to never clobber an existing file.

The open-time action flags tell open to do additional operations which are not really related to opening the file. The reason to do them as part of open instead of in separate calls is that open can do them atomically.

-- Macro: int O_TRUNC

Truncate the file to zero length. This option is only useful for regular files, not special files such as directories or FIFOs. POSIX.1 requires that you open the file for writing to use O_TRUNC. In BSD and GNU you must have permission to write the file to truncate it, but you need not open for write access. 

This is the only open-time action flag specified by POSIX.1. There is no good reason for truncation to be done by open, instead of by calling ftruncate afterwards. The O_TRUNC flag existed in Unix before ftruncate was invented, and is retained for backward compatibility.

Operating Modes 
Previous:  Open-time Flags , Up:  File Status Flags 




I/O Operating Modes

The operating modes affect how input and output operations using a file descriptor work. These flags are set by open and can be fetched and changed with fcntl.
-- Macro: int O_APPEND

The bit that enables append mode for the file. If set, then all write operations write the data at the end of the file, extending it, regardless of the current file position. This is the only reliable way to append to a file. In append mode, you are guaranteed that the data you write will always go to the current end of the file, regardless of other processes writing to the file. Conversely, if you simply set the file position to the end of file and write, then another process can extend the file after you set the file position but before you write, resulting in your data appearing someplace before the real end of file.

Operations on Complex 
Next:  Parsing of Numbers , Previous:  Complex Numbers , Up:  Arithmetic 




Projections, Conjugates, and Decomposing of Complex Numbers

ISO C99 also defines functions that perform basic operations on complex numbers, such as decomposition and conjugation. The prototypes for all these functions are in complex.h. All functions are available in three variants, one for each of the three complex types.

-- Function: double creal (complex double z)

-- Function: float crealf (complex float z)

-- Function: long double creall (complex long double z)

These functions return the real part of the complex number z.

-- Function: double cimag (complex double z)

-- Function: float cimagf (complex float z)

-- Function: long double cimagl (complex long double z)

These functions return the imaginary part of the complex number z.

-- Function: complex double conj (complex double z)

-- Function: complex float conjf (complex float z)

-- Function: complex long double conjl (complex long double z)

These functions return the conjugate value of the complex number z. The conjugate of a complex number has the same real part and a negated imaginary part. In other words, `conj(a + bi) = a + -bi'.

-- Function: double carg (complex double z)

-- Function: float cargf (complex float z)

-- Function: long double cargl (complex long double z)

These functions return the argument of the complex number z. The argument of a complex number is the angle in the complex plane between the positive real axis and a line passing through zero and the number. This angle is measured in the usual fashion and ranges from 0 to 2&pi;. 

carg has a branch cut along the positive real axis.

-- Function: complex double cproj (complex double z)

-- Function: complex float cprojf (complex float z)

-- Function: complex long double cprojl (complex long double z)

These functions return the projection of the complex value z onto the Riemann sphere. Values with a infinite imaginary part are projected to positive infinity on the real axis, even if the real part is NaN. If the real part is infinite, the result is equivalent to 

          INFINITY + I * copysign (0.0, cimag (z))
     
Other Input Conversions 
Next:  Formatted Input Functions , Previous:  String Input Conversions , Up:  Formatted Input 




Other Input Conversions

This section describes the miscellaneous input conversions. 

The `%p' conversion is used to read a pointer value. It recognizes the same syntax used by the `%p' output conversion for printf (see  Other Output Conversions ); that is, a hexadecimal number just as the `%x' conversion accepts. The corresponding argument should be of type void **; that is, the address of a place to store a pointer. 

The resulting pointer value is not guaranteed to be valid if it was not originally written during the same program execution that reads it in. 

The `%n' conversion produces the number of characters read so far by this call. The corresponding argument should be of type int *. This conversion works in the same way as the `%n' conversion for printf; see  Other Output Conversions , for an example. 

The `%n' conversion is the only mechanism for determining the success of literal matches or conversions with suppressed assignments. If the `%n' follows the locus of a matching failure, then no value is stored for it since scanf returns before processing the `%n'. If you store -1 in that argument slot before calling scanf, the presence of -1 after scanf indicates an error occurred before the `%n' was reached. 

Finally, the `%%' conversion matches a literal `%' character in the input stream, without using an argument. This conversion does not permit any flags, field width, or type modifier to be specified.

+ Other Output Conversions 
Next:  Formatted Output Functions , Previous:  Floating-Point Conversions , Up:  Formatted Output 




Other Output Conversions

This section describes miscellaneous conversions for printf. 

The `%c' conversion prints a single character. In case there is no `l' modifier the int argument is first converted to an unsigned char. Then, if used in a wide stream function, the character is converted into the corresponding wide character. The `-' flag can be used to specify left-justification in the field, but no other flags are defined, and no precision or type modifier can be given. For example:

     printf ("%c%c%c%c%c", 'h', 'e', 'l', 'l', 'o');

prints `hello'. 

If there is a `l' modifier present the argument is expected to be of type wint_t. If used in a multibyte function the wide character is converted into a multibyte character before being added to the output. In this case more than one output byte can be produced. 

The `%s' conversion prints a string. If no `l' modifier is present the corresponding argument must be of type char * (or const char *). If used in a wide stream function the string is first converted in a wide character string. A precision can be specified to indicate the maximum number of characters to write; otherwise characters in the string up to but not including the terminating null character are written to the output stream. The `-' flag can be used to specify left-justification in the field, but no other flags or type modifiers are defined for this conversion. For example:

     printf ("%3s%-6s", "no", "where");

prints ` nowhere '. 

If there is a `l' modifier present the argument is expected to be of type wchar_t (or const wchar_t *). 

If you accidentally pass a null pointer as the argument for a `%s' conversion, the GNU library prints it as `(null)'. We think this is more useful than crashing. But it's not good practice to pass a null argument intentionally. 

The `%p' conversion prints a pointer value. The corresponding argument must be of type void *. In practice, you can use any type of pointer. 

In this system, pointers are printed as unsigned integers, as if a `%#x' conversion were used.

For example:

     printf ("%p", "testing");

prints `0x' followed by a hexadecimal number--the address of the string constant "testing". It does not print the word `testing'. 

You can supply the `-' flag with the `%p' conversion to specify left-justification, but no other flags, precision, or type modifiers are defined. 

The `%n' conversion is unlike any of the other output conversions. It uses an argument which must be a pointer to an int, but instead of printing anything it stores the number of characters printed so far by this call at that location. The `h' and `l' type modifiers are permitted to specify that the argument is of type short int * or long int * instead of int *, but no flags, field width, or precision are permitted. 

For example,

     int nchar;
     printf ("%d %s%n\n", 3, "bears", &nchar);

prints:

     3 bears

and sets nchar to 7, because `3 bears' is seven characters. 

The `%%' conversion prints a literal `%' character. This conversion doesn't use an argument, and no flags, field width, precision, or type modifiers are permitted.

Output Conversion Syntax 
Next:  Table of Output Conversions , Previous:  Formatted Output Basics , Up:  Formatted Output 




Output Conversion Syntax

This section provides details about the precise syntax of conversion specifications that can appear in a printf template string. 

Characters in the template string that are not part of a conversion specification are printed as-is to the output stream. Multibyte character sequences (see  Character Set Handling ) are permitted in a template string. 

The conversion specifications in a printf template string have the general form:

     % [ param-no $] flags width [ . precision ] type conversion

For example, in the conversion specifier `%-10.8ld', the `-' is a flag, `10' specifies the field width, the precision is `8', the letter `l' is a type modifier, and `d' specifies the conversion style. (This particular type specifier says to print a long int argument in decimal notation, with a minimum of 8 digits left-justified in a field at least 10 characters wide.) 

In more detail, output conversion specifications consist of an initial `%' character followed in sequence by:

· Zero or more flag characters that modify the normal behavior of the conversion specification.
· An optional decimal integer specifying the minimum field width. If the normal conversion produces fewer characters than this, the field is padded with spaces to the specified width. This is a minimum value; if the normal conversion produces more characters than this, the field is not truncated. Normally, the output is right-justified within the field. You can also specify a field width of `*'. This means that the next argument in the argument list (before the actual value to be printed) is used as the field width. The value must be an int. If the value is negative, this means to set the `-' flag (see below) and to use the absolute value as the field width. 
· An optional precision to specify the number of digits to be written for the numeric conversions. If the precision is specified, it consists of a period (`.') followed optionally by a decimal integer (which defaults to zero if omitted). You can also specify a precision of `*'. This means that the next argument in the argument list (before the actual value to be printed) is used as the precision. The value must be an int, and is ignored if it is negative. If you specify `*' for both the field width and precision, the field width argument precedes the precision argument. Other C library versions may not recognize this syntax. 
· An optional type modifier character, which is used to specify the data type of the corresponding argument if it differs from the default type. (For example, the integer conversions assume a type of int, but you can specify `h', `l', or `L' for other integer types.)
· A character that specifies the conversion to be applied.

The exact options that are permitted and how they are interpreted vary between the different conversion specifiers. See the descriptions of the individual conversions for information about the particular options that they use. 

Parsing of Floats 
Previous:  Parsing of Integers , Up:  Parsing of Numbers 




Parsing of Floats

The `str' functions are declared in stdlib.h and those beginning with `wcs' are declared in wchar.h. One might wonder about the use of restrict in the prototypes of the functions in this section. It is seemingly useless but the ISO C standard uses it (for the functions defined there) so we have to do it as well.

-- Function: double strtod (const char *restrict string, char **restrict tailptr)

The strtod ("string-to-double") function converts the initial part of string to a floating-point number, which is returned as a value of type double. 

This function attempts to decompose string as follows:

· A (possibly empty) sequence of whitespace characters. Which characters are whitespace is determined by the isspace function (see  Classification of Characters ). These are discarded. 
· An optional plus or minus sign (`+' or `-'). 
· A floating point number in decimal or hexadecimal format. The decimal format is:

· A nonempty sequence of digits optionally containing a decimal-point character--normally `.', but it depends on the locale (see  General Numeric ). 
· An optional exponent part, consisting of a character `e' or `E', an optional sign, and a sequence of digits.

The hexadecimal format is as follows:

· A 0x or 0X followed by a nonempty sequence of hexadecimal digits optionally containing a decimal-point character--normally `.', but it depends on the locale (see  General Numeric ). 
· An optional binary-exponent part, consisting of a character `p' or `P', an optional sign, and a sequence of digits.

· Any remaining characters in the string. If tailptr is not a null pointer, a pointer to this tail of the string is stored in *tailptr.

If the string is empty, contains only whitespace, or does not contain an initial substring that has the expected syntax for a floating-point number, no conversion is performed. In this case, strtod returns a value of zero and the value returned in *tailptr is the value of string. 

In a locale other than the standard "C" or "POSIX" locales, this function may recognize additional locale-dependent syntax. 

If the string has valid syntax for a floating-point number but the value is outside the range of a double, strtod will signal overflow or underflow as described in  Math Error Reporting . 

strtod recognizes four special input strings. The strings "inf" and "infinity" are converted to &infin;, or to the largest representable value if the floating-point format doesn't support infinities. You can prepend a "+" or "-" to specify the sign. Case is ignored when scanning these strings. 

The strings "nan" and "nan(chars...)" are converted to NaN. Again, case is ignored. If chars... are provided, they are used in some unspecified fashion to select a particular representation of NaN (there can be several). 

Since zero is a valid result as well as the value returned on error, you should check for errors in the same way as for strtol, by examining errno and tailptr.

-- Function: float strtof (const char *string, char **tailptr)

-- Function: long double strtold (const char *string, char **tailptr)

These functions are analogous to strtod, but return float and long double values respectively. They report errors in the same way as strtod. strtof can be substantially faster than strtod, but has less precision; conversely, strtold can be much slower but has more precision (on systems where long double is a separate type). 

These functions have been GNU extensions and are new to ISO C99.

-- Function: double wcstod (const wchar_t *restrict string, wchar_t **restrict tailptr)

-- Function: float wcstof (const wchar_t *string, wchar_t **tailptr)

-- Function: long double wcstold (const wchar_t *string, wchar_t **tailptr)

The wcstod, wcstof, and wcstol functions are equivalent in nearly all aspect to the strtod, strtof, and strtold functions but it handles wide character string. 

The wcstod function was introduced in Amendment 1 of ISO C90. The wcstof and wcstold functions were introduced in ISO C99.

-- Function: double atof (const char *string)

This function is similar to the strtod function, except that it need not detect overflow and underflow errors. The atof function is provided mostly for compatibility with existing code; using strtod is more robust.

Parsing of Integers 
Next:  Parsing of Floats , Up:  Parsing of Numbers 




Parsing of Integers

The `str' functions are declared in stdlib.h and those beginning with `wcs' are declared in wchar.h. One might wonder about the use of restrict in the prototypes of the functions in this section. It is seemingly useless but the ISO C standard uses it (for the functions defined there) so we have to do it as well.

-- Function: long int strtol (const char *restrict string, char **restrict tailptr, int base)

The strtol ("string-to-long") function converts the initial part of string to a signed integer, which is returned as a value of type long int. 

This function attempts to decompose string as follows:

· A (possibly empty) sequence of whitespace characters. Which characters are whitespace is determined by the isspace function (see  Classification of Characters ). These are discarded. 
· An optional plus or minus sign (`+' or `-'). 
· A nonempty sequence of digits in the radix specified by base. 

If base is zero, decimal radix is assumed unless the series of digits begins with `0' (specifying octal radix), or `0x' or `0X' (specifying hexadecimal radix); in other words, the same syntax used for integer constants in C. 

Otherwise base must have a value between 2 and 36. If base is 16, the digits may optionally be preceded by `0x' or `0X'. If base has no legal value the value returned is 0l and the global variable errno is set to EINVAL. 
· Any remaining characters in the string. If tailptr is not a null pointer, strtol stores a pointer to this tail in *tailptr.

If the string is empty, contains only whitespace, or does not contain an initial substring that has the expected syntax for an integer in the specified base, no conversion is performed. In this case, strtol returns a value of zero and the value stored in *tailptr is the value of string. 

In a locale other than the standard "C" locale, this function may recognize additional implementation-dependent syntax. 

If the string has valid syntax for an integer but the value is not representable because of overflow, strtol returns either LONG_MAX or LONG_MIN (see  Range of Type ), as appropriate for the sign of the value. It also sets errno to ERANGE to indicate there was overflow. 

You should not check for errors by examining the return value of strtol, because the string might be a valid representation of 0l, LONG_MAX, or LONG_MIN. Instead, check whether tailptr points to what you expect after the number (e.g. '\0' if the string should end after the number). You also need to clear errno before the call and check it afterward, in case there was overflow. 

There is an example at the end of this section.

-- Function: long int wcstol (const wchar_t *restrict string, wchar_t **restrict tailptr, int base)

The wcstol function is equivalent to the strtol function in nearly all aspects but handles wide character strings. 

The wcstol function was introduced in Amendment 1 of ISO C90.

-- Function: unsigned long int strtoul (const char *retrict string, char **restrict tailptr, int base)

The strtoul ("string-to-unsigned-long") function is like strtol except it converts to an unsigned long int value. The syntax is the same as described above for strtol. The value returned on overflow is ULONG_MAX (see  Range of Type ). 

If string depicts a negative number, strtoul acts the same as strtol but casts the result to an unsigned integer. That means for example that strtoul on "-1" returns ULONG_MAX and an input more negative than LONG_MIN returns (ULONG_MAX + 1) / 2. 

strtoul sets errno to EINVAL if base is out of range, or ERANGE on overflow.

-- Function: unsigned long int wcstoul (const wchar_t *restrict string, wchar_t **restrict tailptr, int base)

The wcstoul function is equivalent to the strtoul function in nearly all aspects but handles wide character strings. 

The wcstoul function was introduced in Amendment 1 of ISO C90.

-- Function: long long int strtoll (const char *restrict string, char **restrict tailptr, int base)

The strtoll function is like strtol except that it returns a long long int value, and accepts numbers with a correspondingly larger range. 

If the string has valid syntax for an integer but the value is not representable because of overflow, strtoll returns either LONG_LONG_MAX or LONG_LONG_MIN (see  Range of Type ), as appropriate for the sign of the value. It also sets errno to ERANGE to indicate there was overflow. 

The strtoll function was introduced in ISO C99.

-- Function: long long int wcstoll (const wchar_t *restrict string, wchar_t **restrict tailptr, int base)

The wcstoll function is equivalent to the strtoll function in nearly all aspects but handles wide character strings. 

The wcstoll function was introduced in Amendment 1 of ISO C90.

-- Function: long long int strtoq (const char *restrict string, char **restrict tailptr, int base)

strtoq ("string-to-quad-word") is the BSD name for strtoll.

-- Function: long long int wcstoq (const wchar_t *restrict string, wchar_t **restrict tailptr, int base)

The wcstoq function is equivalent to the strtoq function in nearly all aspects but handles wide character strings. 

The wcstoq function is a GNU extension.

-- Function: unsigned long long int strtoull (const char *restrict string, char **restrict tailptr, int base)

The strtoull function is related to strtoll the same way strtoul is related to strtol. 

The strtoull function was introduced in ISO C99.

-- Function: unsigned long long int wcstoull (const wchar_t *restrict string, wchar_t **restrict tailptr, int base)

The wcstoull function is equivalent to the strtoull function in nearly all aspects but handles wide character strings. 

The wcstoull function was introduced in Amendment 1 of ISO C90.

-- Function: unsigned long long int strtouq (const char *restrict string, char **restrict tailptr, int base)

strtouq is the BSD name for strtoull.

-- Function: unsigned long long int wcstouq (const wchar_t *restrict string, wchar_t **restrict tailptr, int base)

The wcstouq function is equivalent to the strtouq function in nearly all aspects but handles wide character strings. 

The wcstoq function is a GNU extension.

-- Function: intmax_t strtoimax (const char *restrict string, char **restrict tailptr, int base)

The strtoimax function is like strtol except that it returns a intmax_t value, and accepts numbers of a corresponding range. 

If the string has valid syntax for an integer but the value is not representable because of overflow, strtoimax returns either INTMAX_MAX or INTMAX_MIN (see  Integers ), as appropriate for the sign of the value. It also sets errno to ERANGE to indicate there was overflow. 

See  Integers  for a description of the intmax_t type. The strtoimax function was introduced in ISO C99.

-- Function: intmax_t wcstoimax (const wchar_t *restrict string, wchar_t **restrict tailptr, int base)

The wcstoimax function is equivalent to the strtoimax function in nearly all aspects but handles wide character strings. 

The wcstoimax function was introduced in ISO C99.

-- Function: uintmax_t strtoumax (const char *restrict string, char **restrict tailptr, int base)

The strtoumax function is related to strtoimax the same way that strtoul is related to strtol. 

See  Integers  for a description of the intmax_t type. The strtoumax function was introduced in ISO C99.

-- Function: uintmax_t wcstoumax (const wchar_t *restrict string, wchar_t **restrict tailptr, int base)

The wcstoumax function is equivalent to the strtoumax function in nearly all aspects but handles wide character strings. 

The wcstoumax function was introduced in ISO C99.

-- Function: long int atol (const char *string)

This function is similar to the strtol function with a base argument of 10, except that it need not detect overflow errors. The atol function is provided mostly for compatibility with existing code; using strtol is more robust.

-- Function: int atoi (const char *string)

This function is like atol, except that it returns an int. The atoi function is also considered obsolete; use strtol instead.

-- Function: long long int atoll (const char *string)

This function is similar to atol, except it returns a long long int. 

The atoll function was introduced in ISO C99. It too is obsolete (despite having just been added); use strtoll instead.

All the functions mentioned in this section so far do not handle alternative representations of characters as described in the locale data. Some locales specify thousands separator and the way they have to be used which can help to make large numbers more readable. To read such numbers one has to parse them manually. 

Here is a function which parses a string as a sequence of integers and returns the sum of them:

     int
     sum_ints_from_string (char *string)
     {
       int sum = 0;
     
       while (1) {
         char *tail;
         int next;
     
         /* Skip whitespace by hand, to detect the end.  */
         while (isspace (*string)) string++;
         if (*string == 0)
           break;
     
         /* There is more nonwhitespace,  */
         /* so it ought to be another number.  */
         errno = 0;
         /* Parse it.  */
         next = strtol (string, &tail, 0);
         /* Add it in, if not overflow.  */
         if (errno)
           printf ("Overflow\n");
         else
           sum += next;
         /* Advance past it.  */
         string = tail;
       }
     
       return sum;
     }

+ Parsing of Numbers 
Previous:  Operations on Complex , Up:  Arithmetic 




Parsing of Numbers

This section describes functions for "reading" integer and floating-point numbers from a string. It may be more convenient in some cases to use sscanf or one of the related functions; see  Formatted Input . But often you can make a program more robust by finding the tokens in the string by hand, then converting the numbers one by one.

·  Parsing of Integers : Functions for conversion of integer values.
·  Parsing of Floats : Functions for conversion of floating-point values.

Portable Positioning 
Next:  Stream Buffering , Previous:  File Positioning , Up:  I/O on Streams 




Portable File-Position Functions

In this system, the file position is truly a character count. You can specify any character count value as an argument to fseek and get reliable results for any random access file. However, other ISO C systems may not represent file positions in this manner.

As a consequence, you must observe certain rules when writing code which is portable to these systems:

· The value returned from ftell on a text stream has no predictable relationship to the number of characters you have read so far. The only thing you can rely on is that you can use it subsequently as the offset argument to fseek or fseeko to move back to the same file position. 
· In a call to fseek on a text stream, either the offset must be zero, or whence must be SEEK_SET and and the offset must be the result of an earlier call to ftell on the same stream. 
· The value of the file position indicator of a text stream is undefined while there are characters that have been pushed back with ungetc that haven't been read or discarded. See  Unreading .

If you do want to support systems with peculiar encodings for the file positions, it is better to use the functions fgetpos and fsetpos instead. These functions represent the file position using the data type fpos_t, whose internal representation varies from system to system. 

These symbols are declared in the header file stdio.h.

-- Data Type: fpos_t

This is the type of an object that can encode information about the file position of a stream, for use by the functions fgetpos and fsetpos. 

In the GNU system, fpos_t is an opaque data structure that contains internal data to represent file offset and conversion state information. In other systems, it might have a different internal representation. 

-- Function: int fgetpos (FILE *stream, fpos_t *position)

This function stores the value of the file position indicator for the stream stream in the fpos_t object pointed to by position. If successful, fgetpos returns zero; otherwise it returns a nonzero value and stores an implementation-defined positive value in errno. 

-- Function: int fsetpos (FILE *stream, const fpos_t *position)

This function sets the file position indicator for the stream stream to the position position, which must have been set by a previous call to fgetpos on the same stream. If successful, fsetpos clears the end-of-file indicator on the stream, discards any characters that were "pushed back" by the use of ungetc, and returns a value of zero. Otherwise, fsetpos returns a nonzero value and stores an implementation-defined positive value in errno. 
Program Arguments 
Next:  Environment Variables , Up:  Program Basics 




Program Arguments

The system starts a C program by calling the function main. It is up to you to write a function named main--otherwise, you won't even be able to link your program without errors. 

In ISO C you can define main either to take no arguments, or to take two arguments that represent the command line arguments to the program, like this:

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

The command line arguments are the whitespace-separated tokens given in the shell command used to invoke the program; thus, in `cat foo bar', the arguments are `foo' and `bar'.  A program may also look at its arguments by examining the __argv and __argc variables


The value of the argc argument is the number of command line arguments. The argv argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of argc counts this element. A null pointer always follows the last element: argv[argc] is this null pointer. 

For the command `cat foo bar', argc is 3 and argv has three elements, "cat", "foo" and "bar". 

In this systems you can define main a third way, using three arguments:

     int main (int argc, char *argv[], char *envp[])

The first two arguments are just the same. The third argument envp gives the program's environment; it is the same as the value of _environ. See  Environment Variables . POSIX.1 does not allow this three-argument form, so to be portable it is best to write main to take two arguments, and use the value of _environ.

Program Basics 
Next:  Language Features , Previous:  Signal Handling , Up:  Top 




The Basic Program/System Interface

Processes are the primitive units for allocation of system resources. Each process has its own address space and (usually) one thread of control. A process executes a program; you can have multiple processes executing the same program, but each process has its own copy of the program within its own address space and executes it independently of the other copies. Though it may have multiple threads of control within the same program and a program may be composed of multiple logically separate modules, a process always executes exactly one program. 

Note that we are using a specific definition of "program" for the purposes of this manual, which corresponds to a common definition In popular usage, "program" enjoys a much broader definition; it can refer for example to a system's kernel, an editor macro, a complex package of software, or a discrete section of code executing within a process. 

Writing the program is what this manual is all about. This chapter explains the most basic interface between your program and the system that runs, or calls, it. This includes passing of parameters (arguments and environment) from the system, requesting basic services from the system, and telling the system the program is done. 

A program starts another program with the exec family of system calls. This chapter looks at program startup from the execee's point of view. To see the event from the execor's point of view, See  Executing a File .

·  Program Arguments : Parsing your program's command-line arguments.
·  Environment Variables : Less direct parameters affecting your program
·  Program Termination : Telling the system you're done; return status

Program Error Signals 
Next:  Miscellaneous Signals , Up:  Standard Signals 




Program Error Signals

The following signals are generated when a serious program error is detected by the operating system or the computer itself. In general, all of these signals are indications that your program is seriously broken in some way, and there's usually no way to continue the computation which encountered the error. 

Some programs handle program error signals in order to tidy up before terminating; for example, programs that turn off echoing of terminal input should handle program error signals in order to turn echoing back on. The handler should end by specifying the default action for the signal that happened and then reraising it; this will cause the program to terminate with that signal, as if it had not had a handler. (See  Termination in Handler .) 

Termination is the sensible ultimate outcome from a program error in most programs. However, programming systems such as Lisp that can load compiled user programs might need to keep executing even if a user program incurs an error. These programs have handlers which use longjmp to return control to the command level. 

The default action for all of these signals is to cause the process to terminate. If you block or ignore these signals or establish handlers for them that return normally, your program will probably break horribly when such signals happen, unless they are generated by raise or kill instead of a real error. 

-- Macro: int SIGFPE

The SIGFPE signal reports a fatal arithmetic error. Although the name is derived from "floating-point exception", this signal actually covers all arithmetic errors, including division by zero and overflow. If a program stores integer data in a location which is then used in a floating-point operation, this often causes an "invalid operation" exception, because the processor cannot recognize the data as a floating-point number. Actual floating-point exceptions are a complicated subject because there are many types of exceptions with subtly different meanings, and the SIGFPE signal doesn't distinguish between them. The IEEE Standard for Binary Floating-Point Arithmetic (ANSI/IEEE Std 754-1985 and ANSI/IEEE Std 854-1987) defines various floating-point exceptions and requires conforming computer systems to report their occurrences. However, this standard does not specify how the exceptions are reported, or what kinds of handling and control the operating system can offer to the programmer.

-- Macro: int SIGILL

The name of this signal is derived from "illegal instruction"; it usually means your program is trying to execute garbage or a privileged instruction. Since the C compiler generates only valid instructions, SIGILL typically indicates that the executable file is corrupted, or that you are trying to execute data. Some common ways of getting into the latter situation are by passing an invalid object where a pointer to a function was expected, or by writing past the end of an automatic array (or similar problems with pointers to automatic variables) and corrupting other data on the stack such as the return address of a stack frame. 

SIGILL can also be generated when the stack overflows, or when the system has trouble running the handler for a signal.

-- Macro: int SIGSEGV

This signal is generated when a program tries to read or write outside the memory that is allocated for it, or to write memory that can only be read. (Actually, the signals only occur when the program goes far enough outside to be detected by the system's memory protection mechanism.) The name is an abbreviation for "segmentation violation". 

Common ways of getting a SIGSEGV condition include dereferencing a null or uninitialized pointer, or when you use a pointer to step through an array, but fail to check for the end of the array. It varies among systems whether dereferencing a null pointer generates SIGSEGV or SIGBUS.


-- Macro: int SIGABRT

This signal indicates an error detected by the program itself and reported by calling abort. See  Aborting a Program .

-- Macro: int SIGTRAP

Generated by the machine's breakpoint instruction, and possibly other trap instructions. This signal is used by debuggers. Your program will probably only see SIGTRAP if it is somehow executing bad instructions.

-- Macro: int SIGEMT

Emulator trap; this results from certain unimplemented instructions which might be emulated in software, or the operating system's failure to properly emulate them.

Program Termination 
Previous:  Environment Variables, Up:  Program Basics 




Program Termination

The usual way for a program to terminate is simply for its main function to return. The exit status value returned from the main function is used to report information back to the process's parent process or shell. 

A program can also terminate normally by calling the exit function. 

In addition, programs can be terminated by signals; this is discussed in more detail in  Signal Handling . The abort function causes a signal that kills the program.

·  Normal Termination : If a program calls exit, a process terminates normally.
·  Exit Status : The exit status provides information about why the process terminated.
·  Cleanups on Exit : A process can run its own cleanup functions upon normal termination.
·  Aborting a Program : The abort function causes abnormal program termination.

Pseudo-Random Numbers 
Previous:  Special Functions , Up:  Mathematics 




Pseudo-Random Numbers

This section describes the GNU facilities for generating a series of pseudo-random numbers. The numbers generated are not truly random; typically, they form a sequence that repeats periodically, with a period so large that you can ignore it for ordinary purposes. The random number generator works by remembering a seed value which it uses to compute the next random number and also to compute a new seed. 

Although the generated numbers look unpredictable within one run of a program, the sequence of numbers is exactly the same from one run to the next. This is because the initial seed is always the same. This is convenient when you are debugging a program, but it is unhelpful if you want the program to behave unpredictably. If you want a different pseudo-random series each time your program runs, you must specify a different seed each time. For ordinary purposes, basing the seed on the current time works well. 

You can obtain repeatable sequences of numbers on a particular machine type by specifying the same initial seed value for the random number generator. There is no standard meaning for a particular seed value; the same seed, used in different C libraries or on different CPU types, will give you different random numbers. 

This library supports the standard ISO C random number functions 

·  ISO Random : rand and friends.
+ Range of Type 
Next:  Floating Type Macros , Previous:  Width of Type , Up:  Data Type Measurements 




Range of an Integer Type

Suppose you need to store an integer value which can range from zero to one million. Which is the smallest type you can use? There is no general rule; it depends on the C compiler and target machine. You can use the `MIN' and `MAX' macros in limits.h to determine which type will work. 

Each signed integer type has a pair of macros which give the smallest and largest values that it can hold. Each unsigned integer type has one such macro, for the maximum value; the minimum value is, of course, zero. 

The values of these macros are all integer constant expressions. The `MAX' and `MIN' macros for char and short int types have values of type int. The `MAX' and `MIN' macros for the other types have values of the same type described by the macro--thus, ULONG_MAX has type unsigned long int.

SCHAR_MIN
This is the minimum value that can be represented by a signed char.
SCHAR_MAX
UCHAR_MAX
These are the maximum values that can be represented by a signed char and unsigned char, respectively.
CHAR_MIN
This is the minimum value that can be represented by a char. It's equal to SCHAR_MIN if char is signed, or zero otherwise.
CHAR_MAX
This is the maximum value that can be represented by a char. It's equal to SCHAR_MAX if char is signed, or UCHAR_MAX otherwise.
SHRT_MIN
This is the minimum value that can be represented by a signed short int.  In this system, short integers are 16-bit quantities.
SHRT_MAX
USHRT_MAX
These are the maximum values that can be represented by a signed short int and unsigned short int, respectively.
INT_MIN
This is the minimum value that can be represented by a signed int.  In this system, an int is a 32-bit quantity.
INT_MAX
UINT_MAX
These are the maximum values that can be represented by, respectively, the type signed int and the type unsigned int.
LONG_MIN
This is the minimum value that can be represented by a signed long int. In this system, long integers are 32-bit quantities, the same size as int.
LONG_MAX
ULONG_MAX
These are the maximum values that can be represented by a signed long int and unsigned long int, respectively.
LONG_LONG_MIN
This is the minimum value that can be represented by a signed long long int. In this system, long long integers are 64-bit quantities.
LONG_LONG_MAX
ULONG_LONG_MAX
These are the maximum values that can be represented by a signed long long int and unsigned long long int, respectively.
WCHAR_MAX
This is the maximum value that can be represented by a wchar_t. See  Extended Char Intro .

Reading Attributes 
Previous:  Attribute Meanings 




Reading the Attributes of a File

To examine the attributes of files, use the functions stat, and fstat and lstat. They return the attribute information in a struct stat object.  Both functions are declared in the header file sys/stat.h.

-- Function: int stat (const char *filename, struct stat *buf)

The stat function returns information about the attributes of the file named by filename in the structure pointed to by buf. 

If filename is the name of a symbolic link, the attributes you get describe the file that the link points to. If the link points to a nonexistent file name, then stat fails reporting a nonexistent file. 

The return value is 0 if the operation is successful, or -1 on failure. In addition to the usual file name errors (see  File Name Errors , the following errno error conditions are defined for this function:

ENOENT
The file named by filename doesn't exist.

When the sources are compiled with _FILE_OFFSET_BITS == 64 this function is in fact stat64 since the LFS interface transparently replaces the normal implementation.

- Function: int fstat (int filedes, struct stat *buf)

The fstat function is like stat, except that it takes an open file descriptor as an argument instead of a file name. See  Low-Level I/O . 

Like stat, fstat returns 0 on success and -1 on failure. The following errno error conditions are defined for fstat:

EBADF
The filedes argument is not a valid file descriptor.

When the sources are compiled with _FILE_OFFSET_BITS == 64 this function is in fact fstat64 since the LFS interface transparently replaces the normal implementation.


Receiving Arguments 
Next:  How Many Arguments , Previous:  Variadic Prototypes , Up:  How Variadic 




Receiving the Argument Values

Ordinary fixed arguments have individual names, and you can use these names to access their values. But optional arguments have no names--nothing but `...'. How can you access them? 

The only way to access them is sequentially, in the order they were written, and you must use special macros from stdarg.h in the following three step process:

1. You initialize an argument pointer variable of type va_list using va_start. The argument pointer when initialized points to the first optional argument. 
2. You access the optional arguments by successive calls to va_arg. The first call to va_arg gives you the first optional argument, the next call gives you the second, and so on. 

You can stop at any time if you wish to ignore any remaining optional arguments. It is perfectly all right for a function to access fewer arguments than were supplied in the call, but you will get garbage values if you try to access too many arguments. 
3. You indicate that you are finished with the argument pointer variable by calling va_end. 

(In practice, with most C compilers, calling va_end does nothing. This is true in the CC386 compiler. But you might as well call va_end just in case your program is someday compiled with a peculiar compiler.)

See  Argument Macros , for the full definitions of va_start, va_arg and va_end. 

Steps 1 and 3 must be performed in the function that accepts the optional arguments. However, you can pass the va_list variable as an argument to another function and perform all or part of step 2 there. 

You can perform the entire sequence of three steps multiple times within a single function invocation. If you want to ignore the optional arguments, you can do these steps zero times. 

You can have more than one argument pointer variable if you like. You can initialize each variable with va_start when you wish, and then you can fetch arguments with each argument pointer as you wish. Each argument pointer variable will sequence through the same set of argument values, but at its own pace. 

Portability note: With some compilers, once you pass an argument pointer value to a subroutine, you must not keep using the same argument pointer value after that subroutine returns. For full portability, you should just pass it to va_end. This is actually an ISO C requirement, but most ANSI C compilers work happily regardless.

Remainder Functions 
Next:  FP Bit Twiddling , Previous:  Rounding Functions , Up:  Arithmetic Functions 




Remainder Functions

The functions in this section compute the remainder on division of two floating-point numbers. Each is a little different; pick the one that suits your problem.

-- Function: double fmod (double numerator, double denominator)

-- Function: float fmodf (float numerator, float denominator)

-- Function: long double fmodl (long double numerator, long double denominator)

These functions compute the remainder from the division of numerator by denominator. Specifically, the return value is numerator - n * denominator, where n is the quotient of numerator divided by denominator, rounded towards zero to an integer. Thus, fmod (6.5, 2.3) returns 1.9, which is 6.5 minus 4.6. 

The result has the same sign as the numerator and has magnitude less than the magnitude of the denominator. 

If denominator is zero, fmod signals a domain error.

-- Function: double drem (double numerator, double denominator)

-- Function: float dremf (float numerator, float denominator)

-- Function: long double dreml (long double numerator, long double denominator)

These functions are like fmod except that they rounds the internal quotient n to the nearest integer instead of towards zero to an integer. For example, drem (6.5, 2.3) returns -0.4, which is 6.5 minus 6.9. 

The absolute value of the result is less than or equal to half the absolute value of the denominator. The difference between fmod (numerator, denominator) and drem (numerator, denominator) is always either denominator, minus denominator, or zero. 

If denominator is zero, drem signals a domain error.

-- Function: double remainder (double numerator, double denominator)

-- Function: float remainderf (float numerator, float denominator)

-- Function: long double remainderl (long double numerator, long double denominator)

This function is another name for drem.

Renaming Files 
Next:  Creating Directories , Previous:  Deleting Files , Up:  File System Interface 




Renaming Files

The rename function is used to change a file's name.

-- Function: int rename (const char *oldname, const char *newname)

The rename function renames the file oldname to newname. The file formerly accessible under the name oldname is afterwards accessible as newname instead. (If the file had any other names aside from oldname, it continues to have those names.) 

The directory containing the name newname must be on the same file system as the directory containing the name oldname. 

One special case for rename is when oldname and newname are two names for the same file. The consistent way to handle this case is to delete oldname. However, in this case POSIX requires that rename do nothing and report success--which is inconsistent. We don't know what your operating system will do. 

If oldname is not a directory, then any existing file named newname is removed during the renaming operation. However, if newname is the name of a directory, rename fails in this case. 

If oldname is a directory, then either newname must not exist or it must name a directory that is empty. In the latter case, the existing directory named newname is deleted first. The name newname must not specify a subdirectory of the directory oldname which is being renamed. 

One useful feature of rename is that the meaning of newname changes "atomically" from any previously existing file by that name to its new meaning (i.e. the file that was called oldname). There is no instant at which newname is non-existent "in between" the old meaning and the new meaning. If there is a system crash during the operation, it is possible for both names to still exist; but newname will always be intact if it exists at all. 

If rename fails, it returns -1. In addition to the usual file name errors (see  File Name Errors ), the following errno error conditions are defined for this function:

EACCES
One of the directories containing newname or oldname refuses write permission; or newname and oldname are directories and write permission is refused for one of them. 
EBUSY
A directory named by oldname or newname is being used by the system in a way that prevents the renaming from working. This includes directories that are mount points for filesystems, and directories that are the current working directories of processes. 
ENOTEMPTY
EEXIST
The directory newname isn't empty. The GNU system always returns ENOTEMPTY for this, but some other systems return EEXIST. 
EINVAL
oldname is a directory that contains newname. 
EISDIR
newname is a directory but the oldname isn't. 
EMLINK
The parent directory of newname would have too many links (entries). 
ENOENT
The file oldname doesn't exist. 
ENOSPC
The directory that would contain newname has no room for another entry, and there is no space left in the file system to expand it. 
EROFS
The operation would involve writing to a directory on a read-only file system. 
EXDEV
The two file names newname and oldname are on different file systems.

Representation of Strings 
Next:  String/Array Conventions , Up:  String and Array Utilities 




Representation of Strings

This section is a quick summary of string concepts for beginning C programmers. It describes how character strings are represented in C and some common pitfalls. If you are already familiar with this material, you can skip this section. 

A string is an array of char objects. But string-valued variables are usually declared to be pointers of type char *. Such variables do not include space for the text of a string; that has to be stored somewhere else--in an array variable, a string constant, or dynamically allocated memory (see  Memory Allocation ). It's up to you to store the address of the chosen memory space into the pointer variable. Alternatively you can store a null pointer in the pointer variable. The null pointer does not point anywhere, so attempting to reference the string it points to gets an error. 

"string" normally refers to multibyte character strings as opposed to wide character strings. Wide character strings are arrays of type wchar_t and as for multibyte character strings usually pointers of type wchar_t * are used. 

By convention, a null character, '\0', marks the end of a multibyte character string and the null wide character, L'\0', marks the end of a wide character string. For example, in testing to see whether the char * variable p points to a null character marking the end of a string, you can write !*p or *p == '\0'. 

A null character is quite different conceptually from a null pointer, although both are represented by the integer 0. 

String literals appear in C program source as strings of characters between double-quote characters (`"') where the initial double-quote character is immediately preceded by a capital `L' (ell) character (as in L"foo"). In ISO C, string literals can also be formed by string concatenation: "a" "b" is the same as "ab". For wide character strings one can either use L"a" L"b" or L"a" "b". Modification of string literals is allowed by this C compiler, but for portability this is not a good idea because with some systems literals are placed in read-only storage. 

Character arrays that are declared const cannot be modified either. It's generally good style to declare non-modifiable string pointers to be of type const char *, since this often allows the C compiler to detect accidental modifications as well as providing some amount of documentation about what your program intends to do with the string. 

The amount of memory allocated for the character array may extend past the null character that normally marks the end of the string. In this document, the term allocated size is always used to refer to the total amount of memory allocated for the string, while the term length refers to the number of characters up to (but not including) the terminating null character. A notorious source of program bugs is trying to put more characters in a string than fit in its allocated size. When writing code that extends strings or moves characters into a pre-allocated array, you should be very careful to keep track of the length of the text and make explicit checks for overflowing the array. Many of the library functions do not do this for you! Remember also that you need to allocate an extra byte to hold the null character that marks the end of the string. 

Originally strings were sequences of bytes where each byte represents a single character. This is still true today if the strings are encoded using a single-byte character encoding. Things are different if the strings are encoded using a multibyte encoding (for more information on encodings see  Extended Char Intro ). There is no difference in the programming interface for these two kind of strings; the programmer has to be aware of this and interpret the byte sequences accordingly. 

But since there is no separate interface taking care of these differences the byte-based string functions are sometimes hard to use. Since the count parameters of these functions specify bytes a call to strncpy could cut a multibyte character in the middle and put an incomplete (and therefore unusable) byte sequence in the target buffer. 

To avoid these problems later versions of the ISO C standard introduce a second set of functions which are operating on wide characters (see  Extended Char Intro ). These functions don't have the problems the single-byte versions have since every wide character is a legal, interpretable value. This does not mean that cutting wide character strings at arbitrary points is without problems. It normally is for alphabet-based languages (except for non-normalized text) but languages based on syllables still have the problem that more than one wide character is necessary to complete a logical unit. This is a higher level problem which the C library functions are not designed to solve. But it is at least good that no invalid byte sequences can be created. Also, the higher level functions can also much easier operate on wide character than on multibyte characters so that a general advise is to use wide characters internally whenever text is more than simply copied. 

The remaining of this chapter will discuss the functions for handling wide character strings in parallel with the discussion of the multibyte character strings since there is almost always an exact equivalent available.

Reserved Names 
Previous:  Macro Definitions 




Reserved Names

The names of all library types, macros, variables and functions that come from the ISO C standard are reserved unconditionally; your program may not redefine these names. All other library names are reserved if your program explicitly includes the header file that defines or declares them. There are several reasons for these restrictions:

· Other people reading your code could get very confused if you were using a function named exit to do something completely different from what the standard exit function does, for example. Preventing this situation helps to make your programs easier to understand and contributes to modularity and maintainability. 
· It avoids the possibility of a user accidentally redefining a library function that is called by other library functions. If redefinition were allowed, those other functions would not work properly. 
· It allows the compiler to do whatever special optimizations it pleases on calls to these functions, without the possibility that they may have been redefined by the user. Some library facilities, such as those for dealing with variadic arguments (see  Variadic Functions ) and non-local exits (see  Non-Local Exits ), actually require a considerable amount of cooperation on the part of the C compiler, and with respect to the implementation, it might be easier for the compiler to treat these as built-in parts of the language.

In addition to the names documented in this manual, reserved names include all external identifiers (global functions and variables) that begin with an underscore (`_') and all identifiers regardless of use that begin with either two underscores or an underscore followed by a capital letter are reserved names. This is so that the library and header files can define functions, variables, and macros for internal purposes without risk of conflict with names in user programs. 

Some additional classes of identifier names are reserved for future extensions to the C language or the POSIX.1 environment. While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of the C or POSIX standards, so you should avoid these names.

· Names beginning with a capital `E' followed a digit or uppercase letter may be used for additional error code names. See  Error Reporting . 
· Names that begin with either `is' or `to' followed by a lowercase letter may be used for additional character testing and conversion functions. See  Character Handling . 
· Names that begin with `LC_' followed by an uppercase letter may be used for additional macros specifying locale attributes. See  Locales . 
· Names of all existing mathematics functions (see  Mathematics ) suffixed with `f' or `l' are reserved for corresponding functions that operate on float and long double arguments, respectively. 
· Names that begin with `SIG' followed by an uppercase letter are reserved for additional signal names. See  Standard Signals . 
· Names that begin with `SIG_' followed by an uppercase letter are reserved for additional signal actions. See  Basic Signal Handling . 
· Names beginning with `str', `mem', or `wcs' followed by a lowercase letter are reserved for additional string and array functions. See  String and Array Utilities . 
· Names that end with `_t' are reserved for additional type names.

In addition, some individual header files reserve names beyond those that they actually define. You only need to worry about these restrictions if your program includes that particular header file.

· The header file limits.h reserves names suffixed with `_MAX'.
· The header file signal.h reserves names prefixed with `sa_' and `SA_'.
· The header file sys/stat.h reserves names prefixed with `st_' and `S_'.
· The header file sys/times.h reserves names prefixed with `tms_'.

Restartable multibyte conversion 
Next:  Non-reentrant Conversion , Previous:  Charset Function Overview , Up:  Character Set Handling 




Restartable Multibyte Conversion Functions

The ISO C standard defines functions to convert strings from a multibyte representation to wide character strings. There are a number of peculiarities:

· The character set assumed for the multibyte encoding is not specified as an argument to the functions. Instead the character set specified by the LC_CTYPE category of the current locale is used; see  Locale Categories . 
· The functions handling more than one character at a time require NUL terminated strings as the argument (i.e., converting blocks of text does not work unless one can add a NUL byte at an appropriate place). 

Despite these limitations the ISO C functions can be used in many contexts. In graphical user interfaces, for instance, it is not uncommon to have functions that require text to be displayed in a wide character string if the text is not simple ASCII. The text itself might come from a file with translations and the user should decide about the current locale, which determines the translation and therefore also the external encoding used. In such a situation (and many others) the functions described here are perfect.

·  Selecting the Conversion : Selecting the conversion and its properties.
·  Keeping the state : Representing the state of the conversion.
·  Converting a Character : Converting Single Characters.
·  Converting Strings : Converting Multibyte and Wide Character Strings.
·  Multibyte Conversion Example : A Complete Multibyte Conversion Example.

Roadmap to the Manual 
Previous:  Getting Started , Up:  Introduction 




Roadmap to the Manual

Here is an overview of the contents of the remaining chapters of this manual.

·  Error Reporting , describes how errors detected by the library are reported. 
·  Language Features , contains information about library support for standard parts of the C language, including things like the sizeof operator and the symbolic constant NULL, how to write functions accepting variable numbers of arguments, and constants describing the ranges and other properties of the numerical types. There is also a simple debugging mechanism which allows you to put assertions in your code, and have diagnostic messages printed if the tests fail. 
·  Memory , describes the GNU library's facilities for managing and using virtual and real memory, including dynamic allocation of virtual memory. If you do not know in advance how much memory your program needs, you can allocate it dynamically instead, and manipulate it via pointers. 
·  Character Handling , contains information about character classification functions (such as isspace) and functions for performing case conversion. 
·  String and Array Utilities , has descriptions of functions for manipulating strings (null-terminated character arrays) and general byte arrays, including operations such as copying and comparison. 
·  I/O Overview , gives an overall look at the input and output facilities in the library, and contains information about basic concepts such as file names. 
·  I/O on Streams , describes I/O operations involving streams (or FILE * objects). These are the normal C library functions from stdio.h. 
·  Low-Level I/O , contains information about I/O operations on file descriptors. File descriptors are a lower-level mechanism specific to the Unix family of operating systems. 
·  File System Interface , has descriptions of operations on entire files, such as functions for deleting and renaming them and for creating new directories. This chapter also contains information about how you can access the attributes of a file, such as its owner and file protection modes. 
·  Mathematics , contains information about the math library functions. These include things like random-number generators and remainder functions on integers as well as the usual trigonometric and exponential functions on floating-point numbers. 
·  Low-Level Arithmetic Functions , describes functions for simple arithmetic, analysis of floating-point values, and reading numbers from strings. 
·  Searching and Sorting , contains information about functions for searching and sorting arrays. You can use these functions on any kind of array by providing an appropriate comparison function. 
·  Date and Time , describes functions for measuring both calendar time and CPU time, as well as functions for setting alarms and timers. 
·  Character Set Handling , contains information about manipulating characters and strings using character sets larger than will fit in the usual char data type. 
·  Locales , describes how selecting a particular country or language affects the behavior of the library. For example, the locale affects collation sequences for strings and how monetary values are formatted. 
·  Non-Local Exits , contains descriptions of the setjmp and longjmp functions. These functions provide a facility for goto-like jumps which can jump from one function to another. 
·  Signal Handling , tells you all about signals--what they are, how to establish a handler that is called when a particular kind of signal is delivered, and how to prevent signals from arriving during critical sections of your program. 
·  Program Basics , tells how your programs can access their command-line arguments and environment variables. 

Rounding Functions 
Next:  Remainder Functions , Previous:  Normalization Functions , Up:  Arithmetic Functions 




Rounding Functions

The functions listed here perform operations such as rounding and truncation of floating-point values. Some of these functions convert floating point numbers to integer values. They are all declared in math.h. 

You can also convert floating-point numbers to integers simply by casting them to int. This discards the fractional part, effectively rounding towards zero. However, this only works if the result can actually be represented as an int--for very large numbers, this is impossible. The functions listed here return the result as a double instead to get around this problem.

-- Function: double ceil (double x)

-- Function: float ceilf (float x)

-- Function: long double ceill (long double x)

These functions round x upwards to the nearest integer, returning that value as a double. Thus, ceil (1.5) is 2.0.

-- Function: double floor (double x)

-- Function: float floorf (float x)

-- Function: long double floorl (long double x)

These functions round x downwards to the nearest integer, returning that value as a double. Thus, floor (1.5) is 1.0 and floor (-1.5) is -2.0.

-- Function: double trunc (double x)

-- Function: float truncf (float x)

-- Function: long double truncl (long double x)

The trunc functions round x towards zero to the nearest integer (returned in floating-point format). Thus, trunc (1.5) is 1.0 and trunc (-1.5) is -1.0.

-- Function: double rint (double x)

-- Function: float rintf (float x)

-- Function: long double rintl (long double x)

These functions round x to an integer value according to the current rounding mode. See  Floating Point Parameters , for information about the various rounding modes. The default rounding mode is to round to the nearest integer; some machines support other modes, but round-to-nearest is always used unless you explicitly select another. 

If x was not initially an integer, these functions raise the inexact exception.

-- Function: double nearbyint (double x)

-- Function: float nearbyintf (float x)

-- Function: long double nearbyintl (long double x)

These functions return the same value as the rint functions, but do not raise the inexact exception if x is not an integer.

-- Function: double round (double x)

-- Function: float roundf (float x)

-- Function: long double roundl (long double x)

These functions are similar to rint, but they round halfway cases away from zero instead of to the nearest even integer.

-- Function: long int lrint (double x)

-- Function: long int lrintf (float x)

-- Function: long int lrintl (long double x)

These functions are just like rint, but they return a long int instead of a floating-point number.

-- Function: long long int llrint (double x)

-- Function: long long int llrintf (float x)

-- Function: long long int llrintl (long double x)

These functions are just like rint, but they return a long long int instead of a floating-point number.

-- Function: long int lround (double x)

-- Function: long int lroundf (float x)

-- Function: long int lroundl (long double x)

These functions are just like round, but they return a long int instead of a floating-point number.

-- Function: long long int llround (double x)

-- Function: long long int llroundf (float x)

-- Function: long long int llroundl (long double x)

These functions are just like round, but they return a long long int instead of a floating-point number.

-- Function: double modf (double value, double *integer-part)

-- Function: float modff (float value, float *integer-part)

-- Function: long double modfl (long double value, long double *integer-part)

These functions break the argument value into an integer part and a fractional part (between -1 and 1, exclusive). Their sum equals value. Each of the parts has the same sign as value, and the integer part is always rounded toward zero. 

modf stores the integer part in *integer-part, and returns the fractional part. For example, modf (2.5, &intpart) returns 0.5 and stores 2.0 into intpart.

Rounding
Next:  Control Functions , Previous:  Floating Point Errors , Up:  Arithmetic 




Rounding Modes

Floating-point calculations are carried out internally with extra precision, and then rounded to fit into the destination type. This ensures that results are as precise as the input data. IEEE 754 defines four possible rounding modes:

Round to nearest.
This is the default mode. It should be used unless there is a specific need for one of the others. In this mode results are rounded to the nearest representable value. If the result is midway between two representable values, the even representable is chosen. Even here means the lowest-order bit is zero. This rounding mode prevents statistical bias and guarantees numeric stability: round-off errors in a lengthy calculation will remain smaller than half of FLT_EPSILON.
Round toward plus Infinity.
All results are rounded to the smallest representable value which is greater than the result.
Round toward minus Infinity.
All results are rounded to the largest representable value which is less than the result. 
Round toward zero.
All results are rounded to the largest representable value whose magnitude is less than that of the result. In other words, if the result is negative it is rounded up; if it is positive, it is rounded down.

fenv.h defines constants which you can use to refer to the various rounding modes. Each one will be defined if and only if the FPU supports the corresponding rounding mode.

FE_TONEAREST
Round to nearest.

FE_UPWARD
Round toward +&infin;.

FE_DOWNWARD
Round toward -&infin;.

FE_TOWARDZERO
Round toward zero.

Underflow is an unusual case. Normally, IEEE 754 floating point numbers are always normalized (see  Floating Point Concepts ). Numbers smaller than 2^r (where r is the minimum exponent, FLT_MIN_RADIX-1 for float) cannot be represented as normalized numbers. Rounding all such numbers to zero or 2^r would cause some algorithms to fail at 0. Therefore, they are left in denormalized form. That produces loss of precision, since some bits of the mantissa are stolen to indicate the decimal point. 

If a result is too small to be represented as a denormalized number, it is rounded to zero. However, the sign of the result is preserved; if the calculation was negative, the result is negative zero. Negative zero can also result from some operations on infinity, such as 4/-&infin;. Negative zero behaves identically to zero except when the copysign or signbit functions are used to check the sign bit directly. 

At any time one of the above four rounding modes is selected. You can find out which one with this function:

-- Function: int fegetround (void)

Returns the currently selected rounding mode, represented by one of the values of the defined rounding mode macros.

To change the rounding mode, use this function:

-- Function: int fesetround (int round)

Changes the currently selected rounding mode to round. If round does not correspond to one of the supported rounding modes nothing is changed. fesetround returns zero if it changed the rounding mode, a nonzero value if the mode is not supported.

You should avoid changing the rounding mode if possible. It can be an expensive operation; also, some hardware requires you to compile your program differently for it to work. The resulting code may run slower. See your compiler documentation for details.

Running a Command 
Next:  Executing a File , Previous:  Aborting a Program , Up: Top




Running a Command

The easy way to run another program is to use the system function. This function does all the work of running a subprogram, but it doesn't give you much control over the details: you have to wait until the subprogram terminates before you can do anything else.
-- Function: int system (const char *command)

This function executes command as a shell command. In the  C library, it uses the file configured by the COMMAND environment variable to run the command, or 'cmd.exe' if there is none. In particular, it searches the directories in PATH to find programs to execute. The return value is -1 if it wasn't possible to create the shell process, and otherwise is the status of the shell process.

If the command argument is a null pointer, a return value of zero indicates that no command processor is available. 

The system function is declared in the header file stdlib.h.

Portability Note: Some C implementations may not have any notion of a command processor that can execute other programs. You can determine whether a command processor exists by executing system (NULL); if the return value is nonzero, a command processor is available. 


Search Functions 
Next:  Finding Tokens in a String , Previous:  Collation Functions , Up:  String and Array Utilities 




Search Functions

This section describes library functions which perform various kinds of searching operations on strings and arrays. These functions are declared in the header file string.h.

-- Function: void * memchr (const void *block, int c, size_t size)

This function finds the first occurrence of the byte c (converted to an unsigned char) in the initial size bytes of the object beginning at block. The return value is a pointer to the located byte, or a null pointer if no match was found.

-- Function: wchar_t * wmemchr (const wchar_t *block, wchar_t wc, size_t size)

This function finds the first occurrence of the wide character wc in the initial size wide characters of the object beginning at block. The return value is a pointer to the located wide character, or a null pointer if no match was found.


-- Function: void * memrchr (const void *block, int c, size_t size)

The function memrchr is like memchr, except that it searches backwards from the end of the block defined by block and size (instead of forwards from the front).

-- Function: char * strchr (const char *string, int c)

The strchr function finds the first occurrence of the character c (converted to a char) in the null-terminated string beginning at string. The return value is a pointer to the located character, or a null pointer if no match was found. 

For example, 

          strchr ("hello, world", 'l')
              => "llo, world"
          strchr ("hello, world", '?')
              => NULL
     
The terminating null character is considered to be part of the string, so you can use this function get a pointer to the end of a string by specifying a null character as the value of the c argument. It would be better (but less portable) to use strchrnul in this case, though.

-- Function: wchar_t * wcschr (const wchar_t *wstring, int wc)

The wcschr function finds the first occurrence of the wide character wc in the null-terminated wide character string beginning at wstring. The return value is a pointer to the located wide character, or a null pointer if no match was found. 

The terminating null character is considered to be part of the wide character string, so you can use this function get a pointer to the end of a wide character string by specifying a null wude character as the value of the wc argument. It would be better (but less portable) to use wcschrnul in this case, though.

One useful, but unusual, use of the strchr function is when one wants to have a pointer pointing to the NUL byte terminating a string. This is often written in this way:

       s += strlen (s);

This is almost optimal but the addition operation duplicated a bit of the work already done in the strlen function. A better solution is this:

       s = strchr (s, '\0');

There is no restriction on the second parameter of strchr so it could very well also be the NUL character. But this is slightly more expensive than the strlen function since strchr has two exit criteria.

-- Function: char * strrchr (const char *string, int c)

The function strrchr is like strchr, except that it searches backwards from the end of the string string (instead of forwards from the front). 

For example, 

          strrchr ("hello, world", 'l')
              => "ld"
     
-- Function: wchar_t * wcsrchr (const wchar_t *wstring, wchar_t c)

The function wcsrchr is like wcschr, except that it searches backwards from the end of the string wstring (instead of forwards from the front).

-- Function: char * strstr (const char *haystack, const char *needle)

This is like strchr, except that it searches haystack for a substring needle rather than just a single character. It returns a pointer into the string haystack that is the first character of the substring, or a null pointer if no match was found. If needle is an empty string, the function returns haystack. 

For example, 

          strstr ("hello, world", "l")
              => "llo, world"
          strstr ("hello, world", "wo")
              => "world"
     
-- Function: wchar_t * wcsstr (const wchar_t *haystack, const wchar_t *needle)

This is like wcschr, except that it searches haystack for a substring needle rather than just a single wide character. It returns a pointer into the string haystack that is the first wide character of the substring, or a null pointer if no match was found. If needle is an empty string, the function returns haystack.

-- Function: size_t strspn (const char *string, const char *skipset)

The strspn ("string span") function returns the length of the initial substring of string that consists entirely of characters that are members of the set specified by the string skipset. The order of the characters in skipset is not important. 

For example, 

          strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
              => 5
     
Note that "character" is here used in the sense of byte. In a string using a multibyte character encoding (abstract) character consisting of more than one byte are not treated as an entity. Each byte is treated separately. The function is not locale-dependent.

-- Function: size_t wcsspn (const wchar_t *wstring, const wchar_t *skipset)

The wcsspn ("wide character string span") function returns the length of the initial substring of wstring that consists entirely of wide characters that are members of the set specified by the string skipset. The order of the wide characters in skipset is not important.

-- Function: size_t strcspn (const char *string, const char *stopset)

The strcspn ("string complement span") function returns the length of the initial substring of string that consists entirely of characters that are not members of the set specified by the string stopset. (In other words, it returns the offset of the first character in string that is a member of the set stopset.) 

For example, 

          strcspn ("hello, world", " \t\n,.;!?")
              => 5
     
Note that "character" is here used in the sense of byte. In a string using a multibyte character encoding (abstract) character consisting of more than one byte are not treated as an entity. Each byte is treated separately. The function is not locale-dependent.

-- Function: size_t wcscspn (const wchar_t *wstring, const wchar_t *stopset)

The wcscspn ("wide character string complement span") function returns the length of the initial substring of wstring that consists entirely of wide characters that are not members of the set specified by the string stopset. (In other words, it returns the offset of the first character in string that is a member of the set stopset.)

-- Function: char * strpbrk (const char *string, const char *stopset)

The strpbrk ("string pointer break") function is related to strcspn, except that it returns a pointer to the first character in string that is a member of the set stopset instead of the length of the initial substring. It returns a null pointer if no such character from stopset is found.

For example, 

          strpbrk ("hello, world", " \t\n,.;!?")
              => ", world"
     
Note that "character" is here used in the sense of byte. In a string using a multibyte character encoding (abstract) character consisting of more than one byte are not treated as an entity. Each byte is treated separately. The function is not locale-dependent.

-- Function: wchar_t * wcspbrk (const wchar_t *wstring, const wchar_t *stopset)

The wcspbrk ("wide character string pointer break") function is related to wcscspn, except that it returns a pointer to the first wide character in wstring that is a member of the set stopset instead of the length of the initial substring. It returns a null pointer if no such character from stopset is found.

Searching and Sorting 
Next:  I/O Overview , Previous:  Locales , Up:  Top 




Searching and Sorting

This chapter describes functions for searching and sorting arrays of arbitrary objects. You pass the appropriate comparison function to be applied as an argument, along with the size of the objects in the array and the total number of elements.

·  Comparison Functions : Defining how to compare two objects. Since the sort and search facilities are general, you have to specify the ordering.
·  Array Search Function : The bsearch function.
·  Array Sort Function : The qsort function.
·  Search/Sort Example : An example program.
Search/Sort Example 
Previous:  Array Sort Function , Up:  Searching and Sorting 




Searching and Sorting Example

Here is an example showing the use of qsort and bsearch with an array of structures. The objects in the array are sorted by comparing their name fields with the strcmp function. Then, we can look up individual objects based on their names.

     #include <stdlib.h>
     #include <stdio.h>
     #include <string.h>
     
     /* Define an array of critters to sort. */
     
     struct critter
       {
         const char *name;
         const char *species;
       };
     
     struct critter muppets[] =
       {
         {"Kermit", "frog"},
         {"Piggy", "pig"},
         {"Gonzo", "whatever"},
         {"Fozzie", "bear"},
         {"Sam", "eagle"},
         {"Robin", "frog"},
         {"Animal", "animal"},
         {"Camilla", "chicken"},
         {"Sweetums", "monster"},
         {"Dr. Strangepork", "pig"},
         {"Link Hogthrob", "pig"},
         {"Zoot", "human"},
         {"Dr. Bunsen Honeydew", "human"},
         {"Beaker", "human"},
         {"Swedish Chef", "human"}
       };
     
     int count = sizeof (muppets) / sizeof (struct critter);
     
     
     
     /* This is the comparison function used for sorting and searching. */
     
     int
     critter_cmp (const struct critter *c1, const struct critter *c2)
     {
       return strcmp (c1->name, c2->name);
     }
     
     
     /* Print information about a critter. */
     
     void
     print_critter (const struct critter *c)
     {
       printf ("%s, the %s\n", c->name, c->species);
     }
     
     
     /* Do the lookup into the sorted array. */
     
     void
     find_critter (const char *name)
     {
       struct critter target, *result;
       target.name = name;
       result = bsearch (&target, muppets, count, sizeof (struct critter),
                         critter_cmp);
       if (result)
         print_critter (result);
       else
         printf ("Couldn't find %s.\n", name);
     }
     
     /* Main program. */
     
     int
     main (void)
     {
       int i;
     
       for (i = 0; i < count; i++)
         print_critter (&muppets[i]);
       printf ("\n");
     
       qsort (muppets, count, sizeof (struct critter), critter_cmp);
     
       for (i = 0; i < count; i++)
         print_critter (&muppets[i]);
       printf ("\n");
     
       find_critter ("Kermit");
       find_critter ("Gonzo");
       find_critter ("Janice");
     
       return 0;
     }

The output from this program looks like:

     Kermit, the frog
     Piggy, the pig
     Gonzo, the whatever
     Fozzie, the bear
     Sam, the eagle
     Robin, the frog
     Animal, the animal
     Camilla, the chicken
     Sweetums, the monster
     Dr. Strangepork, the pig
     Link Hogthrob, the pig
     Zoot, the human
     Dr. Bunsen Honeydew, the human
     Beaker, the human
     Swedish Chef, the human
     
     Animal, the animal
     Beaker, the human
     Camilla, the chicken
     Dr. Bunsen Honeydew, the human
     Dr. Strangepork, the pig
     Fozzie, the bear
     Gonzo, the whatever
     Kermit, the frog
     Link Hogthrob, the pig
     Piggy, the pig
     Robin, the frog
     Sam, the eagle
     Swedish Chef, the human
     Sweetums, the monster
     Zoot, the human
     
     Kermit, the frog
     Gonzo, the whatever
     Couldn't find Janice.

Selecting the Conversion 
Next:  Keeping the state , Up:  Restartable multibyte conversion 




Selecting the conversion and its properties

We already said above that the currently selected locale for the LC_CTYPE category decides about the conversion that is performed by the functions we are about to describe. Each locale uses its own character set (given as an argument to localedef) and this is the one assumed as the external multibyte encoding. The wide character character set always is UCS-2.

A characteristic of each multibyte character set is the maximum number of bytes that can be necessary to represent one character. This information is quite important when writing code that uses the conversion functions (as shown in the examples below). The ISO C standard defines two macros that provide this information.

-- Macro: int MB_LEN_MAX

MB_LEN_MAX specifies the maximum number of bytes in the multibyte sequence for a single character in any of the supported locales. It is a compile-time constant and is defined in limits.h.

-- Macro: int MB_CUR_MAX

MB_CUR_MAX expands into a positive integer expression that is the maximum number of bytes in a multibyte character in the current locale. The value is never greater than MB_LEN_MAX. Unlike MB_LEN_MAX this macro need not be a compile-time constant, and in this C library it is not. 

MB_CUR_MAX is defined in stdlib.h.

Two different macros are necessary since strictly ISO C90 compilers do not allow variable length array definitions, but still it is desirable to avoid dynamic allocation. This incomplete piece of code shows the problem:

     {
       char buf[MB_LEN_MAX];
       ssize_t len = 0;
     
       while (! feof (fp))
         {
           fread (&buf[len], 1, MB_CUR_MAX - len, fp);
           /* ... process buf */
           len -= used;
         }
     }

The code in the inner loop is expected to have always enough bytes in the array buf to convert one multibyte character. The array buf has to be sized statically since many compilers do not allow a variable size. The fread call makes sure that MB_CUR_MAX bytes are always available in buf. Note that it isn't a problem if MB_CUR_MAX is not a compile-time constant.

Setting the Locale 
Next:  Standard Locales , Previous:  Locale Categories , Up:  Locales 




How Programs Set the Locale

A C program inherits its locale environment variables when it starts up. This happens automatically. However, these variables do not automatically control the locale used by the library functions, because ISO C says that all programs start by default in the standard `C' locale. To use the locales specified by the environment, you must call setlocale. Call it as follows:

     setlocale (LC_ALL, "");

to select a locale based on the user choice of the appropriate environment variables. 

You can also use setlocale to specify a particular locale, for general use or for a specific category. 

The symbols in this section are defined in the header file locale.h.
-- Function: char * setlocale (int category, const char *locale)

The function setlocale sets the current locale for category category to locale. A list of all the locales the system provides can be created by running

            locale -a
     
If category is LC_ALL, this specifies the locale for all purposes. The other possible values of category specify an single purpose (see  Locale Categories ). 

You can also use this function to find out the current locale by passing a null pointer as the locale argument. In this case, setlocale returns a string that is the name of the locale currently selected for category category. 

The string returned by setlocale can be overwritten by subsequent calls, so you should make a copy of the string (see  Copying and Concatenation ) if you want to save it past any further calls to setlocale. (The standard library is guaranteed never to call setlocale itself.) 

You should not modify the string returned by setlocale. It might be the same string that was passed as an argument in a previous call to setlocale. One requirement is that the category must be the same in the call the string was returned and the one when the string is passed in as locale parameter. 

When you read the current locale for category LC_ALL, the value encodes the entire combination of selected locales for all categories. In this case, the value is not just a single locale name. In fact, we don't make any promises about what it looks like. But if you specify the same "locale name" with LC_ALL in a subsequent call to setlocale, it restores the same combination of locale selections. 

To be sure you can use the returned string encoding the currently selected locale at a later time, you must make a copy of the string. It is not guaranteed that the returned pointer remains valid over time. 

When the locale argument is not a null pointer, the string returned by setlocale reflects the newly-modified locale. 

If you specify an empty string for locale, this means to read the appropriate environment variable and use its value to select the locale for category. 

If a nonempty string is given for locale, then the locale of that name is used if possible. 

If you specify an invalid locale name, setlocale returns a null pointer and leaves the current locale unchanged.

Here is an example showing how you might use setlocale to temporarily switch to a new locale.

     #include <stddef.h>
     #include <locale.h>
     #include <stdlib.h>
     #include <string.h>
     
     void
     with_other_locale (char *new_locale,
                        void (*subroutine) (int),
                        int argument)
     {
       char *old_locale, *saved_locale;
     
       /* Get the name of the current locale.  */
       old_locale = setlocale (LC_ALL, NULL);
     
       /* Copy the name so it won't be clobbered by setlocale. */
       saved_locale = strdup (old_locale);
       if (saved_locale == NULL)
         fatal ("Out of memory");
     
       /* Now change the locale and do some stuff with it. */
       setlocale (LC_ALL, new_locale);
       (*subroutine) (argument);
     
       /* Restore the original locale. */
       setlocale (LC_ALL, saved_locale);
       free (saved_locale);
     }

Portability Note: Some ISO C systems may define additional locale categories, and future versions of the library will do so. For portability, assume that any symbol beginning with `LC_' might be defined in locale.h.

Shift State 
Previous:  Non-reentrant String Conversion , Up:  Non-reentrant Conversion 




States in Non-reentrant Functions

In some multibyte character codes, the meaning of any particular byte sequence is not fixed; it depends on what other sequences have come earlier in the same string. Typically there are just a few sequences that can change the meaning of other sequences; these few are called shift sequences and we say that they set the shift state for other sequences that follow. 

To illustrate shift state and shift sequences, suppose we decide that the sequence 0200 (just one byte) enters Japanese mode, in which pairs of bytes in the range from 0240 to 0377 are single characters, while 0201 enters Latin-1 mode, in which single bytes in the range from 0240 to 0377 are characters, and interpreted according to the ISO Latin-1 character set. This is a multibyte code that has two alternative shift states ("Japanese mode" and "Latin-1 mode"), and two shift sequences that specify particular shift states. 

When the multibyte character code in use has shift states, then mblen, mbtowc, and wctomb must maintain and update the current shift state as they scan the string. To make this work properly, you must follow these rules:

· Before starting to scan a string, call the function with a null pointer for the multibyte character address--for example, mblen (NULL, 0). This initializes the shift state to its standard initial value. 
· Scan the string one character at a time, in order. Do not "back up" and rescan characters already scanned, and do not intersperse the processing of different strings.

Here is an example of using mblen following these rules:

     void
     scan_string (char *s)
     {
       int length = strlen (s);
     
       /* Initialize shift state.  */
       mblen (NULL, 0);
     
       while (1)
         {
           int thischar = mblen (s, length);
           /* Deal with end of string and invalid characters.  */
           if (thischar == 0)
             break;
           if (thischar == -1)
             {
               error ("invalid multibyte character");
               break;
             }
           /* Advance past this character.  */
           s += thischar;
           length -= thischar;
         }
     }

The functions mblen, mbtowc and wctomb are not reentrant when using a multibyte code that uses a shift state. However, no other library functions call these functions, so you don't have to worry that the shift state will be changed mysteriously.

Sign of Money Amount 
Previous:  Currency Symbol , Up:  The Lame Way to Locale Data 




Printing the Sign of a Monetary Amount

These members of the struct lconv structure specify how to print the sign (if any) of a monetary value.

char *positive_sign
char *negative_sign
These are strings used to indicate positive (or zero) and negative monetary quantities, respectively. 

In the standard `C' locale, both of these members have a value of "" (the empty string), meaning "unspecified". 

The ISO standard doesn't say what to do when you find this value; we recommend printing positive_sign as you find it, even if it is empty. For a negative value, print negative_sign as you find it unless both it and positive_sign are empty, in which case print `-' instead. (Failing to indicate the sign at all seems rather unreasonable.) 
char p_sign_posn
char n_sign_posn
char int_p_sign_posn
char int_n_sign_posn
These members are small integers that indicate how to position the sign for nonnegative and negative monetary quantities, respectively. (The string used by the sign is what was specified with positive_sign or negative_sign.) The possible values are as follows:

0
The currency symbol and quantity should be surrounded by parentheses. 
1
Print the sign string before the quantity and currency symbol. 
2
Print the sign string after the quantity and currency symbol. 
3
Print the sign string right before the currency symbol. 
4
Print the sign string right after the currency symbol. 
CHAR_MAX
"Unspecified". Both members have this value in the standard `C' locale.

The ISO standard doesn't say what you should do when the value is CHAR_MAX. We recommend you print the sign after the currency symbol. 

The members with the int_ prefix apply to the int_curr_symbol while the other two apply to currency_symbol.

Signal Actions 
Next:  Defining Handlers , Previous:  Standard Signals , Up:  Signal Handling 




Specifying Signal Actions

The simplest way to change the action for a signal is to use the signal function. You can specify a built-in action (such as to ignore the signal), or you can establish a handler. 

·  Basic Signal Handling : The simple signal function.

Signal Generation 
Previous:  Kinds of Signals , Up:  Concepts of Signals 




Concepts of Signal Generation

In general, the events that generate signals fall into three major categories: errors, external events, and explicit requests. 

An error means that a program has done something invalid and cannot continue execution. But not all kinds of errors generate signals--in fact, most do not. For example, opening a nonexistent file is an error, but it does not raise a signal; instead, open returns -1. In general, errors that are necessarily associated with certain library functions are reported by returning a value that indicates an error. The errors which raise signals are those which can happen anywhere in the program, not just in library calls. These include division by zero and invalid memory addresses. 

Signals may be generated synchronously or asynchronously. A synchronous signal pertains to a specific action in the program, and is delivered (unless blocked) during that action. Most errors generate signals synchronously, and so do explicit requests by a process to generate a signal for that same process. On some machines, certain kinds of hardware errors (usually floating-point exceptions) are not reported completely synchronously, but may arrive a few instructions later. 

Asynchronous signals are generated by events outside the control of the process that receives them. These signals arrive at unpredictable times during execution. External events generate signals asynchronously, and so do explicit requests that apply to some other process. 

A given type of signal is either typically synchronous or typically asynchronous. For example, signals for errors are typically synchronous because errors generate signals synchronously. But any type of signal can be generated synchronously or asynchronously with an explicit request.

Signal Handling 
Next:  Program Basics , Previous:  Non-Local Exits , Up:  Top 




Signal Handling

A signal is a software interrupt delivered to a process. The operating system uses signals to report exceptional situations to an executing program. Some signals report errors such as references to invalid memory addresses; others report asynchronous events, such as disconnection of a phone line. 

The C library defines a variety of signal types, each for a particular kind of event. Some kinds of events make it inadvisable or impossible for the program to proceed as usual, and the corresponding signals normally abort the program. Other kinds of signals that report harmless events are ignored by default. 

If you anticipate an event that causes signals, you can define a handler function and tell the operating system to run it when that particular type of signal arrives. 

Finally, one process can send a signal to another process; this allows a parent process to abort a child, or two related processes to communicate and synchronize.

·  Concepts of Signals : Introduction to the signal facilities.
·  Standard Signals : Particular kinds of signals with standard names and meanings.
·  Signal Actions : Specifying what happens when a particular signal is delivered.
·  Defining Handlers : How to write a signal handler function.
·  Generating Signals : How to send a signal to a process.

Signaling Yourself 
Up:  Generating Signals 




Signaling Yourself

A process can send itself a signal with the raise function. This function is declared in signal.h.
-- Function: int raise (int signum)

The raise function sends the signal signum to the calling process. It returns zero if successful and a nonzero value if it fails. About the only reason for failure would be if the value of signum is invalid.

Portability note: raise was invented by the ISO C committee. Older systems may not support it.
Signals in Handler 
Next:  Nonreentrancy , Previous:  Longjmp in Handler , Up:  Defining Handlers 




Signals Arriving While a Handler Runs

What happens if another signal arrives while your signal handler function is running? 

When the handler for a particular signal is invoked, that signal is automatically blocked until the handler returns. That means that if two signals of the same kind arrive close together, the second one will be held until the first has been handled. 

Simple Calendar Time 
Next:  Broken-down Time , Up:  Calendar Time 




Simple Calendar Time

This section describes the time_t data type for representing calendar time as simple time, and the functions which operate on simple time objects. These facilities are declared in the header file time.h.
-- Data Type: time_t

This is the data type used to represent simple time. Sometimes, it also represents an elapsed time. When interpreted as a calendar time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time. (This calendar time is sometimes referred to as the epoch.) POSIX requires that this count not include leap seconds, but on some systems this count includes leap seconds if you set TZ to certain values (see  TZ Variable ). 

Note that a simple time has no concept of local time zone. Calendar Time T is the same instant in time regardless of where on the globe the computer is. 

In this C library, time_t is equivalent to long int. In other systems, time_t might be either an integer or floating-point type.

The function difftime tells you the elapsed time between two simple calendar times, which is not always as easy to compute as just subtracting. See  Elapsed Time .

-- Function: time_t time (time_t *result)

The time function returns the current calendar time as a value of type time_t. If the argument result is not a null pointer, the calendar time value is also stored in *result. If the current calendar time is not available, the value (time_t)(-1) is returned.

-- Function: int stime (time_t *newtime)

stime sets the system clock, i.e. it tells the system that the current calendar time is newtime, where newtime is interpreted as described in the above definition of time_t. 

If the function succeeds, the return value is zero.
Simple Output 
Next:  Character Input , Previous:  Streams and I18N , Up:  I/O on Streams 




Simple Output by Characters or Lines

This section describes functions for performing character- and line-oriented output. 

These narrow streams functions are declared in the header file stdio.h and the wide stream functions in wchar.h.

-- Function: int fputc (int c, FILE *stream)

The fputc function converts the character c to type unsigned char, and writes it to the stream stream. EOF is returned if a write error occurs; otherwise the character c is returned.

-- Function: wint_t fputwc (wchar_t wc, FILE *stream)

The fputwc function writes the wide character wc to the stream stream. WEOF is returned if a write error occurs; otherwise the character wc is returned.

-- Function: int putc (int c, FILE *stream)

This is just like fputc, except that most systems implement it as a macro, making it faster. One consequence is that it may evaluate the stream argument more than once, which is an exception to the general rule for macros. putc is usually the best function to use for writing a single character.

-- Function: wint_t putwc (wchar_t wc, FILE *stream)

This is just like fputwc, except that it can be implement as a macro, making it faster. One consequence is that it may evaluate the stream argument more than once, which is an exception to the general rule for macros. putwc is usually the best function to use for writing a single wide character.

-- Function: int putchar (int c)

The putchar function is equivalent to putc with stdout as the value of the stream argument.

-- Function: wint_t putwchar (wchar_t wc)

The putwchar function is equivalent to putwc with stdout as the value of the stream argument.

-- Function: int fputs (const char *s, FILE *stream)

The function fputs writes the string s to the stream stream. The terminating null character is not written. This function does not add a newline character, either. It outputs only the characters in the string. 

This function returns EOF if a write error occurs, and otherwise a non-negative value. 

For example: 

          fputs ("Are ", stdout);
          fputs ("you ", stdout);
          fputs ("hungry?\n", stdout);
     
outputs the text `Are you hungry?' followed by a newline.

-- Function: int fputws (const wchar_t *ws, FILE *stream)

The function fputws writes the wide character string ws to the stream stream. The terminating null character is not written. This function does not add a newline character, either. It outputs only the characters in the string. 

This function returns WEOF if a write error occurs, and otherwise a non-negative value.

-- Function: int puts (const char *s)

The puts function writes the string s to the stream stdout followed by a newline. The terminating null character of the string is not written. (Note that fputs does not write a newline as this function does.) 

puts is the most convenient function for printing simple messages. For example: 

          puts ("This is a message.");
     
outputs the text `This is a message.' followed by a newline.
Sleeping
Previous:  Calendar Time , Up:  Date and Time 




Sleeping

The function sleep gives a simple way to make the program wait for a short interval. If your program doesn't use signals (except to terminate), then you can expect sleep to wait reliably throughout the specified interval. Otherwise, sleep can return sooner if a signal arrives.

-- Function: unsigned int sleep (unsigned int seconds)

The sleep function waits for seconds or until a signal is delivered, whichever happens first. 

If sleep function returns because the requested interval is over, it returns a value of zero. If it returns because of delivery of a signal, its return value is the remaining time in the sleep interval. 

The sleep function is declared in unistd.h.

Resist the temptation to implement a sleep for a fixed amount of time by using the return value of sleep, when nonzero, to call sleep again. This will work with a certain amount of accuracy as long as signals arrive infrequently. But each signal can cause the eventual wakeup time to be off by an additional second or so. Suppose a few signals happen to arrive in rapid succession by bad luck--there is no limit on how much this could shorten or lengthen the wait. 

Instead, compute the calendar time at which the program should stop waiting, and keep trying to wait until that calendar time. This won't be off by more than a second. With just a little more work, you can use select and make the waiting period quite accurate. (Of course, heavy system load can cause additional unavoidable delays--unless the machine is dedicated to one application, there is no way you can avoid this.) 
Special Functions 
Next:  Pseudo-Random Numbers , Previous:  Hyperbolic Functions , Up:  Mathematics 




Special Functions

These are some more exotic mathematical functions which are sometimes useful. Currently they only have real-valued versions.

-- Function: double erf (double x)

-- Function: float erff (float x)

-- Function: long double erfl (long double x)

erf returns the error function of x. The error function is defined as 

          erf (x) = 2/sqrt(pi) * integral from 0 to x of exp(-t^2) dt
     
-- Function: double erfc (double x)

-- Function: float erfcf (float x)

-- Function: long double erfcl (long double x)

erfc returns 1.0 - erf(x), but computed in a fashion that avoids round-off error when x is large.

-- Function: double lgamma (double x)

-- Function: float lgammaf (float x)

-- Function: long double lgammal (long double x)

lgamma returns the natural logarithm of the absolute value of the gamma function of x. The gamma function is defined as 

          gamma (x) = integral from 0 to &infin; of t^(x-1) e^-t dt
     
The sign of the gamma function is stored in the global variable signgam, which is declared in math.h. It is 1 if the intermediate result was positive or zero, or -1 if it was negative. 

To compute the real gamma function you can use the tgamma function or you can compute the values as follows: 

          lgam = lgamma(x);
          gam  = signgam*exp(lgam);
     
The gamma function has singularities at the non-positive integers. lgamma will raise the zero divide exception if evaluated at a singularity.

-- Function: double tgamma (double x)

-- Function: float tgammaf (float x)

-- Function: long double tgammal (long double x)

tgamma applies the gamma function to x. The gamma function is defined as 

          gamma (x) = integral from 0 to &infin; of t^(x-1) e^-t dt
     
This function was introduced in ISO C99.


Standard Locales 
Next:  Locale Information , Previous:  Setting the Locale , Up:  Locales 




Standard Locales

The only locale names you can count on finding on all operating systems are these three standard ones:

"C"
This is the standard C locale. The attributes and behavior it provides are specified in the ISO C standard. When your program starts up, it initially uses this locale by default. 
"POSIX"
This is the standard POSIX locale. Currently, it is an alias for the standard C locale. 
""
The empty name says to select a locale based on environment variables. See  Locale Categories .

Defining and installing named locales is normally a responsibility of the system administrator at your site (or the person who installed the C library). It is also possible for the user to create private locales.

If your program needs to use something other than the `C' locale, it will be more portable if you use whatever locale the user specifies with the environment, rather than trying to specify some non-standard locale explicitly by name. Remember, different machines might have different sets of locales installed.

Standard Signals 
Next:  Signal Actions , Previous:  Concepts of Signals , Up:  Signal Handling 




Standard Signals

This section lists the names for various standard kinds of signals and describes what kind of event they mean. Each signal name is a macro which stands for a positive integer--the signal number for that kind of signal. Your programs should never make assumptions about the numeric code for a particular kind of signal, but rather refer to them always by the names defined here. This is because the number for a given kind of signal can vary from system to system, but the meanings of the names are standardized and fairly uniform. 

The signal names are defined in the header file signal.h.

-- Macro: int NSIG

The value of this symbolic constant is the total number of signals defined. Since the signal numbers are allocated consecutively, NSIG is also one greater than the largest defined signal number.

·  Program Error Signals : Used to report serious program errors.
·  Miscellaneous Signals : Miscellaneous Signals.

Standard Streams 
Next:  Opening Streams , Previous:  Streams , Up:  I/O on Streams 




Standard Streams

When the main function of your program is invoked, it already has three predefined streams open and available for use. These represent the "standard" input and output channels that have been established for the process. 

These streams are declared in the header file stdio.h.

-- Variable: FILE * stdin

The standard input stream, which is the normal source of input for the program.

-- Variable: FILE * stdout

The standard output stream, which is used for normal output from the program.

-- Variable: FILE * stderr

The standard error stream, which is used for error messages and diagnostics issued by the program.

In this system, you can specify what files or processes correspond to these streams using the pipe and redirection facilities provided by the shell. (The primitives shells use to implement these facilities are described in  File System Interface .) Most other operating systems provide similar mechanisms, but the details of how to use them can vary. 

In the C library, stdin, stdout, and stderr are normal variables which you can set just like any others. For example, to redirect the standard output to a file, you could do:

     fclose (stdout);
     stdout = fopen ("standard-output-file", "w");

Note however, that in other systems stdin, stdout, and stderr are macros that you cannot assign to in the normal way. But you can use freopen to get the effect of closing one and reopening it. See  Opening Streams . 

The three streams stdin, stdout, and stderr are not unoriented at program start (see  Streams and I18N ).

Status bit operations 
Next:  Math Error Reporting , Previous:  Infinity and NaN , Up:  Floating Point Errors 




Examining the FPU status word

ISO C99 defines functions to query and manipulate the floating-point status word. You can use these functions to check for untrapped exceptions when it's convenient, rather than worrying about them in the middle of a calculation. 

These constants represent the various IEEE 754 exceptions. Not all FPUs report all the different exceptions. Each constant is defined if and only if the FPU you are compiling for supports that exception, so you can test for FPU support with `#ifdef'. They are defined in fenv.h.

FE_INEXACT
The inexact exception.
FE_DIVBYZERO
The divide by zero exception.
FE_UNDERFLOW
The underflow exception.
FE_OVERFLOW
The overflow exception.
FE_INVALID
The invalid exception.

The macro FE_ALL_EXCEPT is the bitwise OR of all exception macros which are supported by the FP implementation. 

These functions allow you to clear exception flags, test for exceptions, and save and restore the set of exceptions flagged.
-- Function: int feclearexcept (int excepts)


This function clears all of the supported exception flags indicated by excepts. 

The function returns zero in case the operation was successful, a non-zero value otherwise.

-- Function: int feraiseexcept (int excepts)

This function raises the supported exceptions indicated by excepts. If more than one exception bit in excepts is set the order in which the exceptions are raised is undefined except that overflow (FE_OVERFLOW) or underflow (FE_UNDERFLOW) are raised before inexact (FE_INEXACT). Whether for overflow or underflow the inexact exception is also raised is also implementation dependent. 

The function returns zero in case the operation was successful, a non-zero value otherwise.

-- Function: int fetestexcept (int excepts)

Test whether the exception flags indicated by the parameter except are currently set. If any of them are, a nonzero value is returned which specifies which exceptions are set. Otherwise the result is zero.

To understand these functions, imagine that the status word is an integer variable named status. feclearexcept is then equivalent to `status &= ~excepts' and fetestexcept is equivalent to `(status & excepts)'. The actual implementation may be very different, of course. 

Exception flags are only cleared when the program explicitly requests it, by calling feclearexcept. If you want to check for exceptions from a set of calculations, you should clear all the flags first. Here is a simple example of the way to use fetestexcept:

     {
       double f;
       int raised;
       feclearexcept (FE_ALL_EXCEPT);
       f = compute ();
       raised = fetestexcept (FE_OVERFLOW | FE_INVALID);
       if (raised & FE_OVERFLOW) { /* ... */ }
       if (raised & FE_INVALID) { /* ... */ }
       /* ... */
     }

You cannot explicitly set bits in the status word. You can, however, save the entire status word and restore it later. This is done with the following functions:

-- Function: int fegetexceptflag (fexcept_t *flagp, int excepts)

This function stores in the variable pointed to by flagp an implementation-defined value representing the current setting of the exception flags indicated by excepts. 

The function returns zero in case the operation was successful, a non-zero value otherwise.

-- Function: int fesetexceptflag (const fexcept_t *flagp, int

excepts) This function restores the flags for the exceptions indicated by excepts to the values stored in the variable pointed to by flagp. 

The function returns zero in case the operation was successful, a non-zero value otherwise.

Note that the value stored in fexcept_t bears no resemblance to the bit mask returned by fetestexcept. The type may not even be an integer. Do not attempt to modify an fexcept_t variable.

Stream Buffering 
Previous:  Portable Positioning , Up:  I/O on Streams 




Stream Buffering

Characters that are written to a stream are normally accumulated and transmitted asynchronously to the file in a block, instead of appearing as soon as they are output by the application program. Similarly, streams often retrieve input from the host environment in blocks rather than on a character-by-character basis. This is called buffering. 

If you are writing programs that do interactive input and output using streams, you need to understand how buffering works when you design the user interface to your program. Otherwise, you might find that output (such as progress or prompt messages) doesn't appear when you intended it to, or displays some other unexpected behavior. 

This section deals only with controlling when characters are transmitted between the stream and the file or device, and not with how things like echoing, flow control, and the like are handled on specific classes of devices. 

You can bypass the stream buffering facilities altogether by using the low-level input and output functions that operate on file descriptors instead. See  Low-Level I/O .

·  Buffering Concepts : Terminology is defined here.
·  Flushing Buffers : How to ensure that output buffers are flushed.
·  Controlling Buffering : How to specify what kind of buffering to use.

Streams and File Descriptors 
Next:  File Position , Up:  I/O Concepts 




Streams and File Descriptors

When you want to do input or output to a file, you have a choice of two basic mechanisms for representing the connection between your program and the file: file descriptors and streams. File descriptors are represented as objects of type int, while streams are represented as FILE * objects. 

File descriptors provide a primitive, low-level interface to input and output operations. Both file descriptors and streams can represent a connection to a device (such as a terminal), as well as a normal file. But, if you want to do control operations that are specific to a particular kind of device, you must use a file descriptor; there are no facilities to use streams in this way. You must also use file descriptors if your program needs to do input or output in special modes, such as nonblocking (or polled) input (see  File Status Flags ). 

Streams provide a higher-level interface.  he stream interface treats all kinds of files pretty much alike--the sole exception being the three styles of buffering that you can choose (see  Stream Buffering ). 

The main advantage of using the stream interface is that the set of functions for performing actual input and output operations (as opposed to control operations) on streams is much richer and more powerful than the corresponding facilities for file descriptors. The file descriptor interface provides only simple functions for transferring blocks of characters, but the stream interface also provides powerful formatted input and output functions (printf and scanf) as well as functions for character- and line-oriented input and output. 

In general, you should stick with using streams rather than file descriptors, unless there is some specific operation you want to do that can only be done on a file descriptor. If you are a beginning programmer and aren't sure what functions to use, we suggest that you concentrate on the formatted input functions (see  Formatted Input ) and formatted output functions (see  Formatted Output ). 

If you are concerned about portability of your programs to systems other than this, you should also be aware that file descriptors are not as portable as streams. You can expect any system running ISO C to support streams, but other systems may not support file descriptors at all, or may only implement a subset of the functions that operate on file descriptors. Most of the file descriptor functions in this library are included in the POSIX.1 standard, however.

Streams and I18N 
Next:  Simple Output , Previous:  Streams and Threads , Up:  I/O on Streams 




Streams in Internationalized Applications

ISO C90 introduced the new type wchar_t to allow handling larger character sets. What was missing was a possibility to output strings of wchar_t directly. One had to convert them into multibyte strings using mbstowcs (there was no mbsrtowcs yet) and then use the normal stream functions. While this is doable it is very cumbersome since performing the conversions is not trivial and greatly increases program complexity and size. 

The Unix standard early on (I think in XPG4.2) introduced two additional format specifiers for the printf and scanf families of functions. Printing and reading of single wide characters was made possible using the %C specifier and wide character strings can be handled with %S. These modifiers behave just like %c and %s only that they expect the corresponding argument to have the wide character type and that the wide character and string are transformed into/from multibyte strings before being used. 

This was a beginning but it is still not good enough. Not always is it desirable to use printf and scanf. The other, smaller and faster functions cannot handle wide characters. Second, it is not possible to have a format string for printf and scanf consisting of wide characters. The result is that format strings would have to be generated if they have to contain non-basic characters. 

In the Amendment 1 to ISO C90 a whole new set of functions was added to solve the problem. Most of the stream functions got a counterpart which take a wide character or wide character string instead of a character or string respectively. The new functions operate on the same streams (like stdout). This is different from the model of the C++ runtime library where separate streams for wide and normal I/O are used. 

Being able to use the same stream for wide and normal operations comes with a restriction: a stream can be used either for wide operations or for normal operations. Once it is decided there is no way back. Only a call to freopen or freopen64 can reset the orientation. The orientation can be decided in three ways:

· If any of the normal character functions is used (this includes the fread and fwrite functions) the stream is marked as not wide oriented. 
· If any of the wide character functions is used the stream is marked as wide oriented. 
· The fwide function can be used to set the orientation either way.

It is important to never mix the use of wide and not wide operations on a stream. There are no diagnostics issued. The application behavior will simply be strange or the application will simply crash. The fwide function can help avoiding this.

-- Function: int fwide (FILE *stream, int mode)

The fwide function can be used to set and query the state of the orientation of the stream stream. If the mode parameter has a positive value the streams get wide oriented, for negative values narrow oriented. It is not possible to overwrite previous orientations with fwide. I.e., if the stream stream was already oriented before the call nothing is done. 

If mode is zero the current orientation state is queried and nothing is changed. 

The fwide function returns a negative value, zero, or a positive value if the stream is narrow, not at all, or wide oriented respectively. 

This function was introduced in Amendment 1 to ISO C90 and is declared in wchar.h.

It is generally a good idea to orient a stream as early as possible. This can prevent surprise especially for the standard streams stdin, stdout, and stderr. If some library function in some situations uses one of these streams and this use orients the stream in a different way the rest of the application expects it one might end up with hard to reproduce errors. Remember that no errors are signal if the streams are used incorrectly. Leaving a stream unoriented after creation is normally only necessary for library functions which create streams which can be used in different contexts. 

When writing code which uses streams and which can be used in different contexts it is important to query the orientation of the stream before using it (unless the rules of the library interface demand a specific orientation). The following little, silly function illustrates this.

     void
     print_f (FILE *fp)
     {
       if (fwide (fp, 0) > 0)
         /* Positive return value means wide orientation.  */
         fputwc (L'f', fp);
       else
         fputc ('f', fp);
     }

Note that in this case the function print_f decides about the orientation of the stream if it was unoriented before (will not happen if the advise above is followed). 

The encoding used for the wchar_t values is unspecified and the user must not make any assumptions about it. For I/O of wchar_t values this means that it is impossible to write these values directly to the stream. This is not what follows from the ISO C locale model either. What happens instead is that the bytes read from or written to the underlying media are first converted into the internal encoding chosen by the implementation for wchar_t. The external encoding is determined by the LC_CTYPE category of the current locale or by the `ccs' part of the mode specification given to fopen, fopen64, freopen, or freopen64. How and when the conversion happens is unspecified and it happens invisible to the user. 

Since a stream is created in the unoriented state it has at that point no conversion associated with it. The conversion which will be used is determined by the LC_CTYPE category selected at the time the stream is oriented. If the locales are changed at the runtime this might produce surprising results unless one pays attention. This is just another good reason to orient the stream explicitly as soon as possible, perhaps with a call to fwide.

Streams
Next:  Standard Streams , Up:  I/O on Streams 




Streams

For historical reasons, the type of the C data structure that represents a stream is called FILE rather than "stream". Since most of the library functions deal with objects of type FILE *, sometimes the term file pointer is also used to mean "stream". This leads to unfortunate confusion over terminology in many books on C. This manual, however, is careful to use the terms "file" and "stream" only in the technical sense. The FILE type is declared in the header file stdio.h.

-- Data Type: FILE

This is the data type used to represent stream objects. A FILE object holds all of the internal state information about the connection to the associated file, including such things as the file position indicator and buffering information. Each stream also has error and end-of-file status indicators that can be tested with the ferror and feof functions; see  EOF and Errors .

FILE objects are allocated and managed internally by the input/output library functions. Don't try to create your own objects of type FILE; let the library do it. Your programs should deal only with pointers to these objects (that is, FILE * values) rather than the objects themselves.

String and Array Utilities 
Next:  Character Set Handling , Previous:  Character Handling , Up:  Top 




String and Array Utilities

Operations on strings (or arrays of characters) are an important part of many programs. The C library provides an extensive set of string utility functions, including functions for copying, concatenating, comparing, and searching strings. Many of these functions can also operate on arbitrary regions of storage; for example, the memcpy function can be used to copy the contents of any kind of array. 

It's fairly common for beginning C programmers to "reinvent the wheel" by duplicating this functionality in their own code, but it pays to become familiar with the library functions and to make use of them, since this offers benefits in maintenance, efficiency, and portability. 

For instance, you could easily compare one string to another in two lines of C code, but if you use the built-in strcmp function, you're less likely to make a mistake. And, since these library functions are typically highly optimized, your program may run faster too.

·  Representation of Strings : Introduction to basic concepts.
·  String/Array Conventions : Whether to use a string function or an arbitrary array function.
·  String Length : Determining the length of a string.
·  Copying and Concatenation : Functions to copy the contents of strings and arrays.
·  String/Array Comparison : Functions for byte-wise and character-wise comparison.
·  Collation Functions : Functions for collating strings.
·  Search Functions : Searching for a specific element or substring.
·  Finding Tokens in a String : Splitting a string into tokens by looking for delimiters.
+ String Input Conversions 
Next:  Dynamic String Input , Previous:  Numeric Input Conversions , Up:  Formatted Input 




String Input Conversions

This section describes the scanf input conversions for reading string and character values: `%s', `%S', `%[', `%c', and `%C'. 

You have two options for how to receive the input from these conversions:

· Provide a buffer to store it in. This is the default. You should provide an argument of type char * or wchar_t * (the latter of the `l' modifier is present). 

Warning: To make a robust program, you must make sure that the input (plus its terminating null) cannot possibly exceed the size of the buffer you provide. In general, the only way to do this is to specify a maximum field width one less than the buffer size. If you provide the buffer, always specify a maximum field width to prevent overflow. 
· Ask scanf to allocate a big enough buffer, by specifying the `a' flag character. This is a GNU extension. You should provide an argument of type char ** for the buffer address to be stored in. See  Dynamic String Input .

The `%c' conversion is the simplest: it matches a fixed number of characters, always. The maximum field width says how many characters to read; if you don't specify the maximum, the default is 1. This conversion doesn't append a null character to the end of the text it reads. It also does not skip over initial whitespace characters. It reads precisely the next n characters, and fails if it cannot get that many. Since there is always a maximum field width with `%c' (whether specified, or 1 by default), you can always prevent overflow by making the buffer long enough. 

If the format is `%lc' or `%C' the function stores wide characters which are converted using the conversion determined at the time the stream was opened from the external byte stream. The number of bytes read from the medium is limited by MB_CUR_LEN * n but at most n wide character get stored in the output string. 

The `%s' conversion matches a string of non-whitespace characters. It skips and discards initial whitespace, but stops when it encounters more whitespace after having read something. It stores a null character at the end of the text that it reads. 

For example, reading the input:

      hello, world

with the conversion `%10c' produces " hello, wo", but reading the same input with the conversion `%10s' produces "hello,". 

Warning: If you do not specify a field width for `%s', then the number of characters read is limited only by where the next whitespace character appears. This almost certainly means that invalid input can make your program crash--which is a bug. 

The `%ls' and `%S' format are handled just like `%s' except that the external byte sequence is converted using the conversion associated with the stream to wide characters with their own encoding. A width or precision specified with the format do not directly determine how many bytes are read from the stream since they measure wide characters. But an upper limit can be computed by multiplying the value of the width or precision by MB_CUR_MAX. 

To read in characters that belong to an arbitrary set of your choice, use the `%[' conversion. You specify the set between the `[' character and a following `]' character, using the same syntax used in regular expressions. As special cases:

· A literal `]' character can be specified as the first character of the set. 
· An embedded `-' character (that is, one that is not the first or last character of the set) is used to specify a range of characters. 
· If a caret character `^' immediately follows the initial `[', then the set of allowed input characters is the everything except the characters listed.

The `%[' conversion does not skip over initial whitespace characters. 

Here are some examples of `%[' conversions and what they mean:

`%25[1234567890]'
Matches a string of up to 25 digits. 
`%25[][]'
Matches a string of up to 25 square brackets. 
`%25[^ \f\n\r\t'
Matches a string up to 25 characters long that doesn't contain any of the standard whitespace characters. This is slightly different from `%s', because if the input begins with a whitespace character, `%[' reports a matching failure while `%s' simply discards the initial whitespace. 
`%25[a-z]'
Matches up to 25 lowercase characters.

As for `%c' and `%s' the `%[' format is also modified to produce wide characters if the `l' modifier is present. All what is said about `%ls' above is true for `%l['. 

One more reminder: the `%s' and `%[' conversions are dangerous if you don't specify a maximum width or use the `a' flag, because input too long would overflow whatever buffer you have provided for it. No matter how long your buffer is, a user could supply input that is longer. A well-written program reports invalid input with a comprehensible error message, not with a crash.


String Length 
Next:  Copying and Concatenation , Previous:  String/Array Conventions , Up:  String and Array Utilities 




String Length

You can get the length of a string using the strlen function. This function is declared in the header file string.h.

-- Function: size_t strlen (const char *s)

The strlen function returns the length of the null-terminated string s in bytes. (In other words, it returns the offset of the terminating null character within the array.) 

For example, 

          strlen ("hello, world")
              => 12
     
When applied to a character array, the strlen function returns the length of the string stored there, not its allocated size. You can get the allocated size of the character array that holds a string using the sizeof operator: 

          char string[32] = "hello, world";
          sizeof (string)
              => 32
          strlen (string)
              => 12
     
But beware, this will not work unless string is the character array itself, not a pointer to it. For example: 

          char string[32] = "hello, world";
          char *ptr = string;
          sizeof (string)
              => 32
          sizeof (ptr)
              => 4  /* (on a machine with 4 byte pointers) */
     
This is an easy mistake to make when you are working with functions that take string arguments; those arguments are always pointers, not arrays. 

It must also be noted that for multibyte encoded strings the return value does not have to correspond to the number of characters in the string. To get this value the string can be converted to wide characters and wcslen can be used or something like the following code can be used: 

          /* The input is in string.
             The length is expected in n.  */
          {
            mbstate_t t;
            char *scopy = string;
            /* In initial state.  */
            memset (&t, '\0', sizeof (t));
            /* Determine number of characters.  */
            n = mbsrtowcs (NULL, &scopy, strlen (scopy), &t);
          }
     
This is cumbersome to do so if the number of characters (as opposed to bytes) is needed often it is better to work with wide characters.

The wide character equivalent is declared in wchar.h.

-- Function: size_t wcslen (const wchar_t *ws)

The wcslen function is the wide character equivalent to strlen. The return value is the number of wide characters in the wide character string pointed to by ws (this is also the offset of the terminating null wide character of ws). 

Since there are no multi wide character sequences making up one character the return value is not only the offset in the array, it is also the number of wide characters. 

This function was introduced in Amendment 1 to ISO C90.
String/Array Comparison 
Next:  Collation Functions , Previous:  Copying and Concatenation , Up:  String and Array Utilities 




String/Array Comparison

You can use the functions in this section to perform comparisons on the contents of strings and arrays. As well as checking for equality, these functions can also be used as the ordering functions for sorting operations. See  Searching and Sorting , for an example of this. 

Unlike most comparison operations in C, the string comparison functions return a nonzero value if the strings are not equivalent rather than if they are. The sign of the value indicates the relative ordering of the first characters in the strings that are not equivalent: a negative value indicates that the first string is "less" than the second, while a positive value indicates that the first string is "greater". 

The most common use of these functions is to check only for equality. This is canonically done with an expression like `! strcmp (s1, s2)'. 

All of these functions are declared in the header file string.h.

-- Function: int memcmp (const void *a1, const void *a2, size_t size)

The function memcmp compares the size bytes of memory beginning at a1 against the size bytes of memory beginning at a2. The value returned has the same sign as the difference between the first differing pair of bytes (interpreted as unsigned char objects, then promoted to int). 

If the contents of the two blocks are equal, memcmp returns 0.

-- Function: int wmemcmp (const wchar_t *a1, const wchar_t *a2, size_t size)

The function wmemcmp compares the size wide characters beginning at a1 against the size wide characters beginning at a2. The value returned is smaller than or larger than zero depending on whether the first differing wide character is a1 is smaller or larger than the corresponding character in a2. 

If the contents of the two blocks are equal, wmemcmp returns 0.

On arbitrary arrays, the memcmp function is mostly useful for testing equality. It usually isn't meaningful to do byte-wise ordering comparisons on arrays of things other than bytes. For example, a byte-wise comparison on the bytes that make up floating-point numbers isn't likely to tell you anything about the relationship between the values of the floating-point numbers. 

wmemcmp is really only useful to compare arrays of type wchar_t since the function looks at sizeof (wchar_t) bytes at a time and this number of bytes is system dependent. 

You should also be careful about using memcmp to compare objects that can contain "holes", such as the padding inserted into structure objects to enforce alignment requirements, extra space at the end of unions, and extra characters at the ends of strings whose length is less than their allocated size. The contents of these "holes" are indeterminate and may cause strange behavior when performing byte-wise comparisons. For more predictable results, perform an explicit component-wise comparison. 

For example, given a structure type definition like:

     struct foo
       {
         unsigned char tag;
         union
           {
             double f;
             long i;
             char *p;
           } value;
       };

you are better off writing a specialized comparison function to compare struct foo objects instead of comparing them with memcmp.

-- Function: int strcmp (const char *s1, const char *s2)

The strcmp function compares the string s1 against s2, returning a value that has the same sign as the difference between the first differing pair of characters (interpreted as unsigned char objects, then promoted to int). 

If the two strings are equal, strcmp returns 0. 

A consequence of the ordering used by strcmp is that if s1 is an initial substring of s2, then s1 is considered to be "less than" s2. 

strcmp does not take sorting conventions of the language the strings are written in into account. To get that one has to use strcoll.

-- Function: int wcscmp (const wchar_t *ws1, const wchar_t *ws2)

The wcscmp function compares the wide character string ws1 against ws2. The value returned is smaller than or larger than zero depending on whether the first differing wide character is ws1 is smaller or larger than the corresponding character in ws2. 

If the two strings are equal, wcscmp returns 0. 

A consequence of the ordering used by wcscmp is that if ws1 is an initial substring of ws2, then ws1 is considered to be "less than" ws2. 

wcscmp does not take sorting conventions of the language the strings are written in into account. To get that one has to use wcscoll.

-- Function: int strcasecmp (const char *s1, const char *s2)

This function is like strcmp, except that differences in case are ignored. How uppercase and lowercase characters are related is determined by the currently selected locale. In the standard "C" locale the characters Ä and ä do not match but in a locale which regards these characters as parts of the alphabet they do match. 

strcasecmp is derived from BSD.

-- Function: int wcscasecmp (const wchar_t *ws1, const wchar_T *ws2)

This function is like wcscmp, except that differences in case are ignored. How uppercase and lowercase characters are related is determined by the currently selected locale. In the standard "C" locale the characters Ä and ä do not match but in a locale which regards these characters as parts of the alphabet they do match. 

wcscasecmp is a GNU extension.

-- Function: int strncmp (const char *s1, const char *s2, size_t size)

This function is the similar to strcmp, except that no more than size wide characters are compared. In other words, if the two strings are the same in their first size wide characters, the return value is zero.

-- Function: int wcsncmp (const wchar_t *ws1, const wchar_t *ws2, size_t size)

This function is the similar to wcscmp, except that no more than size wide characters are compared. In other words, if the two strings are the same in their first size wide characters, the return value is zero.

-- Function: int strnicmp (const char *s1, const char *s2, size_t n)

This function is like strncmp, except that differences in case are ignored. Like strcasecmp, it is locale dependent how uppercase and lowercase characters are related. 

strncasecmp is an extension.

-- Function: int wcsnicmp (const wchar_t *ws1, const wchar_t *s2, size_t n)

This function is like wcsncmp, except that differences in case are ignored. Like wcscasecmp, it is locale dependent how uppercase and lowercase characters are related. 

wcsncasecmp is an extension.

Here are some examples showing the use of strcmp and strncmp (equivalent examples can be constructed for the wide character functions). These examples assume the use of the ASCII character set. (If some other character set--say, EBCDIC--is used instead, then the glyphs are associated with different numeric codes, and the return values and ordering may differ.)

     strcmp ("hello", "hello")
         => 0    /* These two strings are the same. */
     strcmp ("hello", "Hello")
         => 32   /* Comparisons are case-sensitive. */
     strcmp ("hello", "world")
         => -15  /* The character 'h' comes before 'w'. */
     strcmp ("hello", "hello, world")
         => -44  /* Comparing a null character against a comma. */
     strncmp ("hello", "hello, world", 5)
         => 0    /* The initial 5 characters are the same. */
     strncmp ("hello, world", "hello, stupid world!!!", 5)
         => 0    /* The initial 5 characters are the same. */

String/Array Conventions 
Next:  String Length , Previous:  Representation of Strings , Up:  String and Array Utilities 




String and Array Conventions

This chapter describes both functions that work on arbitrary arrays or blocks of memory, and functions that are specific to null-terminated arrays of characters and wide characters. 

Functions that operate on arbitrary blocks of memory have names beginning with `mem' and `wmem' (such as memcpy and wmemcpy) and invariably take an argument which specifies the size (in bytes and wide characters respectively) of the block of memory to operate on. The array arguments and return values for these functions have type void * or wchar_t. As a matter of style, the elements of the arrays used with the `mem' functions are referred to as "bytes". You can pass any kind of pointer to these functions, and the sizeof operator is useful in computing the value for the size argument. Parameters to the `wmem' functions must be of type wchar_t *. These functions are not really usable with anything but arrays of this type. 

In contrast, functions that operate specifically on strings and wide character strings have names beginning with `str' and `wcs' respectively (such as strcpy and wcscpy) and look for a null character to terminate the string instead of requiring an explicit size argument to be passed. (Some of these functions accept a specified maximum length, but they also check for premature termination with a null character.) The array arguments and return values for these functions have type char * and wchar_t * respectively, and the array elements are referred to as "characters" and "wide characters". 

In many cases, there are both `mem' and `str'/`wcs' versions of a function. The one that is more appropriate to use depends on the exact situation. When your program is manipulating arbitrary arrays or blocks of storage, then you should always use the `mem' functions. On the other hand, when you are manipulating null-terminated strings it is usually more convenient to use the `str'/`wcs' functions, unless you already know the length of the string in advance. The `wmem' functions should be used for wide character arrays with known size. 

Some of the memory and string functions take single characters as arguments. Since a value of type char is automatically promoted into an value of type int when used as a parameter, the functions are declared with int as the type of the parameter in question. In case of the wide character function the situation is similarly: the parameter type for a single wide character is wint_t and not wchar_t. This would for many implementations not be necessary since the wchar_t is large enough to not be automatically promoted, but since the ISO C standard does not require such a choice of types the wint_t type is used.

Structure Measurement 
Previous:  Floating Type Macros , Up:  Data Type Measurements 




Structure Field Offset Measurement

You can use offsetof to measure the location within a structure type of a particular structure member.

-- Macro: size_t offsetof (type, member)

This expands to a integer constant expression that is the offset of the structure member named member in a the structure type type. For example, offsetof (struct s, elem) is the offset, in bytes, of the member elem in a struct s. 

This macro won't work if member is a bit field; you get an error from the C compiler in that case.

Table of Input Conversions 
Next:  Numeric Input Conversions , Previous:  Input Conversion Syntax , Up:  Formatted Input 




Table of Input Conversions

Here is a table that summarizes the various conversion specifications:

`%d'
Matches an optionally signed integer written in decimal. See  Numeric Input Conversions . 
`%i'
Matches an optionally signed integer in any of the formats that the C language defines for specifying an integer constant. See  Numeric Input Conversions . 
`%o'
Matches an unsigned integer written in octal radix. See  Numeric Input Conversions . 
`%u'
Matches an unsigned integer written in decimal radix. See  Numeric Input Conversions . 
`%x', `%X'
Matches an unsigned integer written in hexadecimal radix. See  Numeric Input Conversions . 
`%e', `%f', `%g', `%E', `%G'
Matches an optionally signed floating-point number. See  Numeric Input Conversions . 
`%s'
Matches a string containing only non-whitespace characters. See  String Input Conversions . The presence of the `l' modifier determines whether the output is stored as a wide character string or a multibyte string. If `%s' is used in a wide character function the string is converted as with multiple calls to wcrtomb into a multibyte string. This means that the buffer must provide room for MB_CUR_MAX bytes for each wide character read. In case `%ls' is used in a multibyte function the result is converted into wide characters as with multiple calls of mbrtowc before being stored in the user provided buffer. 
`%S'
This is an alias for `%ls' which is supported for compatibility with the Unix standard. 
`%['
Matches a string of characters that belong to a specified set. See  String Input Conversions . The presence of the `l' modifier determines whether the output is stored as a wide character string or a multibyte string. If `%[' is used in a wide character function the string is converted as with multiple calls to wcrtomb into a multibyte string. This means that the buffer must provide room for MB_CUR_MAX bytes for each wide character read. In case `%l[' is used in a multibyte function the result is converted into wide characters as with multiple calls of mbrtowc before being stored in the user provided buffer. 
`%c'
Matches a string of one or more characters; the number of characters read is controlled by the maximum field width given for the conversion. See  String Input Conversions . 

If the `%c' is used in a wide stream function the read value is converted from a wide character to the corresponding multibyte character before storing it. Note that this conversion can produce more than one byte of output and therefore the provided buffer be large enough for up to MB_CUR_MAX bytes for each character. If `%lc' is used in a multibyte function the input is treated as a multibyte sequence (and not bytes) and the result is converted as with calls to mbrtowc. 
`%C'
This is an alias for `%lc' which is supported for compatibility with the Unix standard. 
`%p'
Matches a pointer value in the same implementation-defined format used by the `%p' output conversion for printf. See  Other Input Conversions . 
`%n'
This conversion doesn't read any characters; it records the number of characters read so far by this call. See  Other Input Conversions . 
`%%'
This matches a literal `%' character in the input stream. No corresponding argument is used. See  Other Input Conversions .

If the syntax of a conversion specification is invalid, the behavior is undefined. If there aren't enough function arguments provided to supply addresses for all the conversion specifications in the template strings that perform assignments, or if the arguments are not of the correct types, the behavior is also undefined. On the other hand, extra arguments are simply ignored.

Table of Output Conversions 
Next:  Integer Conversions , Previous:  Output Conversion Syntax , Up:  Formatted Output 




Table of Output Conversions

Here is a table summarizing what all the different conversions do:

`%d', `%i'
Print an integer as a signed decimal number. See  Integer Conversions , for details. `%d' and `%i' are synonymous for output, but are different when used with scanf for input (see  Table of Input Conversions ). 
`%o'
Print an integer as an unsigned octal number. See  Integer Conversions , for details. 
`%u'
Print an integer as an unsigned decimal number. See  Integer Conversions , for details. 
`%x', `%X'
Print an integer as an unsigned hexadecimal number. `%x' uses lower-case letters and `%X' uses upper-case. See  Integer Conversions , for details. 
`%f'
Print a floating-point number in normal (fixed-point) notation. See  Floating-Point Conversions , for details. 
`%e', `%E'
Print a floating-point number in exponential notation. `%e' uses lower-case letters and `%E' uses upper-case. See  Floating-Point Conversions , for details. 
`%g', `%G'
Print a floating-point number in either normal or exponential notation, whichever is more appropriate for its magnitude. `%g' uses lower-case letters and `%G' uses upper-case. See  Floating-Point Conversions , for details. 
`%a', `%A'
Print a floating-point number in a hexadecimal fractional notation which the exponent to base 2 represented in decimal digits. `%a' uses lower-case letters and `%A' uses upper-case. See  Floating-Point Conversions , for details. 
`%c'
Print a single character. See  Other Output Conversions . 
`%C'
This is an alias for `%lc' which is supported for compatibility with the Unix standard. 
`%s'
Print a string. See  Other Output Conversions . 
`%S'
This is an alias for `%ls' which is supported for compatibility with the Unix standard. 
`%p'
Print the value of a pointer. See  Other Output Conversions . 
`%n'
Get the number of characters printed so far. See  Other Output Conversions . Note that this conversion specification never produces any output. 
`%m'
Print the string corresponding to the value of errno. (This is a GNU extension.) See  Other Output Conversions . 
`%%'
Print a literal `%' character. See  Other Output Conversions .

If the syntax of a conversion specification is invalid, unpredictable things will happen, so don't do this. If there aren't enough function arguments provided to supply values for all the conversion specifications in the template string, or if the arguments are not of the correct types, the results are unpredictable. If you supply more arguments than conversion specifications, the extra argument values are simply ignored; this is sometimes useful.

Temporary Files 
Next:  File Size , Previous:  Creating Directories , Up:  File System Interface 




Temporary Files

If you need to use a temporary file in your program, you can use the tmpfile function to open it. Or you can use the tmpnam (better: tmpnam_r) function to provide a name for a temporary file and then you can open it in the usual way with fopen. 

The tempnam function is like tmpnam but lets you choose what directory temporary files will go in, and something about what their file names will look like. Important for multi-threaded programs is that tempnam is reentrant, while tmpnam is not since it returns a pointer to a static buffer. 

These facilities are declared in the header file stdio.h.

-- Function: FILE * tmpfile (void)

This function creates a temporary binary file for update mode, as if by calling fopen with mode "wb+". The file is deleted automatically when it is closed or when the program terminates. (On some other ISO C systems the file may fail to be deleted if the program terminates abnormally). 

This function is reentrant. 

-- Function: char * tmpnam (char *result)

This function constructs and returns a valid file name that does not refer to any existing file. If the result argument is a null pointer, the return value is a pointer to an internal static string, which might be modified by subsequent calls and therefore makes this function non-reentrant. Otherwise, the result argument should be a pointer to an array of at least L_tmpnam characters, and the result is written into that array. 

It is possible for tmpnam to fail if you call it too many times without removing previously-created files. This is because the limited length of the temporary file names gives room for only a finite number of different names. If tmpnam fails it returns a null pointer. 

Warning: Between the time the pathname is constructed and the file is created another process might have created a file with the same name using tmpnam, leading to a possible security hole. The implementation generates names which can hardly be predicted, but when opening the file you should use the O_EXCL flag. Using tmpfile or mkstemp is a safe way to avoid this problem.

-- Macro: int L_tmpnam

The value of this macro is an integer constant expression that represents the minimum size of a string large enough to hold a file name generated by the tmpnam function.

-- Macro: int TMP_MAX

The macro TMP_MAX is a lower bound for how many temporary names you can create with tmpnam. You can rely on being able to call tmpnam at least this many times before it might fail saying you have made too many temporary file names. 

With the GNU library, you can create a very large number of temporary file names. If you actually created the files, you would probably run out of disk space before you ran out of names. Some other systems have a fixed, small limit on the number of temporary files. The limit is never less than 25.


Termination in Handler 
Next:  Longjmp in Handler , Previous:  Handler Returns , Up:  Defining Handlers 




Handlers That Terminate the Process

Handler functions that terminate the program are typically used to cause orderly cleanup or recovery from program error signals and interactive interrupts. 

The cleanest way for a handler to terminate the process is to raise the same signal that ran the handler in the first place. Here is how to do this:

     volatile sig_atomic_t fatal_error_in_progress = 0;
     
     void
     fatal_error_signal (int sig)
     {
       /* Since this handler is established for more than one kind of signal, 
          it might still get invoked recursively by delivery of some other kind
          of signal.  Use a static variable to keep track of that. */
       if (fatal_error_in_progress)
         raise (sig);
       fatal_error_in_progress = 1;
     
       /* Now do the clean up actions:
          - reset terminal modes
          - kill child processes
          - remove lock files */
       ...
     
       /* Now reraise the signal.  We reactivate the signal's
          default handling, which is to terminate the process.
          We could just call exit or abort,
          but reraising the signal sets the return status
          from the process correctly. */
       signal (sig, SIG_DFL);
       raise (sig);
     }

The Lame Way to Locale Data 
Up:  Locale Information 




localeconv: It is portable but ...

Together with the setlocale function the ISO C people invented the localeconv function. It is a masterpiece of poor design. It is expensive to use, not extendable, and not generally usable as it provides access to only LC_MONETARY and LC_NUMERIC related information. Nevertheless, if it is applicable to a given situation it should be used since it is very portable. The function strfmon formats monetary amounts according to the selected locale using this information.
-- Function: struct lconv * localeconv (void)

The localeconv function returns a pointer to a structure whose components contain information about how numeric and monetary values should be formatted in the current locale. 

You should not modify the structure or its contents. The structure might be overwritten by subsequent calls to localeconv, or by calls to setlocale, but no other function in the library overwrites this value.

-- Data Type: struct lconv

localeconv's return value is of this data type. Its elements are described in the following subsections.

If a member of the structure struct lconv has type char, and the value is CHAR_MAX, it means that the current locale has no value for that parameter.

·  General Numeric : Parameters for formatting numbers and currency amounts.
·  Currency Symbol : How to print the symbol that identifies an amount of money (e.g. `$').
·  Sign of Money Amount : How to print the (positive or negative) sign for a monetary amount, if one exists.

Time Basics 
Next:  Elapsed Time , Up:  Date and Time 




Time Basics

Discussing time in a technical manual can be difficult because the word "time" in English refers to lots of different things. In this manual, we use a rigorous terminology to avoid confusion, and the only thing we use the simple word "time" for is to talk about the abstract concept. 

A calendar time is a point in the time continuum, for example November 4, 1990 at 18:02.5 UTC. Sometimes this is called "absolute time". We don't speak of a "date", because that is inherent in a calendar time. An interval is a contiguous part of the time continuum between two calendar times, for example the hour between 9:00 and 10:00 on July 4, 1980. An elapsed time is the length of an interval, for example, 35 minutes. People sometimes sloppily use the word "interval" to refer to the elapsed time of some interval. An amount of time is a sum of elapsed times, which need not be of any specific intervals. For example, the amount of time it takes to read a book might be 9 hours, independently of when and in how many sittings it is read. 

A period is the elapsed time of an interval between two events, especially when they are part of a sequence of regularly repeating events. CPU time is like calendar time, except that it is based on the subset of the time continuum when a particular process is actively using a CPU. CPU time is, therefore, relative to a process. Processor time is an amount of time that a CPU is in use. In fact, it's a basic system resource, since there's a limit to how much can exist in any given interval (that limit is the elapsed time of the interval times the number of CPUs in the processor). People often call this CPU time, but we reserve the latter term in this manual for the definition above.

Time Functions Example 
Previous:  Time Zone Functions , Up:  Calendar Time 




Time Functions Example

Here is an example program showing the use of some of the calendar time functions.

     #include <time.h>
     #include <stdio.h>
     
     #define SIZE 256
     
     int
     main (void)
     {
       char buffer[SIZE];
       time_t curtime;
       struct tm *loctime;
     
       /* Get the current time. */
       curtime = time (NULL);
     
       /* Convert it to local time representation. */
       loctime = localtime (&curtime);
     
       /* Print out the date and time in the standard format. */
       fputs (asctime (loctime), stdout);
     
       /* Print it out in a nice format. */
       strftime (buffer, SIZE, "Today is %A, %B %d.\n", loctime);
       fputs (buffer, stdout);
       strftime (buffer, SIZE, "The time is %I:%M %p.\n", loctime);
       fputs (buffer, stdout);
     
       return 0;
     }

It produces output like this:

     Wed Jul 31 13:02:36 1991
     Today is Wednesday, July 31.
     The time is 01:02 PM.

Time Zone Functions 
Next:  Time Functions Example , Previous:  TZ Variable , Up:  Calendar Time 




Functions and Variables for Time Zones

-- Variable: char * tzname [2]

The array tzname contains two strings, which are the standard names of the pair of time zones (standard and Daylight Saving) that the user has selected. tzname[0] is the name of the standard time zone (for example, "EST"), and tzname[1] is the name for the time zone when Daylight Saving Time is in use (for example, "EDT"). These correspond to the std and dst strings (respectively) from the TZ environment variable. If Daylight Saving Time is never used, tzname[1] is the empty string. 

The tzname array is initialized from the TZ environment variable whenever tzset, ctime, strftime, mktime, or localtime is called. If multiple abbreviations have been used (e.g. "EWT" and "EDT" for U.S. Eastern War Time and Eastern Daylight Time), the array contains the most recent abbreviation. 

The tzname array is required for POSIX.1 compatibility, but in GNU programs it is better to use the tm_zone member of the broken-down time structure, since tm_zone reports the correct abbreviation even when it is not the latest one. 

Though the strings are declared as char * the user must refrain from modifying these strings. Modifying the strings will almost certainly lead to trouble.

-- Function: void tzset (void)

The tzset function initializes the tzname variable from the value of the TZ environment variable. It is not usually necessary for your program to call this function, because it is called automatically when you use the other time conversion functions that depend on the time zone.

-- Variable: long int timezone

This contains the difference between UTC and the latest local standard time, in seconds west of UTC. For example, in the U.S. Eastern time zone, the value is 5*60*60. 

-- Variable: int daylight

This variable has a nonzero value if Daylight Saving Time rules apply. A nonzero value does not necessarily mean that Daylight Saving Time is now in effect; it means only that Daylight Saving Time is sometimes in effect.

Trig Functions 
Next:  Inverse Trig Functions , Previous:  Mathematical Constants , Up:  Mathematics 




Trigonometric Functions

These are the familiar sin, cos, and tan functions. The arguments to all of these functions are in units of radians; recall that pi radians equals 180 degrees. 

The math library normally defines M_PI to a double approximation of pi. If strict ISO and/or POSIX compliance are requested this constant is not defined, but you can easily define it yourself:

     #define M_PI 3.14159265358979323846264338327

You can also compute the value of pi with the expression acos (-1.0).

-- Function: double sin (double x)

-- Function: float sinf (float x)

-- Function: long double sinl (long double x)

These functions return the sine of x, where x is given in radians. The return value is in the range -1 to 1.

-- Function: double cos (double x)

-- Function: float cosf (float x)

-- Function: long double cosl (long double x)

These functions return the cosine of x, where x is given in radians. The return value is in the range -1 to 1.

-- Function: double tan (double x)

-- Function: float tanf (float x)

-- Function: long double tanl (long double x)

These functions return the tangent of x, where x is given in radians. 

Mathematically, the tangent function has singularities at odd multiples of pi/2. If the argument x is too close to one of these singularities, tan will signal overflow.

In many applications where sin and cos are used, the sine and cosine of the same angle are needed at the same time. It is more efficient to compute them simultaneously, so the library provides a function to do that.

-- Function: void sincos (double x, double *sinx, double *cosx)

-- Function: void sincosf (float x, float *sinx, float *cosx)

-- Function: void sincosl (long double x, long double *sinx, long double *cosx)

These functions return the sine of x in *sinx and the cosine of x in *cos, where x is given in radians. Both values, *sinx and *cosx, are in the range of -1 to 1. 

This function is a GNU extension. Portable programs should be prepared to cope with its absence.

ISO C99 defines variants of the trig functions which work on complex numbers. The C library provides these functions, but they are only useful if your compiler supports the new complex types defined by the standard.

-- Function: complex double csin (complex double z)

-- Function: complex float csinf (complex float z)

-- Function: complex long double csinl (complex long double z)

These functions return the complex sine of z. The mathematical definition of the complex sine is 

sin (z) = 1/(2*i) * (exp (z*i) - exp (-z*i)).

-- Function: complex double ccos (complex double z)

-- Function: complex float ccosf (complex float z)

-- Function: complex long double ccosl (complex long double z)

These functions return the complex cosine of z. The mathematical definition of the complex cosine is 

cos (z) = 1/2 * (exp (z*i) + exp (-z*i))

-- Function: complex double ctan (complex double z)

-- Function: complex float ctanf (complex float z)

-- Function: complex long double ctanl (complex long double z)

These functions return the complex tangent of z. The mathematical definition of the complex tangent is 

tan (z) = -i * (exp (z*i) - exp (-z*i)) / (exp (z*i) + exp (-z*i)) 

The complex tangent has poles at pi/2 + 2n, where n is an integer. ctan may signal overflow if z is too close to a pole.

TZ Variable 
Next:  Time Zone Functions , Previous: Formatting Calendar Time, Up:  Calendar Time 




Specifying the Time Zone with TZ

In POSIX systems, a user can specify the time zone by means of the TZ environment variable. For information about how to set environment variables, see  Environment Variables . The functions for accessing the time zone are declared in time.h. You should not normally need to set TZ. If the system is configured properly, the default time zone will be correct. You might set TZ if you are using a computer over a network from a different time zone, and would like times reported to you in the time zone local to you, rather than what is local to the computer. 

In POSIX.1 systems the value of the TZ variable can be in one of three formats. With the C library, the most common format is the last one, which can specify a selection from a large database of time zone information for many regions of the world. The first two formats are used to describe the time zone information directly, which is both more cumbersome and less precise. But the POSIX.1 standard only specifies the details of the first two formats, so it is good to be familiar with them in case you come across a POSIX.1 system that doesn't support a time zone information database. 

The first format is used when there is no Daylight Saving Time (or summer time) in the local time zone:

     std offset

The std string specifies the name of the time zone. It must be three or more characters long and must not contain a leading colon, embedded digits, commas, nor plus and minus signs. There is no space character separating the time zone name from the offset, so these restrictions are necessary to parse the specification correctly. 

The offset specifies the time value you must add to the local time to get a Coordinated Universal Time value. It has syntax like [+|-]hh[:mm[:ss]]. This is positive if the local time zone is west of the Prime Meridian and negative if it is east. The hour must be between 0 and 23, and the minute and seconds between 0 and 59. 

For example, here is how we would specify Eastern Standard Time, but without any Daylight Saving Time alternative:

     EST+5

The second format is used when there is Daylight Saving Time:

     std offset dst [offset],start[/time],end[/time]

The initial std and offset specify the standard time zone, as described above. The dst string and offset specify the name and offset for the corresponding Daylight Saving Time zone; if the offset is omitted, it defaults to one hour ahead of standard time. 

The remainder of the specification describes when Daylight Saving Time is in effect. The start field is when Daylight Saving Time goes into effect and the end field is when the change is made back to standard time. The following formats are recognized for these fields:

Jn
This specifies the Julian day, with n between 1 and 365. February 29 is never counted, even in leap years. 
n
This specifies the Julian day, with n between 0 and 365. February 29 is counted in leap years. 
Mm.w.d
This specifies day d of week w of month m. The day d must be between 0 (Sunday) and 6. The week w must be between 1 and 5; week 1 is the first week in which day d occurs, and week 5 specifies the last d day in the month. The month m should be between 1 and 12.

The time fields specify when, in the local time currently in effect, the change to the other time occurs. If omitted, the default is 02:00:00. 

For example, here is how you would specify the Eastern time zone in the United States, including the appropriate Daylight Saving Time and its dates of applicability. The normal offset from UTC is 5 hours; since this is west of the prime meridian, the sign is positive. Summer time begins on the first Sunday in April at 2:00am, and ends on the last Sunday in October at 2:00am.

     EST+5EDT,M4.1.0/2,M10.5.0/2

The schedule of Daylight Saving Time in any particular jurisdiction has changed over the years. To be strictly correct, the conversion of dates and times in the past should be based on the schedule that was in effect then. However, this format has no facilities to let you specify how the schedule has changed from year to year. The most you can do is specify one particular schedule--usually the present day schedule--and this is used to convert any date, no matter when. 
Unconstrained Allocation 
Next:  Variable Size Automatic , Previous:  Memory Allocation and C , Up:  Memory Allocation 




Unconstrained Allocation

The most general dynamic allocation facility is malloc. It allows you to allocate blocks of memory of any size at any time, make them bigger or smaller at any time, and free the blocks individually at any time (or never).

·  Basic Allocation : Simple use of malloc.
·  Malloc Examples : Examples of malloc. xmalloc.
·  Freeing after Malloc : Use free to free a block you got with malloc.
·  Changing Block Size : Use realloc to make a block bigger or smaller.
·  Allocating Cleared Space : Use calloc to allocate a block and clear it.
Unreading Idea 
Next:  How Unread , Up:  Unreading 




What Unreading Means

Here is a pictorial explanation of unreading. Suppose you have a stream reading a file that contains just six characters, the letters `foobar'. Suppose you have read three characters so far. The situation looks like this:

     f  o  o  b  a  r
              ^

so the next input character will be `b'.

If instead of reading `b' you unread the letter `o', you get a situation like this:

     f  o  o  b  a  r
              |
           o--
           ^

so that the next input characters will be `o' and `b'.

If you unread `9' instead of `o', you get this situation:

     f  o  o  b  a  r
              |
           9--
           ^

so that the next input characters will be `9' and `b'.

Unreading
Next:  Line Input , Previous: Character Input, Up:  I/O on Streams 




Unreading

In parser programs it is often useful to examine the next character in the input stream without removing it from the stream. This is called "peeking ahead" at the input because your program gets a glimpse of the input it will read next. 

Using stream I/O, you can peek ahead at input by first reading it and then unreading it (also called pushing it back on the stream). Unreading a character makes it available to be input again from the stream, by the next call to fgetc or other input function on that stream.

·  Unreading Idea : An explanation of unreading with pictures.
·  How Unread : How to call ungetc to do unreading.

Using Wide Char Classes 
Next:  Wide Character Case Conversion , Previous:  Classification of Wide Characters , Up:  Character Handling 




Notes on using the wide character classes

The first note is probably not astonishing but still occasionally a cause of problems. The iswXXX functions can be implemented using macros and in fact, the C C library does this. They are still available as real functions but when the wctype.h header is included the macros will be used. This is the same as the char type versions of these functions. 

The second note covers something new. It can be best illustrated by a (real-world) example. The first piece of code is an excerpt from the original code. It is truncated a bit but the intention should be clear.

     int
     is_in_class (int c, const char *class)
     {
       if (strcmp (class, "alnum") == 0)
         return isalnum (c);
       if (strcmp (class, "alpha") == 0)
         return isalpha (c);
       if (strcmp (class, "cntrl") == 0)
         return iscntrl (c);
       ...
       return 0;
     }

Now, with the wctype and iswctype you can avoid the if cascades, but rewriting the code as follows is wrong:

     int
     is_in_class (int c, const char *class)
     {
       wctype_t desc = wctype (class);
       return desc ? iswctype ((wint_t) c, desc) : 0;
     }

The problem is that it is not guaranteed that the wide character representation of a single-byte character can be found using casting. In fact, usually this fails miserably. The correct solution to this problem is to write the code as follows:

     int
     is_in_class (int c, const char *class)
     {
       wctype_t desc = wctype (class);
       return desc ? iswctype (btowc (c), desc) : 0;
     }

See  Converting a Character , for more information on btowc. Note that this change probably does not improve the performance of the program a lot since the wctype function still has to make the string comparisons. It gets really interesting if the is_in_class function is called more than once for the same class name. In this case the variable desc could be computed once and reused for all the calls. Therefore the above form of the function is probably not the final one.

Variable Arguments Input 
Previous:  Formatted Input Functions , Up:  Formatted Input 




Variable Arguments Input Functions

The functions vscanf and friends are provided so that you can define your own variadic scanf-like functions that make use of the same internals as the built-in formatted output functions. These functions are analogous to the vprintf series of output functions. See  Variable Arguments Output , for important information on how to use them. 

Portability Note: The functions listed in this section were introduced in ISO C99.

-- Function: int vscanf (const char *template, va_list ap)

This function is similar to scanf, but instead of taking a variable number of arguments directly, it takes an argument list pointer ap of type va_list (see  Variadic Functions ).

-- Function: int vwscanf (const wchar_t *template, va_list ap)

This function is similar to wscanf, but instead of taking a variable number of arguments directly, it takes an argument list pointer ap of type va_list (see  Variadic Functions ).

-- Function: int vfscanf (FILE *stream, const char *template, va_list ap)

This is the equivalent of fscanf with the variable argument list specified directly as for vscanf.

-- Function: int vfwscanf (FILE *stream, const wchar_t *template, va_list ap)

This is the equivalent of fwscanf with the variable argument list specified directly as for vwscanf.

-- Function: int vsscanf (const char *s, const char *template, va_list ap)

This is the equivalent of sscanf with the variable argument list specified directly as for vscanf.

-- Function: int vswscanf (const wchar_t *s, const wchar_t *template, va_list ap)

This is the equivalent of swscanf with the variable argument list specified directly as for vwscanf.

Variable Arguments Output 
Previous:  Formatted Output Functions , Up:  Formatted Output 




Variable Arguments Output Functions

The functions vprintf and friends are provided so that you can define your own variadic printf-like functions that make use of the same internals as the built-in formatted output functions. 

The most natural way to define such functions would be to use a language construct to say, "Call printf and pass this template plus all of my arguments after the first five." But there is no way to do this in C, and it would be hard to provide a way, since at the C language level there is no way to tell how many arguments your function received. 

Since that method is impossible, we provide alternative functions, the vprintf series, which lets you pass a va_list to describe "all of my arguments after the first five." 

When it is sufficient to define a macro rather than a real function, C99 provides a way to do this much more easily with macros. For example:

     #define myprintf(a, b, c, d, e, rest...) \
                 printf (mytemplate , ## rest...)

But this is limited to macros, and does not apply to real functions at all. 

Before calling vprintf or the other functions listed in this section, you must call va_start (see  Variadic Functions ) to initialize a pointer to the variable arguments. Then you can call va_arg to fetch the arguments that you want to handle yourself. This advances the pointer past those arguments. 

Once your va_list pointer is pointing at the argument of your choice, you are ready to call vprintf. That argument and all subsequent arguments that were passed to your function are used by vprintf along with the template that you specified separately. 

In some other systems, the va_list pointer may become invalid after the call to vprintf, so you must not use va_arg after you call vprintf. Instead, you should call va_end to retire the pointer from service. However, you can safely call va_start on another pointer variable and begin fetching the arguments again through that pointer. Calling vprintf does not destroy the argument list of your function, merely the particular pointer that you passed to it. 

CC386 does not have such restrictions. You can safely continue to fetch arguments from a va_list pointer after passing it to vprintf, and va_end is a no-op. (Note, however, that subsequent va_arg calls will fetch the same arguments which vprintf previously used.) 

Prototypes for these functions are declared in stdio.h.

-- Function: int vprintf (const char *template, va_list ap)

This function is similar to printf except that, instead of taking a variable number of arguments directly, it takes an argument list pointer ap.

-- Function: int vwprintf (const wchar_t *template, va_list ap)

This function is similar to wprintf except that, instead of taking a variable number of arguments directly, it takes an argument list pointer ap.

-- Function: int vfprintf (FILE *stream, const char *template, va_list ap)

This is the equivalent of fprintf with the variable argument list specified directly as for vprintf.

-- Function: int vfwprintf (FILE *stream, const wchar_t *template, va_list ap)

This is the equivalent of fwprintf with the variable argument list specified directly as for vwprintf.

-- Function: int vsprintf (char *s, const char *template, va_list ap)

This is the equivalent of sprintf with the variable argument list specified directly as for vprintf.

-- Function: int vswprintf (wchar_t *s, size_t size, const wchar_t *template, va_list ap)

This is the equivalent of swprintf with the variable argument list specified directly as for vwprintf.

-- Function: int vsnprintf (char *s, size_t size, const char *template, va_list ap)

This is the equivalent of snprintf with the variable argument list specified directly as for vprintf.

-- Function: int vasprintf (char **ptr, const char *template, va_list ap)

The vasprintf function is the equivalent of asprintf with the variable argument list specified directly as for vprintf.

-- Function: int obstack_vprintf (struct obstack *obstack, const char *template, va_list ap)

The obstack_vprintf function is the equivalent of obstack_printf with the variable argument list specified directly as for vprintf.

Here's an example showing how you might use vfprintf. This is a function that prints error messages to the stream stderr, along with a prefix indicating the name of the program (see  Error Messages , for a description of program_invocation_short_name).

     #include <stdio.h>
     #include <stdarg.h>
     
     void
     eprintf (const char *template, ...)
     {
       va_list ap;
       extern char *program_invocation_short_name;
     
       fprintf (stderr, "%s: ", program_invocation_short_name);
       va_start (ap, template);
       vfprintf (stderr, template, ap);
       va_end (ap);
     }

You could call eprintf like this:

     eprintf ("file `%s' does not exist\n", filename);

Variable Size Automatic 
Previous: Unconstrained Allocation, Up:  Memory Allocation 




Automatic Storage with Variable Size

The function alloca supports a kind of half-dynamic allocation in which blocks are allocated dynamically but freed automatically. 

Allocating a block with alloca is an explicit action; you can allocate as many blocks as you wish, and compute the size at run time. But all the blocks are freed when you exit the function that alloca was called from, just as if they were automatic variables declared in that function. There is no way to free the space explicitly. 

The prototype for alloca is in stdlib.h. This function is a BSD extension.

-- Function: void * alloca (size_t size);

The return value of alloca is the address of a block of size bytes of memory, allocated in the stack frame of the calling function.

Do not use alloca inside the arguments of a function call--you will get unpredictable results, because the stack space for the alloca would appear on the stack in the middle of the space for the function arguments. An example of what to avoid is foo (x, alloca (4), y).

·  Alloca Example : Example of using alloca.
·  Advantages of Alloca : Reasons to use alloca.
·  Disadvantages of Alloca : Reasons to avoid alloca.
·  C99 Variable-Size Arrays : Only in C99, here is an alternative method of allocating dynamically and freeing automatically.

Variadic Example 
Previous:  How Variadic , Up:  Variadic Functions 




Example of a Variadic Function

Here is a complete sample function that accepts a variable number of arguments. The first argument to the function is the count of remaining arguments, which are added up and the result returned. While trivial, this function is sufficient to illustrate how to use the variable arguments facility.

     #include <stdarg.h>
     #include <stdio.h>
     
     int
     add_em_up (int count,...)
     {
       va_list ap;
       int i, sum;
     
       va_start (ap, count);         /* Initialize the argument list. */
     
       sum = 0;
       for (i = 0; i < count; i++)
         sum += va_arg (ap, int);    /* Get the next argument value. */
     
       va_end (ap);                  /* Clean up. */
       return sum;
     }
     
     int
     main (void)
     {
       /* This call prints 16. */
       printf ("%d\n", add_em_up (3, 5, 5, 6));
     
       /* This call prints 55. */
       printf ("%d\n", add_em_up (10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
     
       return 0;
     }

Variadic Functions 
Next:  Null Pointer Constant , Previous:  Consistency Checking , Up:  Language Features 




Variadic Functions

ISO C defines a syntax for declaring a function to take a variable number or type of arguments. (Such functions are referred to as varargs functions or variadic functions.) However, the language itself provides no mechanism for such functions to access their non-required arguments; instead, you use the variable arguments macros defined in stdarg.h. 

This section describes how to declare variadic functions, how to write them, and how to call them properly. 

Compatibility Note: Many older C dialects provide a similar, but incompatible, mechanism for defining functions with variable numbers of arguments, using varargs.h.

·  Why Variadic : Reasons for making functions take variable arguments.
·  How Variadic : How to define and call variadic functions.
·  Variadic Example : A complete example.

Variadic Prototypes 
Next:  Receiving Arguments , Up:  How Variadic 




Syntax for Variable Arguments

A function that accepts a variable number of arguments must be declared with a prototype that says so. You write the fixed arguments as usual, and then tack on `...' to indicate the possibility of additional arguments. The syntax of ISO C requires at least one fixed argument before the `...'. For example,

     int
     func (const char *a, int b, ...)
     {
       ...
     }

defines a function func which returns an int and takes two required arguments, a const char * and an int. These are followed by any number of anonymous arguments. 

Portability note: For some C compilers, the last required argument must not be declared register in the function definition. Furthermore, this argument's type must be self-promoting: that is, the default promotions must not change its type. This rules out array and function types, as well as float, char (whether signed or not) and short int (whether signed or not). This is actually an ISO C requirement.

+ Why Variadic 
Next:  How Variadic , Up:  Variadic Functions 




Why Variadic Functions are Used

Ordinary C functions take a fixed number of arguments. When you define a function, you specify the data type for each argument. Every call to the function should supply the expected number of arguments, with types that can be converted to the specified ones. Thus, if the function `foo' is declared with int foo (int, char *); then you must call it with two arguments, a number (any kind will do) and a string pointer. 

But some functions perform operations that can meaningfully accept an unlimited number of arguments. 

In some cases a function can handle any number of values by operating on all of them as a block. For example, consider a function that allocates a one-dimensional array with malloc to hold a specified set of values. This operation makes sense for any number of values, as long as the length of the array corresponds to that number. Without facilities for variable arguments, you would have to define a separate function for each possible array size. 

The library function printf (see  Formatted Output ) is an example of another class of function where variable arguments are useful. This function prints its arguments (which can vary in type as well as number) under the control of a format template string. 

These are good reasons to define a variadic function which can handle as many arguments as the caller chooses to pass. 

Some functions such as open take a fixed set of arguments, but occasionally ignore the last few. Strict adherence to ISO C requires these functions to be defined as variadic; in practice, however, this C compiler and most other C compilers let you define such a function to take a fixed set of arguments--the most it can ever use--and then only declare the function as variadic (or not declare its arguments at all!).

Wide Character Case Conversion 
Previous:  Using Wide Char Classes , Up:  Character Handling 




Mapping of wide characters.

The classification functions are also generalized by the ISO C standard. Instead of just allowing the two standard mappings, a locale can contain others. Again, the localedef program already supports generating such locale data files.

-- Data Type: wctrans_t

This data type is defined as a scalar type which can hold a value representing the locale-dependent character mapping. There is no way to construct such a value apart from using the return value of the wctrans function. 

This type is defined in wctype.h.

-- Function: wctrans_t wctrans (const char *property)

The wctrans function has to be used to find out whether a named mapping is defined in the current locale selected for the LC_CTYPE category. If the returned value is non-zero, you can use it afterwards in calls to towctrans. If the return value is zero no such mapping is known in the current locale. 

Beside locale-specific mappings there are two mappings which are guaranteed to be available in every locale: 

 
	"tolower" 	"toupper"	 

These functions are declared in wctype.h.

-- Function: wint_t towctrans (wint_t wc, wctrans_t desc)

towctrans maps the input character wc according to the rules of the mapping for which desc is a descriptor, and returns the value it finds. desc must be obtained by a successful call to wctrans. 

This function is declared in wctype.h.

For the generally available mappings, the ISO C standard defines convenient shortcuts so that it is not necessary to call wctrans for them.

-- Function: wint_t towlower (wint_t wc)

If wc is an upper-case letter, towlower returns the corresponding lower-case letter. If wc is not an upper-case letter, wc is returned unchanged. 

towlower can be implemented using 

          towctrans (wc, wctrans ("tolower"))
     
This function is declared in wctype.h.

-- Function: wint_t towupper (wint_t wc)

If wc is a lower-case letter, towupper returns the corresponding upper-case letter. Otherwise wc is returned unchanged. 

towupper can be implemented using 

          towctrans (wc, wctrans ("toupper"))
     
This function is declared in wctype.h.

The same warnings given in the last section for the use of the wide character classification functions apply here. It is not possible to simply cast a char type value to a wint_t and use it as an argument to towctrans calls.

Width of Type 
Next:  Range of Type , Up:  Data Type Measurements 




Computing the Width of an Integer Data Type

The most common reason that a program needs to know how many bits are in an integer type is for using an array of long int as a bit vector. You can access the bit at index n with

     vector[n / LONGBITS] & (1 << (n % LONGBITS))

provided you define LONGBITS as the number of bits in a long int. 

There is no operator in the C language that can give you the number of bits in an integer data type. But you can compute it from the macro CHAR_BIT, defined in the header file limits.h.

CHAR_BIT
This is the number of bits in a char--eight, on most systems. The value has type int. 

You can compute the number of bits in any data type type like this: 

          sizeof (type) * CHAR_BIT
     
Working Directory 
Next:  Deleting Files , Up:  File System Interface 




Working Directory

Each process has associated with it a directory, called its current working directory or simply working directory, that is used in the resolution of relative file names (see  File Name Resolution ). 

When you log in and begin a new session, your working directory is initially set to the home directory associated with your login account in the system user database. You can find any user's home directory using the getpwuid or getpwnam functions; see  User Database . 

Users can change the working directory using shell commands like cd. The functions described in this section are the primitives used by those commands and by other programs for examining and changing the working directory. Prototypes for these functions are declared in the header file unistd.h.

-- Function: char * getcwd (char *buffer, size_t size)

The getcwd function returns an absolute file name representing the current working directory, storing it in the character array buffer that you provide. The size argument is how you tell the system the allocation size of buffer. 

The return value is buffer on success and a null pointer on failure. The following errno error conditions are defined for this function:

EINVAL
The size argument is zero and buffer is not a null pointer. 
ERANGE
The size argument is less than the length of the working directory name. You need to allocate a bigger array and try again. 
EACCES
Permission to read or search a component of the file name was denied.

You could implement the behavior of GNU's getcwd (NULL, 0) using only the standard behavior of getcwd:

     char *
     gnu_getcwd ()
     {
       size_t size = 100;
     
       while (1)
         {
           char *buffer = (char *) xmalloc (size);
           if (getcwd (buffer, size) == buffer)
             return buffer;
           free (buffer);
           if (errno != ERANGE)
             return 0;
           size *= 2;
         }
     }

See  Malloc Examples , for information about xmalloc, which is not a library function but is a customary name used in most GNU software.

-- Function: int chdir (const char *filename)

This function is used to set the process's working directory to filename. 

The normal, successful return value from chdir is 0. A value of -1 is returned to indicate an error. The errno error conditions defined for this function are the usual file name syntax errors (see  File Name Errors ), plus ENOTDIR if the file filename is not a directory.
Yes-or-No Questions 
Previous:  Locale Information , Up:  Locales 




Yes-or-No Questions

Some non GUI programs ask a yes-or-no question. If the messages (especially the questions) are translated into foreign languages, be sure that you localize the answers too. It would be very bad habit to ask a question in one language and request the answer in another, often English. 

The C library contains rpmatch to give applications easy access to the corresponding locale definitions.
-- Function: int rpmatch (const char *response)

The function rpmatch checks the string in response whether or not it is a correct yes-or-no answer and if yes, which one. The check uses the YESEXPR and NOEXPR data in the LC_MESSAGES category of the currently selected locale. The return value is as follows:

1
The user entered an affirmative answer. 
0
The user entered a negative answer. 
-1
The answer matched neither the YESEXPR nor the NOEXPR regular expression.

This function is not standardized but available beside in GNU libc at least also in the IBM AIX library.

This function would normally be used like this:

       ...
       /* Use a safe default.  */
       _Bool doit = false;
     
       fputs (gettext ("Do you really want to do this? "), stdout);
       fflush (stdout);
       /* Prepare the getline call.  */
       line = NULL;
       len = 0;
       while (getline (&line, &len, stdout) >= 0)
         {
           /* Check the response.  */
           int res = rpmatch (line);
           if (res >= 0)
             {
               /* We got a definitive answer.  */
               if (res > 0)
                 doit = true;
               break;
             }
         }
       /* Free what getline allocated.  */
       free (line);

Note that the loop continues until an read error is detected or until a definitive (positive or negative) answer is read.