Linux 中的 sprint_f 宏用于跨平台应用
我正在将现有的 Windows 应用程序移植到 Linux。
大多数操作系统 API\ Microsoft 非标准扩展函数可以轻松地(或多或少......)被等效的 Linux\ GCC API 替换,但是,我不知道如何处理 sprintf_s ,它获取可变数量的参数。
有人对此有什么想法吗(如果可以的话,请也提供代码示例)?
预先感谢大家。
I'm porting an existing Windows application to Linux.
The most of the OS APIs\ Microsoft non-standard extension functions can be easily (more or less...) replaced by equivalent Linux\ GCC APIs, however, I don't know how to deal with sprintf_s which gets variable numbers of arguments.
Does anyone have an idea (If you can please put the code example as well) for that?
Thank you all in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,您能否将代码移植为使用 C++ iostream(例如
ostringstream
)?这将完全消除sprintf
函数行的所有可能问题,如果调用点数量有限,可能是最好的选择。如果这不是一个选项:
sprintf_s
函数基本上是一个帮助器,可以防止错误(以及外部滥用导致缓冲区溢出。来自 http://msdn.microsoft.com/en-us/library/ce3zzk1k%28VS.80%29.aspx 我们了解到它做了两件事:它检查格式字符串的有效格式(这并不意味着它会进行类型检查 - 它仍然无法做到这一点),并且它允许指定最大长度最好的替换 。将是
snprintf
,与sprintf_s
相比,它不会进行格式字符串验证,并且并非所有版本都保证最终字符串将以 null 结尾:您始终会这样做。还想在调用后将 null 存储到缓冲区的最后一个字符中,以确保最终字符串以 null 结尾。First, can you just port your code to use C++ iostreams instead (for example
ostringstream
)? This would completely remove all the possible issues with thesprintf
line of functions, and if there are a limited number of call points is probably the best option.If that isn't an option: The
sprintf_s
function is basically a helper to prevent mistakes (and external abuse to cause buffer overflows. From http://msdn.microsoft.com/en-us/library/ce3zzk1k%28VS.80%29.aspx we learn that it does two things: It checks the format string for valid formats (this doesn't mean it does type checking - it still can't do that), and it allows a max length to be specified.The best replacement will be
snprintf
which does have limitations compared tosprintf_s
. It won't do format string validation. And not all versions guarantee that the final string will be null terminated: You always want to also store a null into the last character of your buffer after the call to ensure that the final string is null terminated.添加到头文件的末尾或源文件的开头:
Add to end of your header file or beginning of source file:
snprintf 具有相同的签名,但据我所知,它的行为方式略有不同。
snprintf has the same signature, but AFAIK it behaves in a slightly different way.
sprintf_s 只是 sprintf 的“安全”版本(将缓冲区长度作为额外参数),您不能仅将 sprintf 用于您的端口吗?
sprintf_s is just a "secure" version (takes buffer length as extra argument) of sprintf , cant you just use sprintf for your port ?
为什么不直接为 Linux 提供 sprintf_s 的条件编译实现呢?此实现可以简单地忽略额外的参数并调用 sprintf()。
Why not just provide a conditionally compiled implementation of sprintf_s for Linux? This implementation could simply ignore the extra argument and call through to sprintf().