写程序时用到一个删除目录的功能,但C库函数提供的_rmdir() 只能删除空目录,在网上搜索了一下也没得到满意的答案,于是就自己写了个小程序,递归地删除目录下的内容,最后删除目录本身。
主要用到了以下函数:
_access(); /*判断目录是否存在*/
_chdir(); /*改变当前工作目录*/
_findfirst(); /*在目录下查找第一个文件或文件夹*/
_findnext(); /*在目录下查找下一个文件或文件夹*/
_findclose(); /*结束一个查找操作*/
remove(); /*删除一个文件*/
_rmdir(); /*删除一个空目录*/
代码如下(下面的程序将直接删除文件或文件夹,而不是移到回收站,虽然已经本人多次测试,但为了安全起见,准备调试下面程序的朋友请做好备份,或将删除文件和文件夹的函数替换为输出文件名):
- #include "io.h"
- #include "direct.h"
- #include <iostream>
- using std::cin;
- using std::cerr;
- using std::cout;
- using std::endl;
- #include <string>
- using std::string;
- void empty_directory(/*const char* dirName*/);
- int main()
- {
- string path;
- cout << "Input name of the directory you want to remove: ";
- cin >> path;
- if (_access(path.c_str(), 06) == -1)
- {
- cerr << "error: directory does not exist." << endl;
- exit(-1);
- }
- if (path.at(path.length() - 1) != '\\')
- {
- path += '\\';
- }
- _chdir(path.c_str());
- empty_directory();
- _chdir(path.c_str());
- _chdir("..");
- _rmdir(path.c_str());
- return 0;
- }
- void empty_directory( /*const char* dirName*/ )
- {
- _finddata_t fileinfo;
- memset(&fileinfo, 0x0, sizeof(fileinfo));
- intptr_t iFind = _findfirst("*", &fileinfo);
- if (iFind == -1)
- {
- cerr << "error: _findfirst failed." << endl;
- return;
- }
- /* process the first item */
- if (fileinfo.name[0] != '.')
- {
- if ((fileinfo.attrib & _A_SUBDIR) != 0)
- {
- /* process directory */
- _chdir(fileinfo.name);
- empty_directory(/*fileinfo.name*/);
- _chdir("..");
- _rmdir(fileinfo.name);
- }
- else
- {
- /* process file */
- remove(fileinfo.name);
- }
- }
- while (_findnext(iFind, &fileinfo) == 0)
- {
- if (fileinfo.name[0] != '.')
- {
- if ((fileinfo.attrib & _A_SUBDIR) != 0)
- {
- /* process directory */
- _chdir(fileinfo.name);
- empty_directory(/*fileinfo.name*/);
- _chdir("..");
- _rmdir(fileinfo.name);
- }
- else
- {
- /* process file */
- remove(fileinfo.name);
- }
- }
- }
- _findclose(iFind);
- }
程序在vs2008下测试正常。
转载:http://blog.csdn.net/selina6874/article/details/6784766