开发者

Fencepost conditions and portability for using of snprintf()?

开发者 https://www.devze.com 2023-03-18 07:08 出处:网络
Given the following code: const int size = 20; char buffer[size]; // From the Linux man page for snprintf():

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 great开发者_JAVA技巧er than or equal to size


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号