QT6.4.3中,关于QString asprintf(const char*cformat,...)与int asprintf(char**strp,const char*fmt,...)的使用问题

发布时间 2024-01-11 01:38:03作者: 万佛从心

QT中QString类的Static Public Members(静态公众成员)定义了QString asprintf(const char*cformat,...)。与Linux下C语言的定义是有区别的。网上很多搞混了二者的用法,甚至有的在QT下用对象去调用asprintf()的例子!

asprintf()函数原本是Linux下,GNU扩展的C函数库glibc下的函数,不是标准C函数库或者POSIX。如没有安装MinGW,windows下运行还得自已找到他们的原始定义。
asprintf()函数是一个增强版的sprintf()。用于处理变长字符串,能够根据格式化的字符串长度,申请足够的内存空间。原型为:int asprintf(char
strp,const charfmt,...),要注意的是第一个形参是二级指针,使用后需要使用free()释放空间。
如果要在windows下的QT中运行glibc中的int asprintf(char
strp,const char
fmt,...),可以自已写一个头文件加入工程中;
头文件如下:

#ifndef ASPRINTF_H
#define ASPRINTF_H
#include <stdio.h> // needed for vsnprintf
#include <stdlib.h> // needed for malloc-free
#include <stdarg.h> // needed for va_list
#ifndef _vscprintf

int _vscprintf_so(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;}

#endif // _vscprintf
#ifndef vasprintf

int vasprintf(char **strp, const char fmt, va_list ap) {
int len = _vscprintf_so(fmt, ap);
if (len == -1) return -1;
char str = (char)malloc((size_t) len + 1);
if (!str) return -1;
int r = vsnprintf(str, len + 1, fmt, ap); /
"secure" version of vsprintf */
if (r == -1) return free(str), -1;
*strp = str;
return r;}

#endif // vasprintf
#ifndef asprintf

int asprintf(char *strp[], const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
int r = vasprintf(strp, fmt, ap);
va_end(ap);
return r;}

###### #endif // asprintf
#endif // ASPRINTF_H

//=========================
加入头文件后,二种asprintf()函数都可以使用了。
下面为main()函数:

#include
#define debug qdebug()<<
#include<string.h>
#include"a.h"
#include"asprintf.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>

int main(int argc,char*argv[]) //这是从空项目建立来的
{
QCoreApplication app(argc, argv);

QString aa="china";
QString bb=" america";


QString ee;
ee=QString::asprintf("%s,%s",aa.toStdString().data(),bb.toStdString().data());
debug ee;


setbuf(stdout, NULL);
char *b;
asprintf(&b, "Mama %s is equal %d.", "John", 58);

printf("%sabc\n",b);
free(b);


return app.exec(); 

}