c - 内存访问冲突 readdir

标签 c removeall

您好,我必须编写 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/

相关文章:

java - ArrayList.removeAll(Collection<>) 关心重复项吗?

javafx - 无法清除 ObservableList 中的所有项目(元素)

c - 为什么在 C 编程中 scanf ("%d", &number) 结果 'a' 为 29?

c - 查询 The GNU C Reference Manual 中的一段代码

c - 在链表中获取段错误

c++ - 如何使用字符串(字符数组)初始化 char 指针而不是整数数组的 int 指针?

c - 双指针作为函数的数组

Hadoop 从 Cloudera 中删除挂载点文件夹

java - 如何删除所有 View 并重新添加?

jquery - 删除该父级的内容