NO

Author Topic: Write wchar string in UTF16-encoded text file  (Read 8633 times)

topin89

  • Guest
Write wchar string in UTF16-encoded text file
« on: March 26, 2012, 03:06:49 PM »
The problem was solved here
http://stackoverflow.com/questions/2427316/writing-to-a-file-in-unicode
as
Code: [Select]
FILE* f;
f = _wfopen(L"test.txt",L"w, ccs=UTF-16LE");
fwprintf(f,L"日本語");
fclose(f);

but it's not working in Pelles C.
Is there some other way?

CommonTater

  • Guest
Re: Write wchar string in UTF16-encoded text file
« Reply #1 on: March 26, 2012, 03:35:11 PM »
The problem was solved here
http://stackoverflow.com/questions/2427316/writing-to-a-file-in-unicode
as
Code: [Select]
FILE* f;
f = _wfopen(L"test.txt",L"w, ccs=UTF-16LE");
fwprintf(f,L"日本語");
fclose(f);

but it's not working in Pelles C.
Is there some other way?

Tried several permutations ... fwprintf(f,L"%ls",... Tried it without the ccs=  and nothing.  It just writes plain old ascii text...
 
Windows default for WCHAR and wchar_t is UTF16LE... so this should work.
 
I'm thinking you should report this as a bug... 
 
The "other way" would be to go into the Windows API and use the CreateFile, ReadFile, WriteFile and CloseFile functions instead... If you really want to stay with C, you could try opening the file with L"wb" then using swprintf() then fwrite() to write the string buffer to disk in binary mode...

 
 
« Last Edit: March 26, 2012, 03:41:48 PM by CommonTater »

topin89

  • Guest
Re: Write wchar string in UTF16-encoded text file
« Reply #2 on: March 26, 2012, 05:20:42 PM »
I don't think it's a bug. Looks like all wide char functions for files just transforms  char to wchar and vise versa when needed. Too bad there is no easy way.

CommonTater

  • Guest
Re: Write wchar string in UTF16-encoded text file
« Reply #3 on: March 26, 2012, 09:10:46 PM »
I don't think it's a bug. Looks like all wide char functions for files just transforms  char to wchar and vise versa when needed. Too bad there is no easy way.

Well, there's a not terribly hard way.

This is untested so be ready to debug...
 
Code: [Select]

wchar_t buffer[128] // size to need
FILE f = wfopen(L"Test.uni",L"wb");
 
swprintf(buffer,128,L"%ls",L"This is a test string");
fwrite(buffer, sizeof(wchar_t), wcslen(buffer),f);
 
fclose(f);

Open the file in a text editor and see if it's written the unicode (wchar) version.
 
It will get easier when printing wide strings instead of literals, there you can just give it the address of the string...
 
« Last Edit: March 26, 2012, 09:13:12 PM by CommonTater »