使用 snprintf() 的 Fencepost 条件和可移植性?
给出以下代码:
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
Given the following code:
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;
}
Is this portable and if so, did I get all the fencepost conditions correct?
1 Passing size
to snprintf()
2 Checking res
being greater than or equal to size
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
snprintf 严格来说不是可移植的,因为它不是 C/C++ 标准的一部分。 Windows 将其称为 _snprintf - 但其他方面相同。
栅栏条件一切都很好。你的 printf 并不完全正确,在 equals 情况下它将打印
snprintf isn't strictly speaking portable, as it's not part of the C/C++ standards. Windows has it as _snprintf - but otherwise identical.
The fencepost conditions are all fine. Your printf's aren't entirely fine, in the equals case it's going to print