Yuri J
Yuri J

Reputation: 129

How to get the last characters of formatted output when snprintf returns more than its size argument?

I have a buffer that is 65536 characters long. I need to print formatted output to the buffer. Problem is: If the formatted output size turns out to be bigger than 65535, I would like to have the last characters of it in the buffer, discarding the first ones, and not the remaining ones, as snprintf does.

I thought about implementing the snprintf logic, but starting from the end of the string instead of the beginning.

Is there any easier way to accomplish this?

Upvotes: 0

Views: 149

Answers (1)

bruno
bruno

Reputation: 32596

A solution is :

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>

int snprintfEnd(char *str, size_t size, const char *format, ...)
{
  va_list ap1, ap2;

  va_start(ap1, format);
  va_copy(ap2, ap1);

  /* get length of all */
  int sz = vsnprintf(0, 0, format, ap2);

  va_end(ap2);

  /* get all */
  char * all = malloc(sz + 1);

  vsprintf(all, format, ap1);
  va_end(ap1);

  /* copy the expected part */
  int r;

  if (sz < size) {
    strcpy(str, all);
    r = sz;
  }
  else {
    strcpy(str, all + sz - size);
    r = size;
  }

  free(all);
  return r;
}

int main()
{
  char s[6];

  int ln = snprintfEnd(s, 5, "%d %d %d", 1, 234, 567);

  printf("%d : '%s'\n", ln, s);

  return 0;
}

Execution :

5 : '4 567'

Upvotes: 1

Related Questions