使用fstream打开文本文件但文件名字符不是ASCII

时间:2011-04-20 08:53:32

标签: c++

  

可能重复:
  How to open an std::fstream (ofstream or ifstream) with a unicode filename ?

我想使用c ++ fstream打开一个文本文件,但用于文件名的字符并不属于ASCII字符集。 例如:

 fstream fileHandle;
 fileHandle.open("δ»Wüste.txt");

是否存在我可以用这样的名字打开文件的方式。

由于 维维克

2 个答案:

答案 0 :(得分:2)

从问题How to open an std::fstream with a unicode filename @jalf注意到C ++标准库不能识别unicode,但是有一个接受wchar_t数组的Windows扩展。

您可以通过在wstream_t数组作为参数的fstream对象上创建或调用open来打开Windows平台上的文件。

fstream fileHandle(L"δ»Wüste.txt");
fileHandle.open(L"δ»Wüste.txt");

以上两者都会调用相应函数的wchar_t *版本,因为字符串上的L前缀表示它将被视为unicode字符串。

编辑:这是一个应该编译和运行的完整示例。我在我的计算机上创建了一个名为δ»Wüste.txt的文件,内容为This is a test.然后我编译并在同一目录中运行以下代码。

#include <fstream>
#include <iostream>
#include <string>

int main(int, char**)
{
  std::fstream fileHandle(L"δ»Wüste.txt", std::ios::in|std::ios::out);

  std::string text;
  std::getline(fileHandle, text);
  std::cout << text << std::endl;

  system("pause");

  return 0;
}

输出结果为:

This is a test.
Press any key to continue...

答案 1 :(得分:1)

在Windows上,您可以使用长字符串:

fileHandle.open(L"δ»Wüste.txt");
相关问题