ctime problems...any ideas?

hello,

hopefully someone out there can help me with this. I'm using ctime to print a time_t value in a more friendly format, but when ctime is called more than once with different values, it prints the same time. here's a small piece of the code, and the output.



[code]cout << ctime (&(statBuff->st_atime))
<< ctime (&(statBuff->st_mtime))
<< ctime (&(statBuff->st_ctime)) << endl[/code]

output example:

Thu Sep 26 13:38:54 2002
Thu Sep 26 13:38:54 2002
Thu Sep 26 13:38:54 2002

More info....statBuff is a 'struct stat' type, and yes, i did check the members st_atime, st_mtime, st_ctime. they all hold different values so ctime should print a different string for each one.

I really don't see what i'm doing wrong. i'm really thinking it has something to do with the way ctime is implemented. Do anyone know for sure?

gcc 2.96 (Mandrake's version...I don't have a choice on this one)...

Comments

  • ctime returns a pointer (char*) to an internal buffer, which gets reused with each call.
    So you must use the result before calling ctime again

    [code]
    cout << ctime (&(statBuff->st_atime)) ;
    cout << ctime (&(statBuff->st_mtime)) ;
    cout << ctime (&(statBuff->st_ctime)) << endl;
    [/code]

  • Thanks SteveC,

    i do need one point of clarification. What exactly do you me by 'use'? So the function doesn't overwrite the buffer on every successive call?

    : ctime returns a pointer (char*) to an internal buffer, which gets reused with each call.
    : So you must use the result before calling ctime again
    :
    : [code]
    : cout << ctime (&(statBuff->st_atime)) ;
    : cout << ctime (&(statBuff->st_mtime)) ;
    : cout << ctime (&(statBuff->st_ctime)) << endl;
    : [/code]
    :
    :

  • > What exactly do you me by 'use'?
    Use means you
    - print it,
    - save it to a file,
    - copy it to another char array.

    It's like calling fgets() to read a file. The buffer used by fgets() is written to on each call to fgets(), so you need to make sure you've finished with the current buffer contents before calling fgets() again.

    It's the same deal with ctime()


  • okay...i understand what you're saying, but when i send the contents of ctime()'s buffer to cout is that not using it?

    anyway thanks, it works for me when i use separtate cout statements, but I was just wondering why it doesn't work with cascading...

    cheers,
    -g
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories