1 获取某个目录下的下的所有文件
2 删除相应目录
#include <iostream>
#include<Windows.h>
#include<atlstr.h>
#include<vector>
#include<string>
using namespace std;
//根据文件夹路径得到文件夹下的图片名称
vector<string> getAllFiles(string dirpath)
{
dirpath = dirpath + "\\";
//string dir_spec = dirpath + "/*.jpg";
string dir_spec = dirpath + "/*";
WIN32_FIND_DATAA f;
HANDLE h = FindFirstFileA(dir_spec.c_str(), &f);
vector<string> filenames;
filenames.clear();
if (h != INVALID_HANDLE_VALUE)
{
do
{
filenames.push_back(string(f.cFileName));
} while (FindNextFileA(h, &f));
}
FindClose(h);
return filenames;
}
void deleteAllFiles(string path)
{
vector<string> file_name;
file_name = getAllFiles(path);
if (file_name.size() == 2)
return;
for (int i = 2; i<file_name.size(); ++i)
{
string sub_str = ".jpg";
string::size_type idx;
idx = file_name[i].find(sub_str);
if ( idx != string::npos)
{
string pic_str = path + "\\" + file_name[i];
std::cout << pic_str << std::endl;
remove(pic_str.c_str());
}
else
{
string file_str = path + "\\" + file_name[i];
if (getAllFiles(file_str).size() == 2)
{
CString file_str(file_str.c_str());
RemoveDirectory(file_str);
}
else
{
deleteAllFiles(file_str);
CString file_str(file_str.c_str());
RemoveDirectory(file_str);
}
}
}
}
int main()
{
string path = "C:\\Users\\frank\\Desktop\\test";
deleteAllFiles(path);
system("pause");
return 0;
}
const char *c_str();
c_str()函数返回一个指向正规C字符串的指针常量, 内容与本string串相同.
这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
string 转为CString:
string file_str;
CString file_str(file_str.c_str());