将整数转换为字符串而不知道缓冲区大小

时间:2013-06-18 08:58:07

标签: c string casting char int

我想设置路径的占位符值(类型为int):

/ sys / class / gpio / gpio%d / value =>的 / SYS /类/ GPIO / gpio33 /值

插入的值最大为99且最小为1.因为我不希望路径中有任何空字符,所以我希望自动确定缓冲区大小。

这就是为什么我想到 asprintf(),它为字符串执行此操作,但不幸的是它不能用于整数。

#define GPIO_PATH_VALUE "/sys/class/gpio/gpio%d/value"

char * path;

asprintf(path, GPIO_PATH_VALUE, 4);
asprintf(path, GPIO_PATH_VALUE, 67);

是否有与 asprintf()类似的函数,它与整数一起使用?

博多

2 个答案:

答案 0 :(得分:2)

试试此asPrintf()需要char **作为争论,请参阅此http://linux.die.net/man/3/asprintf

#define GPIO_PATH_VALUE "/sys/class/gpio/gpio%d/value"

char * path;

asprintf(&path, GPIO_PATH_VALUE, 4);
asprintf(&path, GPIO_PATH_VALUE, 67);

由于asPrintf()在函数内部执行malloc(),在此函数path中不会指向malloced内存地址,因此您需要发送path的地址以便{{1} }更改asPrintf(),这将指向malloced地址。

答案 1 :(得分:2)

由于asprintf()是GNU扩展,其他遇到此问题的人可能希望避免使用它。

相反,它可以完成,例如

#define GPIO_PATH_VALUE "/sys/class/gpio/gpio%d/value"

char * path;

path = malloc(strlen(GPIO_PATH_VALUE) + 5);
// error checking needed!

sprintf(path, GPIO_PATH_VALUE, 4); // better snprintf?
// or
sprintf(path, GPIO_PATH_VALUE, 67);

path = realloc(path, strlen(path)+1);
// no error checking needed, as we definitely shrink or nop, not extend.

如果很明显GPIO_PATH_VALUE保持这么简单。

如果它变得更复杂,你可以做

#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>

char * vbsprintf(const char * format, va_list ap)
{
    va_list ap2;
    va_copy(ap2, ap);
    int len = vsnprintf(NULL, 0, format, ap2);
    va_end(ap2);
    char * str = malloc(len + 1);
    if (!str) return NULL;

    vsnprintf(str, len + 1, format, ap);
    return str;
}

char * bsprintf(const char * format, ...)
{
    va_list ap;
    va_start(ap, format);
    char * str = vbsprintf(format, ap);
    va_end(ap);
    return str;
}

如果您的系统支持vsnprintf(NULL, 0,以确定所需的长度。

相关问题