Mail Archives: djgpp/1998/10/04/05:34:10
On Tue, 29 Sep 1998, bowman wrote:
> tonyblaha AT juno DOT com wrote:
> >
> > I'm having trouble with the strftime() function in time.h.
> > I've copied the example directly from libc.inf:
> > But I can't get it to work.
>
> The example is a little confusing, in that is doesn't mention that t
> needs to be filled out.
As far as I could see, `strftime' works perfectly okay; I think both
code snippets that were posted in this thread have cockpit errors.
The first snippet was this:
struct tm t;
char buf[100];
strftime(buf, 100, "%B %d, %Y", &t);
This doesn't fill t with a time information, so it's no surprise
zeroes are printed.
The second snippet was this:
time_t current_time;
struct tm* t;
char buf[100];
current_time = time(NULL);
t = localtime(¤t_time);
strftime(buf, 100, "%B %d, %Y", &t);
puts(buf);
This passes a "struct tm **" to `strftime' whereas it expects a
"struct tm *", so it also fails.
The following program works for me (note that it's generally a good
idea to test the return value, to avoid printing random junk):
#include <time.h>
#include <stdio.h>
int main (void)
{
char buf[100];
time_t current_time = time (NULL);
struct tm *t = localtime (¤t_time);
if (strftime (buf, 100, "%B %d, %Y", t) <= 0)
puts ("ERROR!");
else
puts (buf);
return 0;
}
- Raw text -