在strdup C之前追加字符串

时间:2012-07-02 12:03:18

标签: c string

我有这段代码:

if(S_ISDIR(fileStat.st_mode)){
  (*ls)[count++] = strdup(ep->d_name);
  ep = readdir(dp);
} else{
  (*ls)[count++] = strdup(ep->d_name);
  ep = readdir(dp);
}

如何附加字符串“DIR”以获得类似的内容:

 if(S_ISDIR(fileStat.st_mode)){
      (*ls)[count++] = "DIR "strdup(ep->d_name);
      ep = readdir(dp);

所以,当我打印它时,我有这个:
文件1
文件2
DIR:file3
ECC

其中lschar ***ls 提前谢谢!

4 个答案:

答案 0 :(得分:2)

有几种方法可以实现此目的:您可以使用strcat,或者如果您需要进行多项修改,则可以使用snprintf

size_t len = strlen(ep->d_name);
// You need five characters for "DIR: ", and one more for the terminating zero:
(*ls)[count] = malloc(len+6);
strcpy((*ls)[count], "DIR: ");      // Copy the prefix
strcat((*ls)[count++], ep->d_name); // Append the name

答案 1 :(得分:2)

最简单的方法是使用(非标准)函数asprintf

if(asprintf(&(*ls)[count++], "DIR %s", ep->d_name) == -1) /* error */;

它以与(*ls)[count++](以及您的malloc)相同的方式在strdup中分配指针。

答案 2 :(得分:1)

使用asprintf为其分配字符串和printf。类似的东西:

#include <stdio.h>

asprintf(&((*ls)[count++]) "DIR%s", ed->d_name);

我猜测ls是指向char *数组的指针。记得以后释放字符串!

答案 3 :(得分:0)

一些实用程序函数将任意数量的字符串连接到动态分配的缓冲区中:

#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);