① 弹窗选中文件件,获取文件夹 路径
TCHAR szBuffer[MAX_PATH] = { 0 };
BROWSEINFO bi;
ZeroMemory(&bi, sizeof(BROWSEINFO));
bi.hwndOwner = NULL;
bi.pszDisplayName = szBuffer;
bi.lpszTitle = _T("从下面选文件夹目录:");
bi.ulFlags = BIF_RETURNFSANCESTORS;
LPITEMIDLIST idl = SHBrowseForFolder(&bi);
if (NULL == idl)
{
return -1;
}
SHGetPathFromIDList(idl, szBuffer);
int len = wcslen(szBuffer);
char flag = szBuffer[len - 5];
//第一次调用确认转换后单字节字符串的长度,用于开辟空间
int pSize = WideCharToMultiByte(CP_OEMCP, 0, szBuffer, wcslen(szBuffer), NULL, 0, NULL, NULL);
char* path_chars = new char[pSize + 1];
//第二次调用将双字节字符串转换成单字节字符串
WideCharToMultiByte(CP_OEMCP, 0, szBuffer, wcslen(szBuffer), path_chars, pSize, NULL, NULL);
path_chars[pSize] = '\0';
path_chars存放文件夹路径,此处大概需要include的头文件如下:
#include"Shlobj.h"
#include<tchar.h>
② 遍历选定文件夹下的指定类型的文件,这里封装成函数
// Search the folder to get all specified files
void getFiles(const string& directoryName, vector<string>& filenames, string filetype, bool addDirectoryName = true)
{
struct _finddata_t s_file;
string str = directoryName + "\\*.*";
intptr_t h_file = _findfirst(str.c_str(), &s_file);
if (h_file != static_cast<intptr_t>(-1.0))
{
do
{
if (addDirectoryName)
filenames.push_back(directoryName + "\\" + s_file.name);
else
filenames.push_back((string)s_file.name);
string temp = filenames.back();
temp = temp.substr(temp.length() - filetype.length(), filetype.length());
if (temp != filetype) filenames.pop_back();
} while (_findnext(h_file, &s_file) == 0);
}
_findclose(h_file);
}
需要的头文件
#include<string> 等等
文件列表存放在string类型的vector中
③ plus 显示程序当前目录的 小函数
void showWorkPath() {
char *buffer;
//也可以将buffer作为输出参数
if ((buffer = _getcwd(NULL, 0)) == NULL)
{
perror("getcwd error");
}
else
{
printf("%s\n", buffer);
free(buffer);
}
}
需要的头文件
#include <stdio.h> //用到c的输出,懒得改了
#include <direct.h>
④ 调用举例
int main()
{
TCHAR szBuffer[MAX_PATH] = { 0 };
BROWSEINFO bi;
ZeroMemory(&bi, sizeof(BROWSEINFO));
bi.hwndOwner = NULL;
bi.pszDisplayName = szBuffer;
bi.lpszTitle = _T("从下面选文件夹目录:");
bi.ulFlags = BIF_RETURNFSANCESTORS;
LPITEMIDLIST idl = SHBrowseForFolder(&bi);
if (NULL == idl)
{
return -1;
}
SHGetPathFromIDList(idl, szBuffer);
int len = wcslen(szBuffer);
char flag = szBuffer[len - 5];
//第一次调用确认转换后单字节字符串的长度,用于开辟空间
int pSize = WideCharToMultiByte(CP_OEMCP, 0, szBuffer, wcslen(szBuffer), NULL, 0, NULL, NULL);
char* path_chars = new char[pSize + 1];
//第二次调用将双字节字符串转换成单字节字符串
WideCharToMultiByte(CP_OEMCP, 0, szBuffer, wcslen(szBuffer), path_chars, pSize, NULL, NULL);
path_chars[pSize] = '\0';
vector<string> bin_files;
getFiles(path_chars, bin_files, ".bin");
for (int i = 0; i < bin_files.size(); i++) {
//perform operation to each file
}
return 1;
}