| CATEGORII DOCUMENTE | 
| Asp | Autocad | C | Dot net | Excel | Fox pro | Html | Java | 
| Linux | Mathcad | Photoshop | Php | Sql | Visual studio | Windows | Xml | 
  Libraries
  | 
 
  1. IntroductionThere is no doubt that the Standard Committee's decision to define a set of library routines will prove to be a huge benefit to users of C. Previously there were no standard, accepted, definitions of library routines to provide support for the language. As a result, portability suffered seriously. The library routines do not have to be present; they will only be present in a hosted environment-typically the case for applications programmers. Writers of embedded systems and the writers of the hosted environment libraries will not have the libraries present. They are using 'raw' C, in a freestanding environment, and this chapter will not be of much interest to them. The descriptions (except for this introduction) are not meant to be read as a whole chapter, but as individual pieces. The material included here is meant more for information and convenient reference than as a full tutorial introduction. It would take a full book by itself to do real justice to the libraries. 1.1. Headers and standard typesA number of types and macros are used widely by the library functions.
  Where necessary, they are defined in the appropriate  
 The Standard isn't quite as restrictive about identifiers as the list above is, but it's a brave move to make use of the loopholes. Play safe instead. The Standard headers are: <assert.h> <locale.h> <stddef.h><ctype.h> <math.h> <stdio.h> <errno.h> <setjmp.h> <stdlib.h> <float.h> <signal.h> <string.h> <limits.h> <stdarg.h> <time.h> A last general point is that many of the library routines may be
  implemented as macros, provided that there will be no problems to do with
  side-effects (as Chapter 7 describes). The Standard guarantees that, if
  a function is normally implemented as a macro, there will also be a
  true function provided to do the same job. To use the real function, either
  undefine the macro name with  (some function)('Can't be a macron'); 1.2. Character set and cultural dependenciesThe Committee has introduced features that attempt to cater for the use of C in environments which are not based on the character set of US ASCII and where there are cultural dependencies such as the use of comma or full stop to indicate the decimal point. Facilities have been provided (see Section 4) for setting a program's idea of its locale, which is used to control the behaviour of the library functions. Providing full support for different native languages and customs is a difficult and poorly understood task; the facilities provided by the C library are only a first step on the road to a full solution. In several places the 'C locale' is referred to. This is the only locale defined by the Standard and effectively provides support for the way that Old C worked. Other locale settings may provide different behaviour in implementation-defined ways. 1.3. The <stddef.h> HeaderThere are a small number of types and macros, found in  Subtracting one pointer from another gives a result whose type differs
  between different implementations. To allow safe use of the difference, the
  type is defined in  For reasons which still escape us, there is an 'implementation defined
  null pointer constant' defined in  #include <stddef.h> FILE *fp; if((fp = fopen('somefile', 'r')) != NULL)s_tr; distance = offsetof(s_tr, c); printf('Offset of x.c is %lu bytesn', (unsigned long)distance); exit(EXIT_SUCCESS); } Example 1 The expression  Note carefully the way that a  The last item declared in  1.4. The <errno.h> HeaderThis header defines errno along with the macros  
 #include <stddef.h> #include <errno.h> errno = 0; if(some_library_function(arguments) < 0) Example 2 Note that assert returns no value.  | 
 
  3. Character handlingThere are a variety of functions provided for testing and mapping
  characters. The testing functions, which are described first, allow you to
  test if a character is of a particular type, such as alphabetic, upper or
  lower case, numeric, a control character, a punctuation mark, printable or
  not and so on. The character testing functions return an integer, either zero
  if the character supplied is not of the category specified, or non-zero if it
  was. The functions all take an integer argument, which should either be an
  int, the value of which should be representable as  These functions depend on the program's locale setting. A printing character is a member of an implementation defined
  character set. Each printing character occupies one printing position. A control
  character is a member of an implementation defined character set, each
  of which is not a printing character. If the 7-bit ASCII character set is
  used, the printing characters are those that lie between space  The following is a summary of all the character testing functions. The
  header  
 True if  
 True if  Also true for an implementation-defined set of characters which do not return true results from any of iscntrl, isdigit, ispunct or isspace. In the C locale, this extra set of characters is empty. 
 True if  
 True if  
 True if  
 True if  
 True if  
 True if  
 True if  
 True if  Also true for an implementation-defined set of
  characters which do not return true results from any of  
 True if  Two additional functions map characters from one set into another. The
  function  If  The converse function  For each, the conversion is only performed if there is a corresponding character in the alternate case. In some locales, not all upper case characters have lower case equivalents, and vice versa.  | 
 
  4. LocalizationThis is where the program's idea of its current locale can be controlled.
  The header file  LC_COLLATE LC_CTYPE LC_MONETARY LC_NUMERIC LC_TIME all of which expand to integral constant expressions and are used as
  values of the  which is used for storing information about the
  formatting of numeric values. For members of type  
 
 The character used for the
  decimal point in formatted non-monetary values.  
 The character used for separating
  groups of digits to the left of the decimal point in formatted non-monetary
  values.  
 Defines the number of digits in
  each group when formatting non-monetary values. The elements are interpreted
  as follows: A value of  
 The first three characters are
  used to hold the alphabetic international currency symbol for the current locale, the fourth character is used to separate the
  international currency symbol from the monetary quantity.  
 The currency symbol for the
  current locale.  
 The character used as the decimal
  point when formatting monetary values.  
 The digit group separator for
  formatted monetary values.  
 Defines the number of digits in
  each group when formatting monetary values. Its elements are interpreted as
  those for grouping.  
 The string used to signify a
  non-negative monetary value.  
 The string used to signify a
  negative monetary value.  
 The number of digits to be
  displayed after the decimal point in an internationally formatted monetary
  value.  
 The number of digits to be
  displayed after the decimal point in a non-internationally formatted monetary
  value.  
 A value of  
 A value of 1 indicates that the currency symbol is separated by a space from the value when formatting a non-negative monetary quantity; 0 indicates no space. CHAR_MAX in the C locale. 
 As  
 As  
 Indicates the position of the   parentheses surround quantity and   the string precedes the quantity and   the string follows the quantity and   the string precedes the   the string follows the  
 
 As  4.1. The setlocale function#include <locale.h>char *setlocale(int category, const char *locale); This function allows the program's idea of its locale to be set. All or
  parts of the locale can be set by providing values for  
 Set entire locale. 
 Modify behaviour of  
 Modify behaviour of character-handling functions. 
 Modify monetary formatting information returned by localeconv. 
 Modify decimal-point character for formatted I/O and string conversion routines. 
 Modify behaviour of  The values for locale can be: 
 When the program starts, it has an environment as if setlocale(LC_ALL, 'C');has been executed. The current string associated with a
  given category can be queried by passing a null pointer as the value for  4.2. The localeconv function#include <locale.h>struct lconv *localeconv(void); The function returns a pointer to a
  structure of type  For example, if in the current locale monetary values should be represented as 
 then the monetary members of  
  | 
 
  5. LimitsTwo header files  5.1. Limits.hTable 1 gives the names declared, the allowable values, and a comment
  on what they mean. For example, the description of  
 Table 1.  5.2. Float.hFor floating point numbers, the file  
 Table 2.   | 
 ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  6. Mathematical functionsIf you are writing mathematical programs, involving floating point
  calculations and so on, then you will undoubtedly require access to the
  mathematics library. This set of functions all take  The macro  For all the functions, a domain error occurs if an input
  argument is outside the domain over which the function is defined. An example
  might be attempting to take the square root of a negative number. If this
  occurs,  If the result of the function cannot be represented as a double value then
  a range error occurs. If the magnitude of the result is too large,
  the functions return  The following list briefly describes each of the functions available: 
 Principal value of the arc cosine
  of x in
  the range 0-π radians. 
 Principal value of the arc sine
  of x in
  the range -π/2-+π/2 radians. 
 Principal value of the arc tangent of x in the range -π/2-+π/2 radians. 
 Principal value of the arc
  tangent of y/x
  in the range -π-+π radians, using the signs of both arguments to
  determine the quadrant of the return value. 
 Cosine of x (x measured in radians). 
 Sine of x (x measured in radians). 
 Tangent of x (x measured in
  radians). When a range error occurs, the sign of the resulting  
 Hyperbolic cosine of x  
 Hyperbolic sine of x  
 Hyperbolic tangent of  
 Exponential function of x. Errors:  
 Break a floating point number into a normalized fraction and an integral power of two. This integer is stored in the object pointed to by exp. 
 Multiply x by 2 to the
  power exp 
 Natural logarithm of x  
 Base-ten logarithm of x  
 Break the argument value into
  integral and fractional parts, each of which has the same sign as the
  argument. It stores the integrbal part as a  
 Compute x to the power y  
 Compute the square root of x  
 Smallest integer not less than x. 
 Absolute value of x. 
 Largest integer not greater than x. 
 Floating point remainder of x/y   | 
 
  7. Non-local jumpsProvision is made for you to perform what is, in effect, a  The file  int setjmp(jmp_buf env); void longjmp(jmp_buf env, int val); The  #include <stdlib.h> #include <setjmp.h> void func(void); jmp_buf place; main() /* * This call will never return - it * 'jumps' back above. */ func(); printf('What! func returned!n'); } void func(void) Example 3 The  If there has been no call to  The  It's a serious error to  The Standard insists that, apart from appearing as the only expression in
  an expression statement,  if(setjmp(place)) /* whole controlling expression */ if(!setjmp(place)) /* whole controlling expression */ if(setjmp(place) < 4) /* whole controlling expression */ if(setjmp(place)<;4 && 1!=2) /* forbidden */  | 
 
  8. Signal handlingTwo functions allow for asynchronous event handling to be provided. A signal
  is a condition that may be reported during program execution, and can be
  ignored, handled specially, or, as is the default, used to terminate the
  program. One function sends signals, another is used
  to determine how a signal will be processed. Many of the signals may be
  generated by the underlying hardware or operating system as well as by means
  of the signal-sending function  The signals are defined in the include file  
 Abnormal termination, such as
  instigated by the  
 Erroneous arithmetic operation, such as divide by 0 or overflow. (Floating point exception.) 
 An 'invalid object program' has been detected. This usually means that there is an illegal instruction in the program. (Illegal instruction.) 
 Interactive attention signal; on interactive systems this is usually generated by typing some 'break-in' key at the terminal. (Interrupt.) 
 Invalid storage access; most frequently caused by attempting to store some value in an object pointed to by a bad pointer. (Segment violation.) 
 Termination request made to the program. (Terminate.) Some implementations may have additional signals available, over and above
  this standard set. They will be given names that start  The function  void (*signal (int sig, void (*func)(int)))(int); That is to say,  Two special values may be used as the  If the call to  When a signal event happens which is not being ignored, if the associated
  func is a pointer to a function, first the equivalent of  Next, a call is made to the signal-handling function. If that function
  returns normally, then under most circumstances the program will resume at
  the point where the event occurred. However, if the value of  The following program fragment shows the use of signal to perform a tidy exit to a program on receipt of the interrupt or 'interactive attention' signal. #include <stdio.h>#include <stdlib.h> #include <signal.h> FILE *temp_file; void leave(int sig); main() /* can't get here */ exit(EXIT_SUCCESS); } /* * on receipt of SIGINT, close tmp file * but beware - calling library functions from a * signal handler is not guaranteed to work in all * implementations.. * this is not a strictly conforming program */ void leave(int sig) Example 4 It is possible for a program to send signals to itself by means of the  int raise (int sig); The signal sig is sent to the program. 
 void abort(void) If a signal occurs for any reason other than calling abort or raise, the
  signal-handling function may only call signal or assign a value to a volatile
  static object of type   | 
 
  Variable numbers of argumentsIt is often desirable to implement a function where the number of
  arguments is not known, or is not constant, when the function is written.
  Such a function is  int f(int, ) int g() Example 5 In order to access the arguments within the called function, the functions
  declared in the  Before any attempt can be made to access a variable argument list,  void vastart(valist ap, parmN); The  Once initialized, the arguments supplied can be accessed sequentially by means of the va arg macro. This is peculiar because the type returned is determined by an argument to the macro. Note that this is impossible to implement as a true function, only as a macro. It is defined as #include <stdarg.h>type va arg(va list ap, type); Each call to this macro will extract the next argument from the argument
  list as a value of the specified type. The  The behaviour is also undefined if  The type argument must be a type name which can be converted
  into a pointer to such an object simply by appending a  When all the arguments have been processed, the  The entire argument list can be re-traversed by calling  void va_end(va list ap); The following example shows the use of  #include <stdarg.h> #include <stdio.h> int maxof(int, ) ; void f(void); main() int maxof(int n args, ) va_end(ap); return max; } void f(void) Example 6  | 
 
  10. Input and output10.1. IntroductionOne of the reasons that has prevented many programming languages from becoming widely used for 'real programming' is their poor support for I/O, a subject which has never seemed to excite language designers. C has avoided this problem, oddly enough, by having no I/O at all! The C language approach has always been to do I/O using library functions, which ensures that system designers can provide tailored I/O instead of being forced to change the language itself. As C has evolved, a library package known as the 'Standard I/O Library' or stdio, has evolved with it and has proved to be both flexible and portable. This package has now become part of the Standard. The old stdio package relied heavily on the UNIX model of file access, in particular the assumption that there is no distinction between unstructured binary files and files containing readable text. Many operating systems do maintain a distinction between the two, and to ensure that C programs can be written portably to run on both types of file model, the stdio package has been modified. There are changes in this area which affect many existing programs, although strenuous efforts were taken to limit the amount of damage. Old C programs should still be able work unmodified in a UNIX environment. 10.2. The I/O modelThe I/O model does not distinguish between the types of physical devices supporting the I/O. Each source or sink of data (file) is treated in the same way, and is viewed as a stream of bytes. Since the smallest object that can be represented in C is the character, access to a file is permitted at any character boundary. Any number of characters can be read or written from a movable point, known as the file position indicator. The characters will be read, or written, in sequence from this point, and the position indicator moved accordingly. The position indicator is initially set to the beginning of a file when it is opened, but can also be moved by means of positioning requests. (Where random access is not possible, the file position indicator is ignored.) Opening a file in append mode has an implementation defined effect on the stream's file position indicator. The overall effect is to provide sequential reads or writes unless the stream was opened in append mode, or the file position indicator is explicitly moved. There are two types of file, text files and binary files, which, within a program, are manipulated as text streams and binary streams once they have been opened for I/O. The stdio package does not permit operations on the contents of files 'directly', but only by viewing them as streams. 10.2.1. Text streamsThe Standard specifies what is meant by the term text stream,
  which essentially considers a file to contain lines of text. A line is a
  sequence of zero or more characters terminated by a newline character. It is
  quite possible that the actual representation of lines in the external environment
  is different from this and there may be transformations of the data stream on
  the way in and out of the program; a common requirement is to translate the ' Data read in from a text stream is guaranteed to compare equal to the data that was earlier written out to the file if the data consists only of complete lines of printable characters and the control characters horizontal-tab and newline, no newline character is immediately preceded by space characters and the last character is a newline. It is guaranteed that, if the last character written to a text file is a newline, it will read back as the same. It is implementation defined whether the last line written to a text file must terminate with a newline character; this is because on some implementations text files and binary files are the same. Some implementations may strip the leading space from lines consisting only of a space followed by a newline, or strip trailing spaces at the end of a line! An implementation must support text files with lines containing at least 254 characters, including the terminating newline. Opening a text stream in update mode may result in a binary stream in some implementations. Writing on a text stream may cause some implementations to truncate the file at that point-any data beyond the last byte of the current write being discarded. 10.2.2. Binary streamsA binary stream is a sequence of characters that can be used to record a
  program's internal data, such as the contents of structures or arrays in
  binary form. Data read in from a binary stream will always compare equal to
  data written out earlier to the same stream, under the same implementation.
  In some circumstances, an implementation-defined number of  The contents of binary files are exceedingly machine specific, and not, in general, portable. 10.2.3. Other streamsOther stream types may exist, but are implementation defined. 10.3. The stdio.h header fileTo provide support for streams of the various kinds, a number of functions
  and macros exist. The  
 The type of an object used to contain stream control information. Users of stdio never need to know the contents of these objects, but simply manipulate pointers to them. It is not safe to copy these objects within the program; sometimes their addresses may be 'magic'. 
 A type of object that can be used to record unique values of a stream's file position indicator. 
 Values used to control the
  buffering of a stream in conjunction with the  
 The size of the buffer used by
  the  
 A negative integral constant expression, indicating the end-of-file condition on a stream i.e. that there is no more input. 
 The maximum length which a filename can have, if there is a limit, or otherwise the recommended size of an array intended to hold a file name. 
 The minimum number of files that the implementation guarantees may be held open concurrently; at least eight are guaranteed. Note that three predefined streams exist and may need to be closed if a program needs to open more than five files explicitly. 
 The maximum length of the string
  generated by  
 Integral constant expressions
  used to control the actions of  
 The minimum number of unique
  filenames generated by  
 Predefined objects of type ( 10.4. Opening, closing and buffering of streams10.4.1. OpeningA stream is connected to a file by means of the  Three streams are available without any special action; they are normally
  all connected to the physical device associated with the executing program:
  usually your terminal. They are referred to by the names  As mentioned earlier, the file position indicator may or may not be movable, depending on the underlying device. It is not possible, for example, to move the file position indicator on stdin if that is connected to a terminal, as it usually is. All non-temporary files must have a filename, which is a string. The rules for what constitutes valid filenames are implementation defined. Whether a file can be simultaneously open multiple times is also implementation defined. Opening a new file may involve creating the file. Creating an existing file causes its previous contents to be discarded. 10.4.2. ClosingFiles are closed by explicitly calling  10.4.3. BufferingThere are three types of buffering: Unbuffered Minimum internal storage is used by stdio in an attempt to send or receive data as soon as possible. Line buffered Characters are processed on a line-by-line basis. This is commonly used in interactive environments, and internal buffers are flushed only when full or when a newline is processed. Fully buffered Internal buffers are only flushed when full. The buffering associated with a stream can always be flushed by using  10.5. Direct file manipulationA number of functions exist to operate on files directly. #include <stdio.h>int remove(const char *filename); int rename(const char *old, const char *new); char *tmpnam(char *s); FILE *tmpfile(void); 
 Causes a file to be removed.
  Subsequent attempts to open the file will fail, unless it is first created
  again. If the file is already open, the operation of  
 Changes the name of the file identified by  If a file with the new name exists prior to
  calling  If  
 Generates a string that may be used as a filename
  and is guaranteed to be different from any existing filename. It may be
  called repeatedly, each time generating a new name. The constant  If the argument s is set to  
 Creates a temporary binary file,
  opened for update, and returns a pointer to the stream of that file. The file
  will be removed when the stream is closed. If no file could be opened,  10.6. Opening named filesNamed files are opened by a call to the  FILE *fopen(const char *pathname, const char *mode); The  Files can be opened in a variety of modes, such as read mode for reading data, write mode for writing data, and so on. Note that if you only want to write data to a file,  The Standard list of modes is shown in Table 3, although implementations may permit extra modes by appending extra characters at the end of the modes. 
 Table 3. File opening modes Beware that some implementations of binary files may pad the last record
  with  If a file is opened in append mode, all writes will occur at the
  end of the file, regardless of attempts to move the file position indicator
  with  Attempts to open a file in read mode, indicated by an ' Files opened for update (' It may also be possible in some implementations to omit the  Streams opened by fopen are fully buffered only if they are not connected to an interactive device; this ensures that prompts and responses are handled properly. If  10.7. FreopenThe  FILE *freopen(const char *pathname, const char *mode, FILE *stream); The  10.8. Closing filesAn open file is closed using  int fclose(FILE *stream); Any unwritten data buffered for  Zero is returned on success,  10. Setbuf, setvbufThese two functions are used to change the buffering strategy for an open stream: #include <stdio.h>int setvbuf(FILE *stream, char *buf, int type, size_t size); void setbuf(FILE *stream, char *buf); They must be used before the file is either read from or written
  to. The  
 Table 4. Type of buffering The  A call of  No value is returned by  10.10. Fflush#include <stdio.h>int fflush(FILE *stream); If  The most recent operation on the stream must have been an output operation; if not, the behaviour is undefined. A call of  
  | 
 
  11. Formatted I/OThere are a number of related functions used for formatted I/O, each one determining the format of the I/O from a format string. For output, the format string consists of plain text, which is output unchanged, and embedded format specifications which call for some special processing of one of the remaining arguments to the function. On input, the plain text must match what is seen in the input stream; the format specifications again specify what the meaning of remaining arguments is. Each format specification is introduced by a  11.1. Output: the printf familyFor those functions performing output, the format specification takes the following form, with optional parts enclosed in brackets: %<flags><field width><precision><length>conversionThe meaning of flags, field width, precision, length, and conversion are given below, although tersely. For more detail, it is worth looking at what the Standard says. flags Zero or more of the following: Left justify the conversion within its field. A signed conversion will always start with a plus or minus sign. space If the first character of a
  signed conversion is not a sign, insert a space. Overridden by  Forces an alternative form of
  output. The first digit of an octal conversion will always be a  Pad  field width A decimal integer specifying the
  minimum output field width. This will be exceeded if necessary. If an
  asterisk is used here, the next argument is converted to an integer and used
  for the value of the field width; if the value is negative it is treated as a
   precision This starts with a period ' length 
 conversion See Table 5. 
 Table 5. Conversions The functions that use these formats are described in Table 6. All
  need the inclusion of  int fprintf(FILE *stream, const char *format, ); int printf(const char *format, ); int sprintf(char *s, const char *format, ); #include <stdarg.h> /* as well as stdio.h */ int vfprintf(FILE *stream, const char *format, va list arg); int vprintf(const char *format, va list arg); int vsprintf(char *s, const char *format, va list arg); 
 Table 6. Functions performing formatted output All of the above functions return the number of characters output, or a
  negative value on error. The trailing null is not counted by  Implementations must permit at least 509 characters to be produced by any single conversion. 11.2. Input: the scanf familyA number of functions exist analogous to the  The format string is used to control interpretation of a stream of input
  data, which generally contains values to be assigned to the objects pointed
  to by the remaining arguments to  white space This causes the input stream to be read up to the next non-white-space character. ordinary character Anything except white-space or  conversion specification This is a  Except for the specifiers  The result is put into wherever the corresponding argument points, unless
  the assignment is suppressed using the  
 Convert a signed integer, a
  signed integer in a form acceptable to  
 Convert a  
 Read a string, and add a null at the end. The string is terminated by whitespace on input (which is not read as part of the string). Read a string. A list of
  characters, called the scan set follows the  
 Read a single character; white
  space is significant here. To read the first non-white space character, use  
 Read a ( A  
 Return as an integer the number of characters read by this call so far. The size specifiers have the effect shown in Table 7. 
 Table 7. Size specifiers The functions are described below, with the following declarations: #include <stdio.h>int fscanf(FILE *stream, const char *format, ); int sscanf(const char *s, const char *format, ); int scanf(const char *format, ); 
 If an input failure occurs before any conversion, EOF is returned. Otherwise, the number of successful conversions is returned: this may be zero if no conversions are performed. An input failure is caused by reading   | 
 
  12. Character I/OA number of functions provide for character oriented I/O. Their declarations are: #include <stdio.h>/* character input */ int fgetc(FILE *stream); int getc(FILE *stream); int getchar(void); int ungetc(int c, FILE *stream); /* character output */ int fputc(int c, FILE *stream); int putc(int c, FILE *stream); int putchar(int c); /* string input */ char *fgets(char *s, int n, FILE *stream); char *gets(char *s); /* string output */ int fputs(const char *s, FILE *stream); int puts(const char *s); Their descriptions are as follows. 12.1. Character inputThese read an  There is also the supporting  12.2. Character outputThese are identical in description to the input functions already
  described, except performing output. They return the character written, or  12.3. String outputThese write strings to the output file;  12.4. String input
 Gets works similarly for the stream stdin, but discards the newline! Both return s if successful, or a null pointer otherwise. In each case, if EOF is encountered before any characters have been read, the array is unchanged and a null pointer is returned. A read error in the middle of a string leaves the array contents undefined and a null pointer is returned.  | 
 
  13. Unformatted I/OThis is simple: only two functions provide this facility, one for reading and one for writing: #include <stdio.h>size_t fread(void *ptr, size_t size, size_t nelem, FILE *stream); size_t fwrite(const void *ptr, size_t size, size_t nelem, FILE *stream); In each case, the appropriate read or write is performed on the data
  pointed to by  If  An example may help. #include <stdio.h>#include <stdlib.h> struct xxar[20]; main() rewind(fp); if(fread((void *)&ar[10], sizeof(ar[0]), 5, fp) != 5) if(feof(fp)) } exit(EXIT_SUCCESS); } Example 7  | 
 
  14. Random access functionsThe file I/O routines all work in the same way; unless the user takes
  explicit steps to change the file position indicator, files will be read and
  written sequentially. A read followed by a write followed by a read (if the
  file was opened in a mode to permit that) will cause the second read to start
  immediately following the end of the data just written. (Remember that  Three types of function exist which allow the file position indicator to be examined or changed. Their declarations and descriptions follow. #include <stdio.h>/* return file position indicator */ long ftell(FILE *stream); int fgetpos(FILE *stream, fpos_t *pos); /* set file position indicator to zero */ void rewind(FILE *stream); /* set file position indicator */ int fseek(FILE *stream, long offset, int ptrname); int fsetpos(FILE *stream, const fpos_t *pos); 
 
 
 
 Note that for  
 
 For both functions, on success, zero is returned; on failure, non-zero is returned and errno is set. 14.1. Error handlingThe standard I/O functions maintain two indicators with each open stream to show the end-of-file and error status of the stream. These can be interrogated and set by the following functions: #include <stdio.h>void clearerr(FILE *stream); int feof(FILE *stream); int ferror(FILE *stream); void perror(const char *s); 
 
 
 
 #include <stdlib.h> main() perror('fgetc'); exit(EXIT_SUCCESS); } /* Result */ fgetc: Bad file number Example 8 Well, we didn't say that the message had to be very meaningful!  | 
 
  15. General UtilitiesThese all involve the use of the header  
 Described at the start of this chapter. 
 This is the type of the structure
  returned by  
 This is the type of the structure
  returned by  
 Again, described at the start of this chapter. 
 
 These may be used as arguments to
   
 The maximum number of bytes in a multibyte character from the extended character set specified by the current locale. 
 This is the maximum value returned
  by the  15.1. String conversion functionsThree functions take a string as an argument and convert it to a number of the type shown below: #include <stdlib.h>double atof(const char *nptr); long atol(const char *nptr); int atoi(const char *nptr); For each of the functions, the number is converted and the result
  returned. None of them guarantees to set  More sophisticated functions are: #include <stdlib.h>double strtod(const char *nptr, char **endptr); long strtol(const char *nptr, char **endptr, int base); unsigned long strtoul(const char *nptr,char **endptr, int base); All three functions work in a similar way. Leading white space is skipped,
  then a  
 Optional  
 Optional  
 Identical to  If  If a conversion can be performed, the functions convert the number and return its value, taking into account a leading sign where permitted. Otherwise they return zero. On overflow or error the action is as follows: 
 On overflow, returns  
 On overflow,  
 On overflow,  If the locale is not the 'C' locale, there may be other subject sequences recognised depending on the implementation. 15.2. Random number generationProvision for pseudo-random number generation is made by the following functions. #include <stdlib.h>int rand(void); void srand(unsigned int seed); 
 
 The Standard describes an algorithm which may be used to implement  15.3. Memory allocationThese functions are used to allocate and free storage. The storage so obtained is only guaranteed to be large enough to store an object of the specified type and aligned appropriately so as not to cause addressing exceptions. No further assumptions can be made. #include <stdlib.h>void *malloc(size_t size); void *calloc(size_t nmemb, size_t size); void *realloc(void *ptr, size_t size); void *free(void *ptr); All of the memory allocation functions return a pointer to allocated
  storage of size  
 
 If an attempt is made to free store which was never allocated, or has already been freed, the behaviour is undefined. In many environments this causes an addressing exception which aborts the program, but this is not a reliable indicator. 15.4. Communication with the environmentA miscellany of functions is found here. #include <stdlib.h>void abort(void); int atexit(void (*func)(void)); void exit(int status); char *getenv(const char *name); int system(const char *string); 
 Causes abnormal program
  termination to occur, by raising the  
 The argument  
 Normal program termination occurs
  when this is called. First, all of the functions registered using  
 The implementation-defined environment list is searched to find an item which corresponds to the string pointed to by name. A pointer to the item is returned-it points to an array which must not be modified by the program, but may be overwritten by a subsequent call to getenv. A null pointer is returned if no item matches. The purpose and implementation of the environment list depends on the host environment. 
 An implementation-defined command processor is passed the string string. A null pointer will cause a return of zero if no command processor exists, non-zero otherwise. A non-null pointer causes the command to be processed. The effect of the command and the value returned are implementation defined. 15.5. Searching and sortingTwo functions exist in this category: one for searching an already sorted list, the other for sorting an unsorted list. They are completely general, handling arrays of arbitrary size with elements of arbitrary size. To enable them to compare two elements, the user provides a comparison function, which is called with pointers to two of the elements as its arguments. It returns a value less than, equal to or greater than zero depending on whether the first pointer points to an element considered to be less than, equal to or greater than the object pointed to by the second pointer, respectively. #include <stdlib.h>void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); void *qsort(const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); For both functions,  
 
 15.6. Integer arithmetic functionsThese provide ways of finding the absolute value of an integral argument
  and the quotient and remainder of a division, for both  int abs(int j); long labs(long j); div_t div(int numerator, int denominator); ldiv_t ldiv(long numerator, long denominator); 
 
 These return the absolute value of their argument-choose the appropriate one for your needs. The behaviour is undefined if the value cannot be represented-this can happen in two's complement systems where the most negative number has no positive equivalent. 
 
 These divide the  15.7. Functions using multibyte charactersThe  The functions are: #include <stdlib.h>int mblen(const char *s, size_t n); int mbtowc(wchar_t *pwc, const char *s, size_t n); int wctomb(char *s, wchar_t wchar); size_t mbstowcs(wchar_t *pwcs, const char *s, size_t n); size_t wcstombs(char *s, const wchar_t *pwcs, size_t n); 
 Returns the number of bytes that
  are contained in the multibyte character pointed to by  
 Converts the multibyte character
  pointed to by s to the corresponding code of type  
 Converts the code whose value is
  in  
 Converts the sequence of multibyte characters,
  beginning in the initial shift state, in the array pointed to by  If the two objects overlap, the behaviour is undefined. 
 Converts the sequence of codes pointed to by  If the two objects overlap, the behaviour is undefined.  | 
 
  16. String handlingNumerous functions exist to handle strings. In C, a string is an array of
  characters terminated by a null. In all cases, the functions expect a pointer
  to the first character in the string. The header  16.1. CopyingThe functions for this purpose are: #include <string.h>void *memcpy(void *s1, const void *s2, size_t n); void *memmove (void *s1, const void *s2, size_t n); char *strcpy(char *s1, const char *s2); char *strncpy(char *s1, const char *s2, size_t n); char *strcat(char *s1, const char *s2); char *strncat(char *s1, const char *s2, size_t n); 
 This copies  
 Identical to  
 
 Both of these copy the string
  pointed to by  
 
 Both append the string in  16.2. String and byte comparisonThese comparison functions are used to compare arrays of bytes. This
  obviously includes the traditional C strings, which are an array of  For all except  int memcmp(const void *s1, const void *s2, size_t n); int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); size_t strxfrm(char *to, const char *from, int strcoll(const char *s1, const char *s2); 
 Compares the first  
 Compares the two strings. This is one of the most commonly used of the string-handling functions. 
 As for  
 The string in from is converted (by some magic),
  and placed wherever to points. At most  In all cases, the length of the resulting string
  (not counting its terminating null) is returned. If the value is equal to or
  greater than maxsize, the contents of *to is undefined. If  If the two objects overlap, the behaviour is undefined. 
 This function compares the two strings according to the collating sequence specified by the current locale. 16.3. Character and string searching functions#include <string.h>void *memchr(const void *s, int c, size_t n); char *strchr(const char *s, int c); size_t strcspn(const char *s1, const char *s2); char *strpbrk(const char *s1, const char *s2); char *strrchr(const char *s, int c); size_t strspn(const char *s1, const char *s2); char *strstr(const char *s1, const char *s2); char *strtok(const char *s1, const char *s2); 
 Returns a pointer to the first
  occurrence in the initial  
 Returns a pointer to the first
  occurrence of  
 Returns the length of the initial
  part of the string  
 Returns a pointer to the first
  character in  
 Returns a pointer to the last
  occurrence in  
 Returns the length of the initial
  part of  
 Returns a pointer to the first
  occurrence in  
 Breaks the string in  16.4. Miscellaneous functions#include <string.h>void *memset(void *s, int c, size_t n); char *strerror(int errnum); size_t strlen(const char *s); 
 Sets the  
 Returns the length of the string  
 Returns a pointer to a string
  describing the error number   | 
 
  17. Date and timeThese functions deal with either 'elapsed' or 'calendar' time. They share
  the  
 This is the number of 'ticks' per
  second returned by the  
 
 These are arithmetic types used to represent different forms of time. 
 This structure is used to hold the values representing a calendar time. It contains the following members, with the meanings as shown. int tm_sec /* seconds after minute [0-61] (61 allows for 2 leap-seconds)*/int tm_min /* minutes after hour [0-59] */ int tm_hour /* hours after int tm_mday /* day of the month [1-31] */ int tm_mon /* month of year [0-11] */ int tm_year /* current year-1900 */ int tm_wday /* days since Sunday [0-6] */ int tm_yday /* days since January 1st [0-365] */ int tm_isdst /* daylight savings indicator */ The  The time manipulation functions are the following: #include <time.h>clock_t clock(void); double difftime(time_t time1, time_t time2); time_t mktime(struct tm *timeptr); time_t time(time_t *timer); char *asctime(const struct tm *timeptr); char *ctime(const time_t *timer); struct tm *gmtime(const time_t *timer); struct tm *localtime(const time_t *timer); size_t strftime(char *s, size_t maxsize, const char *format, const struct tm *timeptr); The functions  
 Returns the best available
  approximation to the time used by the current invocation of the program, in
  'ticks'.  
 This returns the difference in seconds between two calendar times. 
 This returns the calendar time corresponding to
  the values in a structure pointed to by  The  
 Returns the best approximation to
  the current calendar time in an unspecified encoding.  
 Converts the time in the structure pointed to by  the example being taken from the Standard. The Standard defines the algorithm used, but the important point to notice is that all the fields within that string are of constant width and relevant to most English-speaking communities. The string is stored in a static structure which may be overwritten by a subsequent call to one of the other time-manipulation functions (see above). 
 Equivalent to  
 Returns a pointer to a  
 Converts the time pointed to by  
 Fills the character array pointed to by  
 The total number of characters copied into   | 
 
  18. SummaryIt will almost certainly be the standardization of the run-time library that has the most effect on the portability of C programs. Prospective users of C really should read through this chapter carefully and familiarize themselves with its contents. The lack of a widely implemented, portable library was historically the biggest single barrier to portability. If you are writing programs for embedded systems, bad luck! The library is not defined for stand-alone applications, but in practice we can expect suppliers to produce a stand-alone library package too. It will probably come without the file handling, but there is no reason why, say, the string-handling functions should not work just as well in hosted and unhosted environments.  | 
 
| 
Politica de confidentialitate | Termeni si conditii de utilizare | 
              
                Vizualizari: 1079				
                Importanta: ![]()
Termeni si conditii de utilizare | Contact 
     
      © SCRIGROUP 2025 . All rights reserved