Redirecting standard streams in Windows

Alexander Zhirov azhirov1991 at gmail.com
Tue Jul 18 23:52:06 UTC 2023


On Tuesday, 18 July 2023 at 22:09:40 UTC, Adam D Ruppe wrote:
> You need to use WriteFile when it is redirected, which you can 
> detect with GetFileType to see if it is a character device or 
> not.

The redirection issue has been resolved. Another one has now 
emerged. Since I have unicode, I need to write 2 bytes each, 
which is exactly what happens. In this regard, incorrect output 
to the file. How to convert it otherwise? Or does it not depend 
on the output?

```d
import core.sys.windows.windows;
import std.stdio;
import std.utf;

void main() {
     wstring str = "Это тестовый текст";
     HANDLE h_stderr = GetStdHandle(STD_ERROR_HANDLE);
     switch (GetFileType(h_stderr)) {
         case FILE_TYPE_CHAR:
             WriteConsoleW(h_stderr, str.ptr, 
cast(DWORD)str.length, NULL, NULL);
             break;
         case FILE_TYPE_PIPE:
             auto utf_str = str.toUTF8;
             WriteFile(h_stderr, utf_str.ptr, 
cast(DWORD)utf_str.length, NULL, NULL);
             break;
         default:
     }
}
```

output:

```sh
PS C:\dlang\test> dmd.exe .\app.d
PS C:\dlang\test> .\app.exe
Это тестовый текст
PS C:\dlang\test> .\app.exe 2> .\stderr.txt
PS C:\dlang\test> cat .\stderr.txt
.\app.exe : ╨н╤В╨╛ ╤В╨╡╤Б╤В╨╛╨▓╤Л╨╣ ╤В╨╡╨║╤Б╤В
строка:1 знак:1
+ .\app.exe 2> .\stderr.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : NotSpecified: (╨н╤В╨╛ 
╤В╨╡╤Б╤В╨╛╨▓╤Л╨╣ ╤В╨╡╨║╤Б╤В:String) [], RemoteException
     + FullyQualifiedErrorId : NativeCommandError


```



More information about the Digitalmars-d-learn mailing list