For reasons beyond the scope of this question, assume I have a pre-allocated set of discontinuous memory buffers. I want to be able to print a formatted string into as many buffers as it takes to hold all the characters. I don't want to dynamically allocate a buffer large enough to hold the generated string.
Is there any way to get snprintf to "resume" on the first discarded character? Or a way to get that effect, without reimplementing the whole format parsing code from the stdlib?
Conceptually:
int nwritten = snprintf(message_buf[nextbuf++], MAX_MSG_LEN, fmt_string, var1, var2);
while (nwritten > MAX_MSG_LEN) {
already_written += MAX_MSG_LEN;
//It didn't fit in one buffer, write any remaining characters to the next buffer.
nwritten = snprintf_REMAINDER(message_buf[nextbuf++], already_written, MAX_MSG_LEN,
fmt_string, var1, var2);
}
With that code, these inputs
MAX_MSG_LEN = 16;
fmt_string = "%s: %.2f";
char* var1 = "percent complete";
float var2 = 45.6;
char msgbuf[N][MAX_MSG_LEN];
nextbuf = already_written = 0;
should result in
msgbuf[0]
containing "percent complet"
and
msgbuf[1]
containing "e: 45.06"
How do I implement snprintf_REMAINDER
?