如何使用 glob 函数?

How to use the glob function?

我想为自定义 shell 实现 globbing,但是当我尝试使用该函数时出现段错误。

#include <stdlib.h>
#include <string.h>
#include <glob.h>

/* Convert a wildcard pattern into a list of blank-separated
   filenames which match the wildcard.  */

char * glob_pattern(char *wildcard)
{
  char *gfilename;
  size_t cnt, length;
  glob_t glob_results;
  char **p;

  glob(wildcard, GLOB_NOCHECK, 0, &glob_results);

  /* How much space do we need?  */
  for (p = glob_results.gl_pathv, cnt = glob_results.gl_pathc;
       cnt; p++, cnt--)
    length += strlen(*p) + 1;

  /* Allocate the space and generate the list.  */
  gfilename = (char *) calloc(length, sizeof(char));
  for (p = glob_results.gl_pathv, cnt = glob_results.gl_pathc;
       cnt; p++, cnt--)
    {
      strcat(gfilename, *p);
      if (cnt > 1)
        strcat(gfilename, " ");
    }

  globfree(&glob_results);
  return gfilename;
}

如果我尝试使用上述代码,则会出现段错误。为什么不起作用?

问题是因为 length 在您将路径长度累积到其中之前未初始化。

length = 0; <-- should initialize length here
for (p = glob_results.gl_pathv, cnt = glob_results.gl_pathc; cnt; p++, cnt--)
    length += strlen(*p) + 1;

另外,不要强制转换calloc的return值,sizeof(char)在标准中定义为1。所以最好只做:

gfilename = calloc(length, 1);

gfilename = malloc(length);