411 REFERENCE · Wikibooks
A Little C Primer/C Standard Utility Library & Time Library
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
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
C Programming/Standard libraries
C Programming/C Reference
C++ Programming/Code/Standard C Library