I want to implement this myself and I come up something like this:
/* DIR *opendir(const char *name);
*
* Open a directory stream to argv[1] and make sure
* it's a readable and valid (directory) */
if ((dip = opendir(argv[1])) == NULL)
{
perror("opendir");
return 0;
}
printf("Directory stream is now open\n");
/* struct dirent *readdir(DIR *dir);
*
* Read in the files from argv[1] and print */
while ((dit = readdir(dip)) != NULL)
{
printf("\n%s", dit->d_name);
remove(dit->d_name);
}
I am guessing I have to start delete things from the deepest level and then go up, but now it seems readdir does not give me that order.
Please help, thanks!
You have to recurse all the way down to the lower levels first, as in the following pseudo code:
That’s it really, this guarantees that all lower directories and files are deleted before you attempt to remove the parent.
Since
itemis likely to be just the current component of the directory, you may need to construct a full name using, for example,strcpy/strcat: