【问题标题】:Opening a text file with fstream but filename characters are not in ASCII [duplicate]使用 fstream 打开文本文件,但文件名字符不是 ASCII [重复]
【发布时间】:2011-04-20 08:53:32
【问题描述】:

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

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

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

有没有办法可以打开具有这些名称的文件。

谢谢 维韦克

【问题讨论】:

  • @Ephphatha 看,这个问题的描述正确。它不是重复的。
  • 看起来和我一模一样,但我还是会回答的。
  • 文件名本质上是系统特定的,并且取决于底层文件系统支持的内容。语言无法定义。

标签: c++


【解决方案1】:

从问题How to open an std::fstream with a unicode filename@jalf 中指出,C++ 标准库不支持 unicode,但有一个接受 wchar_t 数组的 windows 扩展。

您将能够通过在 fstream 对象上创建或调用 open 以 wchar_t 数组作为参数来在 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...

【讨论】:

  • 我需要这个和 fstream。我已经浏览了与此相关的上一篇文章。
  • 我不确定你在问什么抱歉,我提供的示例适用于 Windows 系统并使用 fstream。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多