Home >Backend Development >C++ >Is Console Input Redirected?
Detecting Console Input Redirection
Many console applications need to adapt their behavior depending on whether input comes from the keyboard or a file. This article shows how to reliably distinguish between these input sources.
Method 1: Using the Windows FileType() API (P/Invoke)
A robust solution involves leveraging the Windows FileType()
API function through P/Invoke. This C# helper class simplifies the process:
<code class="language-csharp">using System; using System.Runtime.InteropServices; public static class ConsoleEx { public static bool IsOutputRedirected => FileType.Char != GetFileType(GetStdHandle(StdHandle.Stdout)); public static bool IsInputRedirected => FileType.Char != GetFileType(GetStdHandle(StdHandle.Stdin)); public static bool IsErrorRedirected => FileType.Char != GetFileType(GetStdHandle(StdHandle.Stderr)); // P/Invoke declarations: private enum FileType { Unknown, Disk, Char, Pipe }; private enum StdHandle { Stdin = -10, Stdout = -11, Stderr = -12 }; [DllImport("kernel32.dll")] private static extern FileType GetFileType(IntPtr hdl); [DllImport("kernel32.dll")] private static extern IntPtr GetStdHandle(StdHandle std); }</code>
Implementation:
Check for input redirection using the ConsoleEx
class:
<code class="language-csharp">bool isInputRedirected = ConsoleEx.IsInputRedirected;</code>
Method 2: .NET 4.5 and Later
.NET 4.5 and later versions provide built-in methods within the Console
class. For newer applications, these are the preferred approach:
Console.IsOutputRedirected
Console.IsInputRedirected
Console.IsErrorRedirected
These offer a simpler, more direct way to determine redirection status. Choose the method that best suits your .NET framework version.
The above is the detailed content of Is Console Input Redirected?. For more information, please follow other related articles on the PHP Chinese website!