Patch-ID: bash32-032
[bash.git] / examples / loadables / strftime.c
blob92f489e38b4ec445f67142f90ecac14222db333a
1 /* strftime - loadable builtin interface to strftime(3) */
3 /* See Makefile for compilation details. */
5 #include <config.h>
7 #if defined (HAVE_UNISTD_H)
8 # include <unistd.h>
9 #endif
11 #include "bashtypes.h"
12 #include "posixtime.h"
14 #include <stdio.h>
16 #include "builtins.h"
17 #include "shell.h"
18 #include "common.h"
20 int
21 strftime_builtin (list)
22 WORD_LIST *list;
24 char *format, *tbuf;
25 size_t tbsize, tsize;
26 time_t secs;
27 struct tm *t;
28 int n;
29 intmax_t i;
31 if (list == 0)
33 builtin_usage ();
34 return (EX_USAGE);
37 if (no_options (list))
38 return (EX_USAGE);
40 format = list->word->word;
41 if (format == 0 || *format == 0)
43 printf ("\n");
44 return (EXECUTION_SUCCESS);
47 list = list->next;
49 if (list && list->word->word)
51 n = legal_number (list->word->word, &i);
52 if (n == 0 || i < 0 || i != (time_t)i)
54 sh_invalidnum (list->word->word);
55 return (EXECUTION_FAILURE);
57 else
58 secs = i;
60 else
61 secs = NOW;
63 t = localtime (&secs);
65 tbsize = strlen (format) * 4;
66 tbuf = 0;
68 /* Now try to figure out how big the buffer should really be. strftime(3)
69 will return the number of bytes placed in the buffer unless it's greater
70 than MAXSIZE, in which case it returns 0. */
71 for (n = 1; n < 4; n++)
73 tbuf = xrealloc (tbuf, tbsize * n);
74 tsize = strftime (tbuf, tbsize * n, format, t);
75 if (tsize)
76 break;
79 printf ("%s\n", tbuf);
80 free (tbuf);
82 return (EXECUTION_SUCCESS);
85 /* An array of strings forming the `long' documentation for a builtin xxx,
86 which is printed by `help xxx'. It must end with a NULL. */
87 char *strftime_doc[] = {
88 "Converts date and time format to a string and displays it on the",
89 "standard output. If the optional second argument is supplied, it",
90 "is used as the number of seconds since the epoch to use in the",
91 "conversion, otherwise the current time is used.",
92 (char *)NULL
95 /* The standard structure describing a builtin command. bash keeps an array
96 of these structures. The flags must include BUILTIN_ENABLED so the
97 builtin can be used. */
98 struct builtin strftime_struct = {
99 "strftime", /* builtin name */
100 strftime_builtin, /* function implementing the builtin */
101 BUILTIN_ENABLED, /* initial flags for builtin */
102 strftime_doc, /* array of long documentation strings. */
103 "strftime format [seconds]", /* usage synopsis; becomes short_doc */
104 0 /* reserved for internal use */