2

我有这个代码:

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

所以当我打印它时,我有这个:
file1
file2
DIR: file3
ecc

在哪里ls提前char ***ls
谢谢!

4

4 回答 4

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
于 2012-07-02T12:09:02.877 回答
2

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

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

它以与(和您的)(*ls)[count++]相同的方式分配指针。mallocstrdup

于 2012-07-02T12:11:20.850 回答
1

使用asprintfwhich 分配一个字符串和printfs 给它。就像是:

#include <stdio.h>

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

我猜这ls是一个指向数组的指针char *。记得稍后释放字符串!

于 2012-07-02T12:08:25.527 回答
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);
于 2012-07-02T15:17:49.333 回答