Skip to content

Instantly share code, notes, and snippets.

@Yoticc
Created October 11, 2023 12:31
Show Gist options
  • Save Yoticc/87e178f346b7e86af9239c4e0f2e5770 to your computer and use it in GitHub Desktop.
Save Yoticc/87e178f346b7e86af9239c4e0f2e5770 to your computer and use it in GitHub Desktop.
C# alternative for "freopen("CONIN$")"
void Main()
{
AllocConsole();
SetupIn();
SetupOut();
Console.WriteLine("Output something");
var input = Console.ReadLine();
}
void SetupIn() => Console.SetIn(CreateInStream()); // freopen("CONOUT$", "w", stdout);
void SetupOut() => Console.SetOut(CreateOutStream()); // freopen("CONIN$", "r", stdin);
StreamWriter CreateOutStream() => new(CreateFileStream("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, FileAccess.Write)) { AutoFlush = true };
StreamReader CreateInStream() => new(CreateFileStream("CONIN$", GENERIC_READ, FILE_SHARE_READ, FileAccess.Read));
FileStream CreateFileStream(string name, uint desAccess, uint shareMode, FileAccess fileAccess)
{
var fileHandle = CreateFileW(name, desAccess, shareMode, 0, (uint)FileMode.Open, (uint)FileAttributes.Normal, 0);
var file = new SafeFileHandle(fileHandle, true);
return !file.IsInvalid ? new FileStream(file, fileAccess) : null;
}
const uint
GENERIC_WRITE = 0x40000000,
GENERIC_READ = 0x80000000,
FILE_SHARE_READ = 1,
FILE_SHARE_WRITE = 2;
const string kernel = "kernel32";
[DllImport(kernel, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern
nint CreateFileW(string fileName, uint desAccess, uint shareMode, nint securityAttb, uint creationDispose, uint flagsAndAttb, nint templateFile);
[DllImport(kernel)] [return: MarshalAs(UnmanagedType.Bool)] public static extern
bool AllocConsole();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment