How to delete a non empty directory in C or C++? Is there any function? rmdir only deletes empty directory. Please provide a way without using any external library.
Also tell me how to delete a file in C or C++?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You want to write a function (a recursive function is easiest, but can easily run out of stack space on deep directories) that will enumerate the children of a directory. If you find a child that is a directory, you recurse on that. Otherwise, you delete the files inside. When you are done, the directory is empty and you can remove it via the syscall.
To enumerate directories on Unix, you can use
opendir(),readdir(), andclosedir(). To remove you usermdir()on an empty directory (i.e. at the end of your function, after deleting the children) andunlink()on a file. Note that on many systems thed_typemember instruct direntis not supported; on these platforms, you will have to usestat()andS_ISDIR(stat.st_mode)to determine if a given path is a directory.On Windows, you will use
FindFirstFile()/FindNextFile()to enumerate,RemoveDirectory()on empty directories, andDeleteFile()to remove files.Here’s an example that might work on Unix (completely untested):