Skip to content

Commit

Permalink
#137: bin/base64: windows: ensure stdout is binary-clean
Browse files Browse the repository at this point in the history
In some Windows environments, `stdout' automatically changes newlines to
CRLFs. This is bad when encoding, because the encoded file will have the
wrong line terminators, and it is bad when decoding, because the decoded
data might get mangled.

It turns out that the best method to make `stdout' binary-clean is with:

  _setmode(1, _O_BINARY);

Equivalent uses of `freopen()' and `SetConsoleMode()' do not always work
because they can run into permissions errors, whereas it seems that
`_setmode()' does not have that problem.

Resolves #137.
  • Loading branch information
aklomp committed Jan 29, 2024
1 parent 8f3212f commit 26443b7
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions bin/base64.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
# define MINGW
#endif

// Test for Windows.
#if defined(_WIN32) || defined(_WIN64)
# define WIN
#endif

// Decide if the writev(2) system call needs to be emulated as a series of
// write(2) calls. At least MinGW does not support writev(2).
#ifdef MINGW
Expand All @@ -24,6 +29,12 @@
#include <errno.h>
#include <limits.h>

// Include Windows-specific headers.
#ifdef WIN
# include <io.h>
# include <fcntl.h>
#endif

#include "../include/libbase64.h"

// Size of the buffer for the "raw" (not base64-encoded) data in bytes.
Expand Down Expand Up @@ -638,6 +649,15 @@ main (int argc, char **argv)
return 1;
}

#ifdef WIN

// On Windows, ensure that stdout is binary-clean, and does not
// silently convert newlines to CRLFs. This seems to be the portable
// way to do it; freopen() and SetConsoleMode() occasionally result in
// permission errors, whereas this always seems to work.
_setmode(1, _O_BINARY);
#endif

// Encode or decode the input based on the user's choice.
const bool ret = config.decode
? decode(&config, &buf)
Expand Down

0 comments on commit 26443b7

Please sign in to comment.