将当前目录中的所有文件列为C中的String

时间:2014-10-13 20:05:27

标签: c string stdout

好的,我试图将当前目录目录的所有文件列为C中的String。 当前目录中的文件是:

myftpclient.c,myftpclient.o,myftpserver.c,myftpserver.o

char * list(void) 
{
    DIR *dp; // directory var
    struct dirent *ep;
    char str[256] ;
    int n = 0 ;
    dp = opendir ("./");
    if (dp != NULL)
    {
        while ((ep = readdir (dp)))
        {
            int curLen = strlen((ep->d_name)) ;
            strncat(str, (ep->d_name), curLen) ;
            strncat(str, "\n", 1) ;
            n += curLen + 1 ;
        }
        str[n] = '\0' ;
        (void) closedir (dp);
    }
    else
        perror ("Couldn't open the directory");

    return str ;
}

这是我对它的呼吁:

char * str = malloc(256) ;
str = list() ;

我打印字符串时的输出是: B0

哪个甚至没有接近正确。我究竟做错了什么?

1 个答案:

答案 0 :(得分:0)

我在您的代码中看到以下问题。

  1. 您正在创建一个char数组,仅保留256个字符。当保存目录条目名称和换行符所需的字符数超过256时,您将遇到超出范围的内存访问。

  2. 您正在返回指向本地范围中定义的数组的指针。从函数返回后,数组将无效。

  3. 您可以使用strcat代替strncatstrncat仅在您想要追加少于在源头保留的字符数时才有用。

  4. 您可以通过以下方式修复这些问题:

    1. 使用mallocstr分配内存。

    2. 使用realloc增加每个目录条目的已分配内存。

    3. 确保free在调用函数中list()返回的内存。

    4. 这是一个应该有效的版本。

      char * list(void) 
      {
          DIR *dp; // directory var
          struct dirent *ep;
          char* str = malloc(1);
          int n = 0 ;
          str[0] = '\0';
          dp = opendir ("./");
          if (dp != NULL)
          {
              while ((ep = readdir (dp)))
              {
                  int curLen = strlen((ep->d_name)) ;
                  n += curLen + 2 ; // One of the terminating null and the
                                    // other for the newline.
                  str = realloc(str, n);
                  strcat(str, (ep->d_name)) ;
                  strcat(str, "\n") ;
              }
              (void) closedir (dp);
          }
          else
              perror ("Couldn't open the directory");
      
          return str;
      }