/* Copyright (C) 2008 Emmanuel Varoquaux
This file is part of XOS.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see . */
#include "common.h"
#include
#include
#include
#include
#include
#include
static void print_date(const char *format, const struct tm *tm)
{
char buf[4096];
if (!strftime(buf, sizeof buf, format, tm))
error(EXIT_FAILURE, 0, "output too big");
printf("%s\n", buf + 1);
}
static void __attribute__ ((noreturn)) die_bad_usage()
{
fprintf(stderr, "Try `%s --help' for more information.\n", program_invocation_name);
exit(EXIT_FAILURE);
}
static void print_help()
{
printf("Usage: %s [OPTION]... [+FORMAT]\n", program_invocation_name);
puts("Display the current time in the given FORMAT, or set the system date.");
putchar('\n');
puts(" -u, --utc, --universal print Coordinated Universal Time");
puts(" -h, --help display this help and exit");
}
int main(int argc, char **argv)
{
static const struct option longopts[] = {
{"utc", no_argument, NULL, 'u'},
{"universal", no_argument, NULL, 'u'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0}
};
char c;
int utc;
const char *format;
time_t current_time;
const struct tm *date;
atexit(close_stdout);
utc = 0;
while ((c = getopt_long(argc, argv, "uh", longopts, NULL)) != -1)
switch (c) {
case 'u':
utc = 1;
break;
case 'h':
print_help();
return EXIT_SUCCESS;
case '?':
die_bad_usage();
}
if (argc > optind + 1) {
error(0, 0, "extra operand `%s'", argv[optind + 1]);
die_bad_usage();
}
if (optind < argc) {
if (argv[optind][0] != '+')
error(EXIT_FAILURE, 0, "the argument %s lacks a leading `+'", argv[optind]);
format = argv[optind];
}
else
format = "+%a %b %e %H:%M:%S %Z %Y";
if (time(¤t_time) == (time_t)-1)
error(EXIT_FAILURE, errno, "cannot get system date");
if (utc)
if (setenv("TZ", "UTC", 1) == -1)
error(EXIT_FAILURE, errno, "setenv");
if (!(date = localtime(¤t_time)))
error(EXIT_FAILURE, errno, "localtime");
print_date(format, date);
return EXIT_SUCCESS;
}