Linux C

#include
#include
#include
#include
#include
/* strptime() */
#define __USE_XOPEN
#include
#define PACKAGE "utconv"
#define VERSION "0.0.1"
void print_help(int exval); /* status epilepticus, print help */
int get_utc(char *str); /* extract UTC time from string */
char *convert_utc(int uval); /* convert UTC to time string */
int main(int argc, char *argv[]) {
int opt = 0;
if(argc == 1)
print_help(0);
while((opt = getopt(argc, argv, "hvu:s:")) != -1) {
switch(opt) {
case 'h': /* print help and exit */
print_help(0);
break;
case 'v': /* print version and exit */
fprintf(stdout, "%s %s\n", PACKAGE, VERSION);
exit(0);
break;
case 'u': /* convert INT utc value to timestring */
printf("%s\n", convert_utc(atoi(optarg)));
break;
case 's': /* convert STR to INT utc time value */
/* small check for correct user input ... */
if(strlen(optarg) < 23 || strlen(optarg) > 24) {
fprintf(stderr, "%s: Error, correct format ? `%s'\n", PACKAGE, optarg);
fprintf(stderr, "%s: Something like this maybe: `Sun Sep 7 00:00:04 2003'\n\n",
PACKAGE);
return 1;
}
printf("%d\n", get_utc(optarg));
break;
case '?':
fprintf(stderr, "%s: Error - No such option `%c'\n", PACKAGE, optopt);
print_help(1);
case ':':
fprintf(stderr, "%s: Error - Option `%c' requires an argument\n", PACKAGE, optopt);
print_help(1);
} /* switch */
} /* while */
return 0;
}
/* convert INT UTC to time string */
char *convert_utc(int uval) {
time_t timeval;
char *tstr = NULL;
timeval = uval;
tstr = strdup(ctime(&timeval));
/* remove trailing newline */
tstr[strlen(tstr) - 1] = '\0';
return tstr;
free(tstr);
}
int get_utc(char *str) {
struct tm timestruct;
int retval = 0;
/* Sun Sep 7 00:00:04 2003 */
if(strptime(str, "%a %b %d %T %Ey", ×truct) == 0)
return -1;
else {
timestruct.tm_year -= 1900;
timestruct.tm_isdst = -1;
}
retval = mktime(×truct);
return retval;
}
/* print help, status epilepticus */
void print_help(int exval) {
printf("%s,%s convert a time value to and from UTC time\n", PACKAGE, VERSION);
printf("Usage: %s [-h] [-v] [-s STR] [-u INT]\n\n", PACKAGE);
printf(" -h print this help and exit\n");
printf(" -v print version info and exit\n\n");
printf(" -u INT convert UTC time `INT' to a human readable format\n");
printf(" -s STR convert time `STRING' to an UTC value\n");
printf(" format of `STR' should be:\n");
printf(" Sun Sep 7 00:00:04 2003\n\n");
exit(exval);
}