使用 std::filesystem 输出作为 LPCWSTR [英] Using std::filesystem output as LPCWSTR

查看:29
本文介绍了使用 std::filesystem 输出作为 LPCWSTR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个程序,它递归地列出某个目录中的所有文件,并使用 WinINet 将每个文件分别上传到 FTP 服务器.我遇到的问题是在 FtpPutFile() 函数中使用 filesystem::path::filename 因为需要 LPCWSTR.转换它(或以某种方式按原样使用)的最佳和最简单的方法是什么?

I'm making a program which recursively lists all files in a certain directory and uploads each file separately to an FTP server using WinINet. The problem I'm encountering is using filesystem::path::filename in the FtpPutFile() function because a LPCWSTR is needed. Whats the best and easiest way to convert it (or somehow use it as is)?

    std::string path = "C:\\Programs";
    for (const auto & entry : std::experimental::filesystem::recursive_directory_iterator(path))
        FtpPutFile(hIConnect, entry.path().filename(), entry.path().filename(), FTP_TRANSFER_TYPE_BINARY, 0);

我得到的错误是:不存在从const std::experimental::filesystem::v1::path"到LPCWSTR"的合适转换函数

The error I get is: no suitable conversion function from "const std::experimental::filesystem::v1::path" to "LPCWSTR" exists

这是一个对我有用的解决方案,遵循 Lightness 解决方案:

Here is a solution that worked for me, by following Lightness solution:

    std::string path = "C:\\Programs";
    for (const auto & entry : std::experimental::filesystem::recursive_directory_iterator(path))
        FtpPutFile(hIConnect, entry.path().wstring().c_str(), entry.path().filename().wstring().c_str(), FTP_TRANSFER_TYPE_BINARY, 0);

推荐答案

LPCWSTR 是微软对const wchar_t* 类型filesystem 路径方便地有一个 wstring() 成员函数.您可能还记得,C++ 字符串也允许您通过 c_str() 访问它们的字符缓冲区.

LPCWSTR is Microsoft's obfuscation of the const wchar_t* type, and filesystem paths conveniently have a wstring() member function. As you may recall, C++ strings give you access to their character buffer, too, via c_str().

因此,entry.path().filename().wstring().c_str() 是您可以使用的 LPCWSTR(呃!).小心立即使用它,或者将 wstring() 的结果存储在某个地方,只要您需要 LPCWSTR 继续存在,因为 wstring() 按值返回,您不需要悬空指针.

So, entry.path().filename().wstring().c_str() is a LPCWSTR you can use (ugh!). Be careful to use that immediately, or store the result of wstring() somewhere for as long as you need the LPCWSTR to survive, because wstring() returns by value and you don't want a dangling pointer.

// Untested, but a logical adaptation of your code
const std::string path = "C:\\Programs";
std::experimental::filesystem::recursive_directory_iterator it(path);
for (const auto& entry : it)
{
    const std::wstring filename = entry.path().filename().wstring();

    FtpPutFile(
       hIConnect,
       filename.c_str(),
       filename.c_str(),
       FTP_TRANSFER_TYPE_BINARY,
       0
    );
}

这篇关于使用 std::filesystem 输出作为 LPCWSTR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆