Search code examples
cremoveall

Memory Access Violation readdir


Hello i have to write in c (linux) function to remove all file from directory i cannot use remove function or execl only unlink and rmdir.

i used 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;
}

but i get Memory Access Violation thx


Solution

  • You did not allocate memory for your strings.

    To "create" a string in you need to request some storage to put it in, you can do it by defining an array like the following

    char string[SIZE];
    

    where SIZE is a reasonably large number.

    This is perhaps what you wanted, but you still need to check errors everywhere

    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
    }
    

    Note: Read the documentation of snprintf() and also read a simple and complete tutorial about .