1

I want to create a file with the given location path that contains Unicode characters. I've tried the below code but after compiling my code no file is generated.

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;
phuclv
  • 37,963
  • 15
  • 156
  • 475
Md. Zakir Hossain
  • 1,082
  • 11
  • 24
  • It says "wchar_t do not equal Unicode." You can check the documentation https://stackoverflow.com/questions/3010739/how-to-use-unicode-in-c/3019339 – Yunus Temurlenk Jan 14 '20 at 08:40

1 Answers1

4

"D:/File/ফোল্ডার/filename.txt" is a string literal of type const char [N]. So (wchar_t)"D:/File/ফোল্ডার/filename.txt" cast a const char * pointer to wchar_t which doesn't do what you want

Besides wchar_t path declare a single wide character and not a string of wchar_t

You need to use the L prefix to get a string literal of wchar_t, and declare a pointer instead:

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;

Also note that the default path separator on Windows is backslash \ and not slash /, although for many APIs they behave the same.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
phuclv
  • 37,963
  • 15
  • 156
  • 475
  • Thanks, after applied your suggestion file has been created but no content written inside the file. How i do that? – Md. Zakir Hossain Jan 14 '20 at 09:01
  • 2
    `std::wstring dat(L"Data to Write");` - here's a hint. If you have to explicitly cast, you're probably doing it wrong. :) – selbie Jan 14 '20 at 09:03
  • of course the data must also be in `wchar_t*` like this `file << L"Data to Write"` – phuclv Jan 14 '20 at 09:03
  • my mistake, i've already applied and file created with content but one more help needed, if i use parameter/variable then how i use `L` before variable? say std::string ss = "D:/File/ফোল্ডার/filename.txt"; const wchar_t* path = L???; – Md. Zakir Hossain Jan 14 '20 at 09:08
  • 1
    @Md.ZakirHossain you need to [convert `std::string` to `std::wstring`](https://stackoverflow.com/q/2573834/995714). But try to use `std::wstring` from the start to avoid the cost of runtime conversion – phuclv Jan 14 '20 at 09:13