-1

I need some help in converting following format using strcat function instead of s printf.

const char* const MSG_STAMP_PRINTF_FORMAT = "%c %04d-%02d-%02d %02d:%02d:%02d.%03d";

char cMsgStamp[500];
char cSevChr = 'I'; 

struct tm gmt;

// Calculate Day/Hour/Min/Sec
gmtime_r((time_t *)&pMsg->iSysTimeSec, &gmt);

int iSysTimeMs = 100;

// Format the begining of the message, the message stamp

sprintf(&cMsgStamp[0],
         MSG_STAMP_PRINTF_FORMAT,
         cSevChr, gmt.tm_year+1900, gmt.tm_mon + 1, gmt.tm_mday, gmt.tm_hour, gmt.tm_min, gmt.tm_sec,iSysTimeMs
             ); is 0x%s\n", n3);

instead of using sprintf, i have to get same info which is present in cMsgStamp above using number of strcat functions.

can any one help me on this. Thanks! Venkata RKA

nmichaels
  • 49,466
  • 12
  • 107
  • 135
Venkata
  • 513
  • 1
  • 9
  • 15

1 Answers1

0

You need to write one auxilliary function that, given an integer number n, a number of digits d, and a buffer which is 'big enough' (at least n+1 bytes long), does the work of formatting '%04d', etc. This function might use strcat(), but probably wouldn't.

You need a main function that can step through the format string, isolating different bits (basically, there are %-sequences and other chars) and processing them appropriately. This might use strcat(), but probably wouldn't unless you have two buffers in use - one to hold temporary results from the first (auxilliary) function and one for the final result. (I don't see a need to use the two buffers, but it would provide an excuse to use strcat().)

Make sure that the main function is told how big the buffer is and that it does not overflow the bounds of its buffer. It is only ever safe to use strcat() (or strncat()) if you know precisely how much data is in the buffer you are copying to, how much data is in the string you are adding, and precisely how long the buffer you are using is altogether. And, in particular, the interface to strncat() invites disaster - the last (size) argument isn't the size of the target buffer (like it is in most similar calls); it is the amount of space left in the buffer.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278