开发者

Opening a text file with fstream but filename characters are not in ASCII [duplicate]

开发者 https://www.devze.com 2023-02-27 00:52 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to open an st开发者_运维问答d::fstream (ofstream or ifstream) with a unicode filename ?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to open an st开发者_运维问答d::fstream (ofstream or ifstream) with a unicode filename ?

I want to open a text file using c++ fstream but the character used for the filename didn't fall in ASCII character set. for example :

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

Is there way exist in through which I could open file with such names.

Thanks Vivek


From the question How to open an std::fstream with a unicode filename @jalf notes that the C++ standard library is not unicode aware, but there is a windows extension that accepts wchar_t arrays.

You will be able to open a file on a windows platform by creating or calling open on an fstream object with a wchar_t array as the argument.

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

Both of the above will call the wchar_t* version of the appropriate functions, as the L prefix on a string indicates that it is to be treated as a unicode string.

Edit: Here is a complete example that should compile and run. I created a file on my computer called δ»Wüste.txt with the contents This is a test. I then compiled and ran the following code in the same directory.

#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;
}

The output is:

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


On Windows, you can use long strings:

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

精彩评论

暂无评论...
验证码 换一张
取 消