给定以下代码:
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