使用 snprintf() 的 Fencepost 条件和可移植性?

发布于 2024-11-19 07:08:10 字数 994 浏览 2 评论 0原文

给出以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撞了怀 2024-11-26 07:08:10

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

栅栏条件一切都很好。你的 printf 并不完全正确,在 equals 情况下它将打印

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

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

The buffer was not large enough, we needed 215 but only had 215.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文