Условия забора и переносимость использования snprintf ()? - PullRequest
2 голосов
/ 06 июля 2011

С учетом следующего кода:

const int size = 20;
char buffer[size];

// From the Linux man page for snprintf():
//
// The 'res' is the number of bytes that would be written to buffer had size been
// sufficiently large excluding the terminating null byte.  Output bytes beyond
// the size-1st are discarded instead of being written to the buffer, and a null
// byte is written at the end of the bytes actually written into the buffer.
int res = snprintf(buffer, size, "some format with %d and %s", 23, "some string");

if (res >= size) {
  cerr << "The buffer was not large enough, we needed " << res
       << " but only had " << size << "." << endl;
} else {
  cout << "The buffer is big enough, we only needed " << res
       << " but had " << size << "." << endl;
}

Является ли это портативным, и если да, правильно ли я выполнил все условия на заборе

1 Передача size в snprintf ()

2 Проверка res больше или равно size

1 Ответ

1 голос
/ 07 июля 2011

snprintf не является строго переносимым, поскольку он не является частью стандартов C / C ++. В Windows он указан как _snprintf, но в остальном идентичен.

Условия забора все в порядке. Ваш printf не совсем в порядке, в случае равенства он напечатает

The buffer was not large enough, we needed 215 but only had 215.
...