Mistake of opening of a file having a name in cp1251.

MGW via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Apr 2 23:26:52 PDT 2015


Greetings to all!

I work on Windows with cp1251 and I have a mistake in the program:

import std.stdio;
int main (string [] args) {
     string nameFile = `«Ёлки с объектами №876».txt`;
     File f = File (nameFile, "w");
     f.writeln ("Greetings!");
     return 0;
}

This mistake of a kind:

std.exception. ErrnoException at std\stdio.d (372): Cannot open file 
` ┬л╨Б ╨╗╨║╨╕ ╨Ю ╨▒
╤К ╨╡╨║╤ 876 ┬╗. txt ' in mode ` w ' (Invalid argument)

For correction of this mistake I had to change a file std\stdio.d,
having added in it function fromUtf8toAnsiW (). The piece of an 
source code
of a file std\stdio.d with changes is presented more low.

private FILE* fopen(in char[] name, in char[] mode = "r") 
@trusted // nothrow @nogc - mgw отключено из-за fromUtf8toAnsiW
{
     import std.internal.cstring : tempCString;

     version(Windows)
     {
		// 02.04.2015 8:31:19 repair for dmd 2.067.0
		wchar* fromUtf8toAnsiW(in char[] s, uint codePage = 0) @trusted 
  {
			import std.c.windows.windows: WideCharToMultiByte, 
GetLastError;
			import std.windows.syserror: sysErrorString;
			import std.conv: to;
			char[] result, rez;	int readLen; auto ws = std.utf.toUTF16z(s);
			result.length = WideCharToMultiByte(codePage, 0, ws, -1, null, 
0, null, null);
			if (result.length)	{
				readLen = WideCharToMultiByte(codePage, 0, ws, -1, 
result.ptr,	to!int(result.length), null, null);
				for(int i; i != result.length; i++) { rez ~= result[i]; rez 
~= 0; } rez ~= 0; rez ~= 0;
			}
			if (!readLen || readLen != result.length)	{
				throw new Exception("Couldn't convert string: " ~ 
sysErrorString(GetLastError()));
			}
			return cast(wchar*)rez.ptr;
		}

         import std.internal.cstring : tempCStringW;
         // return _wfopen(name.tempCStringW(), 
mode.tempCStringW());
         return _wfopen(fromUtf8toAnsiW(name), 
mode.tempCStringW());
     }
     else version(Posix)
     {
         import core.sys.posix.stdio : fopen;
         return fopen(name.tempCString(), mode.tempCString());
     }
     else
     {
         return .fopen(name.tempCString(), mode.tempCString());
     }
}

With the given correction all works correctly.

Question.
Whether correctly such change from the point of view of 
programming canons on D ?


More information about the Digitalmars-d-learn mailing list