gpt4 book ai didi

c - 内存访问冲突 readdir

转载 作者:行者123 更新时间:2023-11-30 16:32:56 26 4
gpt4 key购买 nike

您好,我必须编写 c (linux) 函数来从目录中删除所有文件,我无法使用删除函数或 execl 只能取消链接和 rmdir。

我使用了readdir:

    int removefile( char *file)
{
struct dirent * entry;
DIR *dir;
char *p;
char *d;
char *tmp;
dir = opendir(file);
errno =0;
strcpy( d, file );//kopiowanie file do p
strcat( d, "/" );//dodawanie /
strcpy(tmp,d);//kopiowanie d do tmp
strcpy(p,d); //kopiowanie d do p


while((entry=readdir(dir)) !=NULL)
{
if(entry->d_type==DT_REG)
{
strcat(d,entry->d_name);
int a=unlink(d);
strcpy(d,tmp);
}
else if(entry->d_type==DT_DIR)
{
strcat(p,entry->d_name);
int b=removefile(p);
int c=rmdir(p);
strcpy(p,tmp);
}
}

closedir(dir);
return 0;
}

但我遇到内存访问冲突谢谢

最佳答案

您没有为字符串分配内存。

中“创建”字符串你需要请求一些存储来放入它,你可以通过定义一个数组来实现,如下所示

char string[SIZE];

其中 SIZE 是一个相当大的数字。

这也许是您想要的,但您仍然需要检查各处的错误

int removefile(const char *const dirpath)
{
struct dirent *entry;
DIR *dir;
dir = opendir(dirpath);
if (dir == NULL)
return -1;
while ((entry = readdir(dir)) != NULL) {
char path[256];
// Build the path string
snprintf(path, sizeof(path), "%s/%s", dirpath, entry->d_name);
if (entry->d_type == DT_REG) {
unlink(path);
} else if (entry->d_type == DT_DIR) {
// Recurse into the directory
removefile(path);
// Remove the directory
rmdir(path);
}
}
closedir(dir);
return 0
}

注意:阅读snprintf()的文档,并阅读关于的简单而完整的教程。 .

关于c - 内存访问冲突 readdir,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49919325/

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