[comp.unix.programmer] How to get the time of the day in C?

hui@shiva.trl.oz (Alvaro Hui) (01/11/91)

Hi all experts:

 I am writing a small program to generate random numbers in C and
an idea came up in my mind: it is a good idea to use the time of the
day as seed to my random generator!

 Unfortunately, I "man -k time" and search through all my 'C' books
and couldn't came up an idea how to get current time in C.

 Can some of you folks help me?

 Thanks in advance!

Alvaro,

a.hui@trl.oz.au.

===============================================================================
	Alvaro Hui		|ACSnet,	hui@rhea.trl.oz.au
    4th Year B.E.\ B.Sc.	|Internet &	akkh@mullian.ee.mu.OZ.AU
   University of Melbourne	|Arpanet	rcoahk@koel.co.rmit.OZ.AU 

mike@bria.UUCP (Michael Stefanik) (01/12/91)

In article <2584@trlluna.trl.oz> shiva.trl.oz!hui (Alvaro Hui) writes:
>Hi all experts:
>
> I am writing a small program to generate random numbers in C and
>an idea came up in my mind: it is a good idea to use the time of the
>day as seed to my random generator!
>
> Unfortunately, I "man -k time" and search through all my 'C' books
>and couldn't came up an idea how to get current time in C.
>
> Can some of you folks help me?
>

Try ...
	#include <time.h>

	long	now;	/* number of seconds since the Epoch */

		time(&now);
		printf("%s",ctime(&now));	/* time string */

'now' will contain the number of seconds since 00:00 GMT on 1 Jan 1970
(aka "the Epoch"); the ctime() function was thrown in for giggles.
If a long is too high, then you could use:

	long now;
	int today;
	struct tm *t;	/* localtime structure defined in time.h */

		time(&now);
		t = localtime(&now);
		today = t->tm_sec + (t->tm_min * 60) + (t->tm_hour * 3600);

where 'today' is the number of seconds elapsed since midnight.
Hope that helps ...
-- 
Michael Stefanik, Systems Engineer (JOAT), Briareus Corporation
UUCP: ...!uunet!bria!mike
--
technoignorami (tek'no-ig'no-ram`i) a group of individuals that are constantly
found to be saying things like "Well, it works on my DOS machine ..."

silver@xrtll.uucp (Hi Ho Silver) (01/13/91)

In comp.unix.programmer, hui@shiva.trl.oz (Alvaro Hui) typed:
$ Unfortunately, I "man -k time" and search through all my 'C' books
$and couldn't came up an idea how to get current time in C.

   Look through sys/time.h for a line similar to

time_t time (time_t *timer);

   It returns the calendary time; also look for the definition of time_t.
-- 
 __            __  _  | ...!nexus.yorku.edu!xrtll!silver |  always
(__  | | |  | |_  |_) >----------------------------------< searching
 __) | |_ \/  |__ | \ | if you don't like my posts, type |    for
_____________________/  find / -print|xargs cat|compress |   SNTF