gpt4 book ai didi

c - 如何使用 glob 函数?

转载 作者:太空宇宙 更新时间:2023-11-04 03:30:49 27 4
gpt4 key购买 nike

我想为自定义 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的返回值不要强制转换,sizeof(char)在标准中定义为1。所以最好这样做:

gfilename = calloc(length, 1);

gfilename = malloc(length);

关于c - 如何使用 glob 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36757641/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com