使用snprintf()的栅栏条件和可移植性

Fencepost conditions and portability for using of snprintf()?

本文关键字:条件 可移植性 snprintf 使用      更新时间:2023-10-16

给定以下代码:

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

snprintf严格来说不是可移植的,因为它不是C/c++标准的一部分。Windows将其命名为_snprintf -但其他方面是相同的。

栅栏柱的条件都很好。你的printf不是很好,在等号的情况下它会打印

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