Cover V04, I01
Article
Figure 1
Listing 1
Listing 2
Listing 3

jan95.tar


Listing 2: cvttime.c

/*
** Thomas Richter
**
** cvttime [-f Format] [epoch]
**
** If invoked without any parameters, print the current time in seconds since
** 1.Jan 1970 (epoch). If the epoch parameter is specified, it is assumed
** to be seconds since epoch and is converted into human readable date and
** time. The option -f specifies the format of the date/time printout and the
** format string is the same as for the function strftime(3).
** The default format string is '%c%n'.
** Examples:
** cvttime  --> 779048101
** cvttime 360     --> Thu Jan  1 00:06:00 1970
** cvttime -f'%H:%M %d-%b-%y' 3666      --> 01:01 01-Jan-70
*/

#include <sys/types.h>
#include <sys/errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define OPTION  "f:"

char    *Prog;   /* Program's name on invocation */
int     main(int argc, char ** argv)
{
extern char     *optarg;
extern int      optind;
extern int      opterr;
extern int      errno;

int      ch;
char     *format = NULL,
buf[128];
time_t   epoch = time(NULL);     /* Default is current since epoch */
struct tm*tmptr;

opterr = 0;
Prog = strrchr(*argv, '/') ? strrchr(*argv, '/')+1 : *argv;
while( (ch = getopt(argc, argv, OPTION)) != EOF )
switch( ch ){
case 'f':   format = optarg;
break;
default:
fprintf(stderr, "usage:%s [-f format] [epoch]\n", Prog);
exit(1);
}
if( argv[optind] ){
char *endptr;
errno = 0;
/*
** Check if number is not too big for us to handle
*/
epoch = strtol(argv[optind], &endptr, 10);
if( errno == ERANGE ){
fprintf(stderr, "%s:parameter %s out of range\n", Prog,
argv[optind]);
exit(2);
}
/*
** If parameter epoch doesn't start with a digit or doesn't
** entirely consist of digits print an error and give up.
*/
if( strlen(argv[optind]) == 0
|| strlen(argv[optind]) != strspn(argv[optind], "0123456789") ){
fprintf(stderr, "%s:parameter '%s' invalid\n", Prog,
argv[optind]);
exit(3);
}
/*
** Default format is output of the date command
*/
if( format == NULL )
format = "%c%n";
}else
if( format == NULL ){
/* Just print current time in seconds since epoch */
printf("%ld\n", epoch);
return 0;
}

/* Convert time to human readable format */
tmptr = localtime(&epoch);
strftime(buf, sizeof buf, format, tmptr);
printf("%s", buf);
return 0;
}
/* End of File */