delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/10/04/05:34:10

Date: Sun, 4 Oct 1998 12:33:34 +0300 (IDT)
From: Eli Zaretskii <eliz AT is DOT elta DOT co DOT il>
X-Sender: eliz AT is
To: bowman <bowman AT montana DOT com>
cc: tonyblaha AT juno DOT com, "djgpp AT delorie DOT com" <djgpp AT delorie DOT com>,
DJ Delorie <dj AT delorie DOT com>
Subject: Re: newbie: strftime
In-Reply-To: <36118D7D.9BC37287@montana.com>
Message-ID: <Pine.SUN.3.91.981004123247.1863I-100000@is>
MIME-Version: 1.0

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(&current_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 (&current_time);

    if (strftime (buf, 100, "%B %d, %Y", t) <= 0)
      puts ("ERROR!");
    else
      puts (buf);
    return 0;
  }

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019