在MacOS / Linux上替换MS _vscprintf? [英] Replacement for MS _vscprintf on MacOS/Linux?
问题描述
作为一个学习经验,我从Windows移植一些东西到MacOS,并遇到类似这样的:
void SomeClass :: someFunction(const char * format,va_list args)
{
int size = _vscprintf(format,args); //格式化后的长度
std :: string s;
s.resize(size);
vsprintf(& s [0]);
...
}
现在,由于_vscprintf是Microsoft特定的没有在Linux上发现类似的东西我想我会问这里。
我们还假设这个代码在一些关键路径,不应该有一些额外的开销堆分配等。
在MacOS / Linux上推荐的_vscprintf替换是什么?
谢谢!
可以使用 vsnprintf
int _vscprintf(const char * format,va_list pargs){
int retval;
va_list argcopy;
va_copy(argcopy,pargs);
retval = vsnprintf(NULL,0,format,argcopy);
va_end(argcopy);
return retval;感谢@dbasic更完整的解决方案和@ja修复了明显的错误。错误。
As a learning experience I'm porting some stuff from Windows to MacOS and came across something like this:
void SomeClass::someFunction(const char* format, va_list args)
{
int size = _vscprintf(format, args); // length after formatting
std::string s;
s.resize(size);
vsprintf(&s[0]);
...
}
Now, as _vscprintf is Microsoft specific and I haven't found anything similar on Linux I thought I'd ask here.
Let's also assume this code is in some critical path and shouldn't have some extra overhead of heap allocation or such.
What is the recommended replacement for _vscprintf on MacOS/Linux?
Thanks!
解决方案 You can use vsnprintf
instead;
int _vscprintf (const char * format, va_list pargs) {
int retval;
va_list argcopy;
va_copy(argcopy, pargs);
retval = vsnprintf(NULL, 0, format, argcopy);
va_end(argcopy);
return retval;
}
Thanks to @dbasic for the more complete solution and @j-a for fixing the obvious errors.
这篇关于在MacOS / Linux上替换MS _vscprintf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!