Windows API使用(1)——对文件的操作(获取名字或路径)

一、获取文件夹下所有的文件名(路径)

void GetFiles(std::wstring path, std::vector<std::wstring>& files)
{
    WIN32_FIND_DATA FindFileData;
    HANDLE hFind = INVALID_HANDLE_VALUE;
    std::wstring fname = path + L"\\*";
    hFind = FindFirstFile(fname.c_str(), &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE)
    {
        if (hFind)
        {
            ::FindClose(hFind);
        }
        return;
    }
    while (::FindNextFile(hFind, &FindFileData) != 0) {
        if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 && wcscmp(FindFileData.cFileName, L".") == 0 || wcscmp(FindFileData.cFileName, L"..") == 0) {
            continue;
        }
        if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
            std::wstring cur = path;
            cur.append(L"\\");
            std::wstring filename = cur + FindFileData.cFileName;
            files.push_back(filename);
        }
    }
    ::FindClose(hFind);
}

二、创建文件夹

bool createDirectory(const std::wstring& dirPath)
{
#ifdef _WINDOWS
    int res = _wmkdir(dirPath.c_str());
    return (res == 0 || res == 17);
#else
    std::string sPath = UnicodeToUtf8(dirPath);
    return (mkdir(sPath.c_str(), 0777) == 0);
#endif
}

三、获取exe路径

std::wstring getExePath()
{
    wchar_t exeFullPath[MAX_PATH]; // MAX_PATH在WINDEF.h中定义了,等于260
    memset(exeFullPath, 0, MAX_PATH);

    GetModuleFileName(NULL, exeFullPath, MAX_PATH);
    wchar_t *p = /*strrchr*/wcsrchr(exeFullPath, '\\');
    *p = 0x00;
    return exeFullPath;
}

四、获取dll路径

std::wstring getModulePath()
{
    wchar_t dllFullPath[MAX_PATH];
    memset(dllFullPath, 0, MAX_PATH);
    HMODULE hm = NULL;

    if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
        (LPCWSTR)&getModulePath, &hm) == 0)
    {
        int ret = GetLastError();
        return L"";
        // Return or however you want to handle an error.
    }
    if (GetModuleFileName(hm, dllFullPath, MAX_PATH) == 0)
    {
        int ret = GetLastError();
        return L"";
        // Return or however you want to handle an error.
    }
    wchar_t *p = /*strrchr*/wcsrchr(dllFullPath, '\\');
    *p = 0x00;
    return dllFullPath;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值