这两天的C语言开发工作中用到了多次字符串格式化拼接,分享一下自己写的一个接口,动态分配内存,减少因缓冲区大小不够导致字符串被截断的烦恼
直接上代码:
#include#include #include #include int str_append_to_string(char **str, const char *fmt, ...) { char *ptr = NULL; va_list args; int limit_size = 0; static int init_size = 512; static int use_size = 0; int size = 0; int append_ok = 0; if (fmt == NULL || strlen(fmt) <= 0) { printf("[%s:%d] param errorn", __FUNCTION__, __LINE__); return -1; } ptr = *str; if (ptr == NULL) { ptr = (char *)malloc(init_size * sizeof(char)); if (ptr == NULL) { printf("[%s:%d] malloc failedn", __FUNCTION__, __LINE__); return -1; } init_size = 512; use_size = 0; memset(ptr, 0, (init_size * sizeof(char))); } do { limit_size = init_size - use_size - 1; va_start(args, fmt); size = vsnprintf((ptr + use_size), limit_size, fmt, args); va_end(args); if (size > 0 && size <= limit_size) { use_size += size; append_ok = 1; continue; } // need more memory init_size += init_size >> 2; ptr = (char *)realloc(ptr, init_size * sizeof(char)); if (ptr == NULL) { printf("[%s:%d] realloc failedn", __FUNCTION__, __LINE__); return -1; } } while(!append_ok); *str = ptr; return 0; } int main(int argc, char*argv[]) { char *string = NULL; str_append_to_string(&string, "123/%s", "ABC"); str_append_to_string(&string, "/456/%s", "EFG"); str_append_to_string(&string, "/789/%s", "hjk"); str_append_to_string(&string, "%s", "over "); str_append_to_string(&string, "id_card/%s/name/%s", "123", "Bob"); if (string != NULL) { printf("string:%sn", string); free(string); string = NULL; } return 0; }
运行效果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)