寫代碼時, 經常需要根據參數值得到一特定的字串. 每次都調用vsprintf, malloc很煩. 以下是一個
實現了此功能的介面.
/***************************************************************************** * Copyright : All Rights Reserved. * * Date : 2012-09-05 23:48:48 * Author/Corporation : Dengzhaoqun * Email : dengzhaoqun@163.com *****************************************************************************/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <stdarg.h>char *xm_vsprintf_ex(int len, char *fmt, ... );int main(int argc, char *argv[]){char *ptr;ptr = xm_vsprintf_ex(100, "%s-%s-%s", "lias", "dzq", "lvo");printf("%s\n", ptr);free(ptr);return 0;}char *xm_vsprintf_ex(int len, char *fmt, ... ){va_list ap;char *ptr;ptr = (char *)malloc(len * sizeof(char));if(ptr == NULL){fprintf(stderr, "malloc failed\n");return NULL;}memset(ptr, 0, len);va_start(ap, fmt);vsprintf(ptr, fmt, ap);va_end(ap);ptr[len-1] = '\0';return ptr;}
用起來還是比較爽的.