【问题标题】:Create file in a specific Unicode path在特定的 Unicode 路径中创建文件
【发布时间】:2020-04-30 22:52:23
【问题描述】:

我想用给定的位置路径创建一个包含 Unicode 字符的文件。我试过下面的代码,但是编译我的代码后没有生成文件。

wchar_t path = (wchar_t)"D:/File/ফোল্ডার/filename.txt";
std::wofstream file(&path); //open in constructor
std::wstring dat((wchar_t*)"Data to Write");
file << dat;

【问题讨论】:

标签: c++ windows file unicode widechar


【解决方案1】:

"D:/File/ফোল্ডার/filename.txt"string literal 类型的 const char [N]。所以(wchar_t)"D:/File/ফোল্ডার/filename.txt"const char * 指向wchar_t 的指针不能满足你的要求

除了wchar_t path 声明一个单个宽字符而不是wchar_t字符串

您需要使用L 前缀来获取wchar_t 的字符串字面量,并改为声明一个指针:

const wchar_t* path = L"D:/File/ফোল্ডার/filename.txt";
std::wofstream file(path); //open in constructor
std::wstring dat(L"Data to Write");
file << dat;

另请注意,Windows 上的默认路径分隔符是反斜杠 \,而不是斜杠 /,尽管对于许多 API,它们的行为相同。

【讨论】:

  • 谢谢,应用后您的建议文件已创建,但文件中没有写入内容。我是怎么做到的?
  • std::wstring dat(L"Data to Write"); - 这里有一个提示。如果你必须明确地强制转换,你可能做错了。 :)
  • 当然数据也必须在wchar_t*这样file &lt;&lt; L"Data to Write"
  • 我的错误,我已经申请并创建了包含内容的文件,但还需要一个帮助,如果我使用参数/变量,那么我如何在变量之前使用L?说 std::string ss = "D:/File/ফোল্ডার/filename.txt"; const wchar_t* path = L???;
  • @Md.ZakirHossain 你需要convert std::string to std::wstring。但是尽量一开始就使用std::wstring,避免运行时转换的成本
猜你喜欢
  • 2021-07-06
  • 2020-08-10
  • 2019-12-28
  • 2020-09-20
  • 2020-05-14
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
相关资源
最近更新 更多