File: whattime.c

package info (click to toggle)
nws 2.11-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,700 kB
  • ctags: 2,820
  • sloc: ansic: 28,849; sh: 3,289; java: 1,205; makefile: 697; perl: 12
file content (105 lines) | stat: -rw-r--r-- 2,059 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/* $Id: whattime.c,v 1.5 2004/08/16 17:25:16 graziano Exp $ */

#include <stdio.h>
#include <string.h>
#if TIME_WITH_SYS_TIME
#	include <sys/time.h>
#	include <time.h>
#else
# if HAVE_SYS_TIME_H
#	include <sys/time.h>
# else
#	include <time.h>
# endif
#endif
#include <stdlib.h>
#include <unistd.h>

#define SWITCHES "af:"

/**
 * print the usage of this executable
 */
void
usage(char *argv[])
{
	fprintf(stderr, "Usage: %s [OPTION] time ...\n", argv[0]);
	fprintf(stderr, "Translate seconds from epoch to friendlier time.\n\n");
	fprintf(stderr, "\t-a        alternative format (for scripts)\n");
	fprintf(stderr, "\t-f file   read from file (1st column is time).\n");
	fflush(stderr);
	exit(1);
}

/**
 * print the translated number
 */
void 
translate(int time_val, int alt)
{
	time_t tmp;
	char s[256];		/* hold the string to print */

	tmp = time_val;

	if (alt == 0) {
		fprintf(stdout,"%d == %s", time_val, ctime(&tmp));
	} else {
		strftime(s, 256, "%d-%m-%Y/%H:%M:%S", localtime(&tmp));
		printf("%s", s);
	}
	fflush(stdout);
}

/**
 * translate seconds from the epoch to some human friendly time. It can
 * print out a date suitable to be used in script (ie gnuplot will
 * understand it easily): use the -a switch.
 */
int
main(int argc, char *argv[])
{
	int time_val = 0;
	int i, alt=0, opt;
	char buffer[256];
	FILE *file = NULL;

	/* parse the command line */
	while ((opt = getopt(argc, argv, SWITCHES)) != EOF) {
		switch (opt) {
		case 'a':
			alt = 1;
			break;
		case 'f':
			file = fopen(optarg, "r");
			if (file == NULL) {
				fprintf(stderr, "Couldn't open %s\n", optarg);
				exit(1);
			}
			break;
		default:
			usage(argv);
			break;
		}
	}

	/* do the work */
	if (file != NULL) {
		while (fgets(buffer, 256, file) != NULL) {
			if (sscanf(buffer, "%d", &time_val) != 0) {
				translate(time_val, alt);
				printf("%s", strchr(buffer, ' '));
			}
		}
	} else {
		for (i = optind; i < argc; i++) {
			time_val = (int)strtol(argv[i], NULL, 10);
			translate(time_val, alt);
		}
	}

	if (file != NULL)
		fclose(file);

	return(0);
}