Skip to content

"failed to write to console" exception on Windows when writing to NUL-redirected file handle #2080

Description

@nickhutchinson

On Windows, fmtlib can throw an exception when writing to a FILE* handle that's been redirected to the NUL device (Windows' equivalent of /dev/null).

This occurs when fmtlib is in unicode mode -- e.g. you're building with Visual Studio with FMT_UNICODE defined, or with clang -- because the WriteConsoleW() function fmtlib calls will fail if it's passed a file handle that's not actually a console. Unfortunately on Windows _isatty() is not a robust test for determining if a given fd is a console.

I would suggest calling GetConsoleMode() instead (or perhaps in addition to the _isatty check, depending on your level of paranoia!). This is how the UCRT itself determine whether it should call WriteConsoleW -- if you have the Windows SDK installed, you can check the source at Source/<version>/ucrt/lowio/write.cpp.

To repro:

#include <cstdio>

#define FMT_UNICODE 1
#include <fmt/core.h>

int main() {
  fmt::print("crash!\n"); // throws exception if stdout has been redirected to NUL

  FILE* fp = std::fopen("NUL", "w");
  fmt::print(fp, "crash!\n"); // throws exception
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions