内存访问违规readdir

时间:2018-04-19 10:55:00

标签: 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;
}

但我得到了内存访问冲突 THX

1 个答案:

答案 0 :(得分: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()的文档,并阅读有关的简单完整的教程。

相关问题