From 86512f67f64fff81ba07245b8e28fa3f065b3618 Mon Sep 17 00:00:00 2001
From: Jason Hood <jadoxa@yahoo.com.au>
Date: Thu, 23 Aug 2018 17:02:47 +1000
Subject: [PATCH] Fix -e et al when redirecting to NUL

Redirecting ansicon to NUL would still write to the console, as NUL is
regarded as a character device.  Export IsConsoleHandle and use that
instead of _isatty.
---
 acrt.def   | 1 +
 ansicon.c  | 5 ++++-
 ansicon.h  | 1 +
 readme.txt | 4 +++-
 4 files changed, 9 insertions(+), 2 deletions(-)

diff --git a/acrt.def b/acrt.def
index b595ab2..bd69158 100644
--- a/acrt.def
+++ b/acrt.def
@@ -1,6 +1,7 @@
 EXPORTS
 __iob_func
 _fileno
+_get_osfhandle
 _iob
 _isatty
 _setmode
diff --git a/ansicon.c b/ansicon.c
index 5af6689..1399f20 100644
--- a/ansicon.c
+++ b/ansicon.c
@@ -92,6 +92,9 @@
 
   v1.84, 7 May, 2018:
     import the DLL.
+
+  v1.85, 22 August, 2018:
+    use IsConsoleHandle for my_fputws, to distinguish NUL.
 */
 
 #define PDATE L"22 August, 2018"
@@ -140,7 +143,7 @@ static HANDLE hConOut;
 // heck, DIY.
 int my_fputws( const wchar_t* s, FILE* f )
 {
-  if (_isatty( _fileno( f ) ))
+  if (IsConsoleHandle( (HANDLE)_get_osfhandle( _fileno( f ) ) ))
   {
     DWORD written;
     WriteConsole( hConOut, s, (DWORD)wcslen( s ), &written, NULL );
diff --git a/ansicon.h b/ansicon.h
index f6d80ff..f670098 100644
--- a/ansicon.h
+++ b/ansicon.h
@@ -89,6 +89,7 @@ typedef struct IMAGE_COR20_HEADER
 #define EXTERN __declspec(dllexport) extern
 #endif
 
+EXTERN BOOL IsConsoleHandle( HANDLE );
 EXTERN int ProcessType( LPPROCESS_INFORMATION, PBYTE*, BOOL* );
 BOOL   Wow64Process( HANDLE );
 
diff --git a/readme.txt b/readme.txt
index f25e88f..8e2b007 100644
--- a/readme.txt
+++ b/readme.txt
@@ -340,7 +340,8 @@ Version History
     Legend: + added, - bug-fixed, * changed.
 
     1.85 - 22 August, 2018:
-    - fix wrap issues with a buffer bigger than the window.
+    - fix wrap issues with a buffer bigger than the window;
+    - fix -e et al when redirecting to NUL.
 
     1.84 - 11 May, 2018:
     - close the flush handles on detach;
@@ -605,6 +606,7 @@ Acknowledgments
     Vincent Fatica for pointing out \e[K was not right.
     Nat Kuhn for pointing out the problem with report cursor position.
     Michel Kempeneers for discovering the buffer wrap issue.
+    Jean-Luc Gautier for pointing out the problem with redirecting -e to NUL.
 
     Thiadmer Riemersma for the nearest color algorithm.