一些将任意数量的字符串连接到动态分配的缓冲区中的实用函数:
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
/*
vstrconcat() - return a newly allocated string that is the concatenation of
all the string passed in the variable length argument list.
The argument list *must* be terminated with a NULL pointer.
All other arguments must be char* to ASCIIZ strings.
Thre return value is a pointer to a dynamically allocated
buffer that contains a null terminated string with
all the argument strings concatenated.
The returned pointer must be freed with the standard free()
function.
*/
char* vstrconcat( char const* s1, ...)
{
size_t len = 0;
char const* src = NULL;
char* result = NULL;
char* curpos = NULL;
va_list argp;
if (!s1) {
return NULL; // maybe should return strdup("")?
}
// determine the buffer size needed
src = s1;
va_start(argp, s1);
while (src) {
len += strlen(src); //TODO: protect against overflow
src = va_arg(argp, char const*);
}
va_end(argp);
result = malloc(len + 1);
if (!result) {
return NULL;
}
// copy the data
src = s1;
va_start(argp, s1);
curpos = result;
while (src) {
size_t tmp = strlen(src);
memcpy(curpos, src, tmp);
curpos += tmp;
src = va_arg(argp, char const*);
}
va_end(argp);
result[len] = '\0';
return result;
}
/*
strconcat() - simple wrapper for the common case of concatenating exactly
two strings into a dynamically allocated buffer
*/
char* strconcat( char const* s1, char const* s2)
{
return vstrconcat( s1, s2, NULL);
}
你可以在你的例子中这样称呼它:
(*ls)[count++] = strconcat( "DIR ", ep->d_name);