【问题标题】:Printing LPCWSTR string to file将 LPCWSTR 字符串打印到文件
【发布时间】:2014-03-01 07:31:57
【问题描述】:

我写了一个程序,我将文件名列表存储在一个结构中,我必须将其打印在一个文件中。文件名的类型在 LPCWSTR 中,并且遇到问题,如果使用 ofstream 类,则只打印文件名的地址.我也尝试使用 wofstream 但它导致“读取位置时访问冲突”。我搜索了网站以缓解此问题但无法获得适当的解决方案。许多人建议尝试使用 wctombs 功能但我不明白如何将 LPCWSTR 打印到文件中很有帮助。请帮助我缓解这种情况。

我的代码是这样的,

 ofstream out;
 out.open("List.txt",ios::out | ios::app);
  for(int i=0;i<disks[data]->filesSize;i++)
                    {
                        //printf("\n%ws",disks[data]->lFiles[i].FileName);
                        //wstring ws = disks[data]->fFiles[i].FileName;
                        out <<disks[data]->fFiles[i].FileName << "\n";
                    }
                    out.close();

【问题讨论】:

  • 我不认为std::owfstream,标准输出文件流的wchar_t版本并实现为basic_ofstream&lt;wchar_t&gt;,会给你带来你想要的吗?从技术上讲,“正确”的事情是转换,但这对你来说可能就足够了。
  • @WhozCraig..请告诉我如何转换或类型转换或其他什么?

标签: c++ ostream lpcwstr


【解决方案1】:

如果你确实想转换,那么这应该可以工作(我无法让 wcstombs 工作):

#include <fstream>
#include <string>
#include <windows.h>

int main()
{
    std::fstream File("File.txt", std::ios::out);

    if (File.is_open())
    {
        std::wstring str = L"русский консоли";

        std::string result = std::string();
        result.resize(WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, NULL, 0, 0, 0));
        char* ptr = &result[0];
        WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, ptr, result.size(), 0, 0);
        File << result;
    }
}

使用原始字符串(因为有评论抱怨我使用了std::wstring):

#include <fstream>
#include <windows.h>

int main()
{
    std::fstream File("File.txt", std::ios::out);

    if (File.is_open())
    {
        LPCWSTR wstr = L"русский консоли";
        LPCSTR result = NULL;

        int len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, 0, 0);

        if (len > 0)
        {
            result = new char[len + 1];
            if (result)
            {
                int resLen = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, &result[0], len, 0, 0);

                if (resLen == len)
                {
                    File.write(result, len);
                }

                delete[] result;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 2015-01-16
    • 1970-01-01
    • 2014-01-04
    • 2018-09-27
    相关资源
    最近更新 更多