[Techtalk] getting the time as a string in c

kristina clair kclair at gmail.com
Thu Sep 29 08:25:46 EST 2005


Thanks for all the replies!  It was all very helpful.

I did consider using ctime(), but the problem is that I do not want a
newline in the time string.

I thought that maybe I could replace it with a space, using something like this:

    time_t timeseconds;
    timeseconds = time(NULL);
    char timestring[] = ctime(&timeseconds);  /* line 13 */
    timestring[strlen(timestring)-1] = " ";

But gcc complains:
program.c:13: error: invalid initializer

Thanks again,
Kristina

On 9/28/05, Almut Behrens <almut-behrens at gmx.net> wrote:
> On Wed, Sep 28, 2005 at 09:07:47PM +0100, Dan wrote:
> > So what you want to do is:
> >
> >    time_t timeInSeconds;
> >    const struct tm *timeptr;
> >
> >    timeInSeconds = time(NULL);
> >    timeptr = localtime(&timeInSeconds);   /* "&" means "pointer to" */
> >
> >    /* Note: a second call to localtime()
> >     * might overwrite timeptr's memory.
> >     * that's not a concern here, though.    */
> >    strftime(timestring, timestrsize, timeformat, timeptr);
> >
> >    printf("%s\n", timestring);
>
> In case the timeformat you want is just "%c", you can also use ctime()
> (as Dan has mentioned in his other reply), which is somewhat shorter,
> as ctime() directly returns the desired string (i.e. a pointer to a
> char buffer, which you don't even need to allocate yourself).
>
> A fully working program to print the current time would be no longer
> than this
>
>   #include <stdio.h>
>   #include <time.h>
>
>   int main(void) {
>
>       time_t t = time(NULL);
>       printf("%s", ctime(&t));
>
>       return 0;
>   }
>
> compared to using strftime():
>
>   #include <stdio.h>
>   #include <time.h>
>
>   #define TSTR_MAXSIZE 40
>
>   int main(void) {
>
>       char timestring[TSTR_MAXSIZE];
>
>       time_t t = time(NULL);
>       const struct tm *timeptr = localtime(&t);
>       strftime(timestring, TSTR_MAXSIZE, "%c", timeptr);
>
>       printf("%s\n", timestring);
>
>       return 0;
>   }
>
> Cheers,
> Almut
>
> P.S.: according to my experiences from giving introductory courses,
> most problems learners of C are facing revolve around memory and
> pointers:
> * where is data stored
> * who is resposible for the associated memory/buffers, i.e.
>   * who allocates it
>   * who needs to free it (if it's dynamic)
> * how to address it, i.e. when to use *foo, foo or &foo
>
> So, if you don't want your program to segfault, it's essential to get a
> good grasp if this stuff... ;)
>
> _______________________________________________
> Techtalk mailing list
> Techtalk at linuxchix.org
> http://linuxchix.org/cgi-bin/mailman/listinfo/techtalk
>


More information about the Techtalk mailing list