C Standard Utility Library & Time Library

A Little C Primer · Wikibooks

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    Read aloud

    How

    Speed: 1×
    Light up
    Highlight

    Symbols: Mulberry Symbols, © 2018–2026 Steve Lee, CC BY-SA 4.0 (licence, the set), the site's own copies.

    From Wikibooks, under CC BY-SA 4.0, as the source states it. This page at Wikibooks.

    C Standard Utility Library & Time Library

    The utility functions library features a grab-bag of functions. It requires the declaration:

       #include <stdlib.h>
    
    

    Useful functions include:

       atof( <string> )     Convert numeric string to double value.
       atoi( <string> )     Convert numeric string to int value.
       atol( <string> )     Convert numeric string to long value.
       rand()               Generates pseudorandom integer.
       srand( <seed> )      Seed random-number generator -- "seed" is an "int".
       exit( <status> )     Exits program -- "status" is an "int".
       system( <string> )   Tells system to execute program given by "string".
       abs( n )             Absolute value of "int" argument.
       labs( n )            Absolute value of long-int argument.
    
    

    The functions "atof()", "atoi()", and "atol()" will return 0 if they can't convert the string given them into a value.

    The time and date library includes a wide variety of functions, some of them obscure and nonstandard. This library requires the declaration:

       #include <time.h>
    

    The most essential function is "time()", which returns the number of seconds since midnight proleptic Coordinated Universal Time (UTC) of January 1, 1970, not counting leap seconds. It returns a value as "time_t" (a "long") as defined in the header file.

    The following function uses "time()" to implement a program delay with resolution in seconds:

       /* delay.c */
    
       #include <stdio.h>
    
       #include <time.h>
    
       void sleep( time_t delay );
    
       void main()
       {
         puts( "Delaying for 3 seconds." );
         sleep( 3 );
         puts( "Done!" );
       }
    
       void sleep( time_t delay )
       {
         time_t t0, t1;
         time( &t0 );
         do
         {
           time( &t1 );
         }
         while (( t1 - t0 ) < delay );
       }
    
    

    The "ctime()" function converts the time value returned by "time()" into a time-and-date string. The following little program prints the current time and date:

       /* time.c */
    
       #include <stdio.h>
       #include <time.h>
    
       void main()
       {
         time_t *t;
         time( t );
         puts( ctime( t ) );
       }
    

    This program prints a string of the form:

       Tue Dec 27 15:18:16 1994
    

    Further reading