使用snprintf()的栅栏条件和可移植性
Fencepost conditions and portability for using of snprintf()?
给定以下代码:
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.
相关文章:
- C++Union/Struct位域的实现和可移植性
- 静态库可移植性
- C++:Unicode 字符串文字的可移植性
- 如何使Visual Studio 2017 C++项目在计算机之间更具可移植性
- 在为视频游戏实施基本的二进制序列化时,请担心可移植性
- 重写类以使其更通用,以实现可移植性
- Visual Studio 2015 <=> QtCreator 5 (c++) 代码可移植性
- 通过虚拟接口类导出C 类的可移植性
- 位移位可移植性
- 如何在Visual Studio中进行串行端口编程C++Windows和Linux之间的可移植性?
- 提高 Python 可移植性问题
- 库如何在不同的操作系统之间实现可移植性
- 使用C 11 /最近的G 版本(4.7 / 4.6)的可移植性
- 模板函数实例化的可移植性问题
- XCode、命名空间、C++和代码可移植性
- 嵌入式C++项目 - 需要支持智能指针.可能的可移植性问题
- 使用指针遍历数组的可移植性
- 头文件中内联自由函数的可移植性
- 文件IO中的可移植性问题
- 使用snprintf()的栅栏条件和可移植性