bangbangpowpow
bangbangpowpow

Reputation: 13

Unlink Not Removing File

Trying to understand why unlink isn't working (not removing the file) in my code down below. The only thing I can imagine is that the program thinks I'm still interacting with the file so its not actually unlinking it since its still in use. The code is meant to be a copy of "rm"

void directorySearch(const char *dName)
{
        DIR *dir;
        struct dirent *ent;
        if ((dir = opendir (dName)) != NULL)
        {
                while ((ent = readdir (dir)) != NULL)
                {

                        if ( ent->d_type!=DT_DIR)
                        {
                                //Where the crazy happens
                                printf ("%s\n", ent->d_name);
                                char path[PATH_MAX];
                                const char * d_name = ent->d_name;
                                unlink(path);
                        }
                        if ( ent->d_type==DT_DIR && strcmp(ent->d_name, ".")!= 0 && strcmp(ent->d_name, "..") != 0)
                        {
                                int path_length;
                                char path[PATH_MAX];
                                const char * d_name = ent->d_name;

                                path_length = snprintf (path, PATH_MAX, "%s/%s", dName, d_name);

                                directorySearch(path);
                        }
                }
                closedir (dir);
        }
        else
        {
                cout << "error with "<< dName<< endl;
        }
}

Edited with unlink instead of remove, although both don't work...

Upvotes: 1

Views: 1898

Answers (1)

Leonard
Leonard

Reputation: 13787

You have declared your path variable, but not actually copied anything into that variable. So that's a problem. Also, as a matter of course you should examine the return value from unlink, and if less than zero, examine errno to determine the exact nature of the error. (Typically permissions on no such file.)

Upvotes: 1

Related Questions