【问题标题】:Memory Access Violation readdir [duplicate]内存访问冲突readdir [重复]
【发布时间】:2018-09-29 20:29:25
【问题描述】:

您好,我必须在 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;
}

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

【问题讨论】:

  • 你必须检查opendir()返回非NULL指针。
  • 您有 多个 错误,其中大多数(如果不是全部)与指针有关。例如,dp 指向哪里? opendir 成功了吗?

标签: c removeall


【解决方案1】:

你没有为你的字符串分配内存。

要“创建 中的字符串,您需要请求一些存储空间以将其放入,您可以通过定义如下所示的数组来实现

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()的文档,同时阅读关于的简单完整教程。

【讨论】:

  • 是的,这很有帮助,但你知道为什么递归(删除文件)永远不会结束吗?
  • 因为您没有跳过'.' 目录,而是一遍又一遍地进入它。
猜你喜欢
  • 1970-01-01
  • 2012-05-22
  • 2019-10-24
  • 2017-11-05
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-16
相关资源
最近更新 更多