Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple Question about timestamps

Status
Not open for further replies.

willz99ta

IS-IT--Management
Sep 15, 2004
132
US
Howdy,

What is the easiest way to put a time stamp onto a string?

Thanks,
Willz99ta
 
I'm not sure it's a simple question. Can you be more specific about exactly what how you want to timestamp a string?

Columb Healy
 
I have a string I am writing to a text file in UNIX. I would like it to have a timestamp at the end of the string.


<code>
fputs("Error: 'ISA' was not at the beginning of the data\n",LogPtr);
</code>
 
I know you said the end of the string, but if you want it to be [tt]fputs[/tt]-like with your string containing the newline at the end, it might be easier to do at the beginning. This is a modified version of something I had lying around.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int foo(const char *msg, FILE *file)
{
   static const char format[] = "<%x %X> ";
   time_t datetime;
   struct tm *local;
   char buffer [ 80 ];
   /*
    * Get the current date/time.
    */
   if ( time ( &datetime ) == (time_t)(-1) )
   {
      fputs ( "calendar time is not available\n", stderr );
      return 0;
   }
   /*
    * Convert to broken-down time.
    */
   local = localtime ( &datetime );
   if ( !local )
   {
      fputs ( "cannot convert to local time\n", stderr );
      return 0;
   }
   /*
    * Write the string with the requested format.
    */
   if ( !strftime ( buffer, sizeof buffer, format, local ) )
   {
      fputs ( "could not write format string\n", stderr );
      return 0;
   }
   /*
    * Display the results.
    */
   fputs ( buffer, file );
   fputs ( msg, file );
   fflush ( file );
   return 1;
}

int main(void)
{
   const char errmsg[] = "Error: 'ISA' was not at the beginning of the data\n";
   fputs ( errmsg, stdout );
   foo   ( errmsg, stdout );
   return 0;
}

/* my output
Error: 'ISA' was not at the beginning of the data
<02/25/05 11:47:27> Error: 'ISA' was not at the beginning of the data
*/
The basic ingredients are there.
 
Thanks Sir this works perfectly

Give this man some points Admin!

Willz99ta
 
Give this man some points Admin!
Click the [link javascript:eek:penindex(450,250,'/pops/tipvote.cfm?qid=1013595&vhandle=DaveSinkula&votes=1&w=450&h=250')]"Thank DaveSinkula for this valuable post!"[/url] at the bottom of his response.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top