gpt4 book ai didi

c - 在 Windows 上使用 asprintf()

转载 作者:可可西里 更新时间:2023-11-01 13:27:48 24 4
gpt4 key购买 nike

我写了一个 C 程序,它在 linux 上运行得很好,但是当我在 windows 上编译它时,它给我一个错误,说 asprintf() 是未定义的。它应该是 stdio 库的一部分,但似乎许多编译器不包含它。我可以将哪个编译器用于允许我使用 asprintf() 函数的 Windows?我已经尝试了多个编译器,但到目前为止似乎都没有定义它。

最佳答案

asprintf()函数不是 C 语言的一部分,并非在所有平台上都可用。 Linux 拥有它的事实不寻常

您可以使用 _vscprintf 编写自己的代码和 _vsprintf_s .

int vasprintf(char **strp, const char *fmt, va_list ap) {
// _vscprintf tells you how big the buffer needs to be
int len = _vscprintf(fmt, ap);
if (len == -1) {
return -1;
}
size_t size = (size_t)len + 1;
char *str = malloc(size);
if (!str) {
return -1;
}
// _vsprintf_s is the "secure" version of vsprintf
int r = _vsprintf_s(str, len + 1, fmt, ap);
if (r == -1) {
free(str);
return -1;
}
*strp = str;
return r;
}

这是凭内存写的,但应该非常接近你的写法 vasprintf用于 Visual Studio 运行时。

_vscprintf的使用和 _vsprintf_s是 Microsoft C 运行时独有的怪癖,您不会在 Linux 或 OS X 上以这种方式编写代码。_s特别是版本,虽然标准化,但实际上在 Microsoft 生态系统之外并不经常遇到,并且 _vscprintf甚至在别处都不存在。

当然,asprintf只是 vasprintf 的包装:

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;
}

这不是一种“可移植”的写法asprintf ,但如果您的唯一目标是支持 Linux + Darwin + Windows,那么这是最好的方法。

关于c - 在 Windows 上使用 asprintf(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40159892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com