Should I set stdout in BINARY mode, explicitly?
by Sanmayce from LinuxQuestions.org on (#4XVYV)
Should I set stdout in BINARY mode, explicitly?
I am writing a fragment where I should dump my data to stdout, both under Windows and *nix:
The superb NAF tool has this portable code already:
Code:#ifdef __MINGW32__
if (_setmode(_fileno(stdout), O_BINARY) == -1) { die("can't set output stream to binary mode\n"); }
#else
if (!freopen(NULL, "wb", stdout)) { die("can't set output stream to binary mode\n"); }
#endifHowever, I need to know whether the *nix part can be omitted as in my current code:
Code:// 2020-Jan-13 [
// https://stackoverflow.com/questions/16888339/what-is-the-simplest-way-to-write-to-stdout-in-binary-mode
// The line below crashes under Windows XP?!
//if (!freopen(NULL, "wb", stdout)) { printf("Can't set output stream to binary mode.\n"); exit(23); }
//https://stackoverflow.com/questions/23107609/is-there-way-to-set-stdout-to-binary-mode
//#ifdef _WIN32
#if defined(_WIN32_ENVIRONMENT_)
setmode(fileno(stdout),O_BINARY);
setmode(fileno(stdin),O_BINARY);
#endif
//https://github.com/KirillKryukov/naf/blob/4e737ce8852f5bde2ca5fb31ee6d2b9c34f1a5cb/unnaf/src/files.c#L29
if (TargetSize <= OneMB) {
fwrite(TargetBlock, 1, TargetSize, stdout);
} else {
for (DoOffset = 0; DoOffset+OneMB < TargetSize; DoOffset=DoOffset+OneMB) {
fwrite(TargetBlock+DoOffset, 1, OneMB, stdout);
}
//if (DoOffset+OneMB >= TargetSize) {
fwrite(TargetBlock+DoOffset, 1, TargetSize - DoOffset, stdout);
}
fclose(stdout);
// 2020-Jan-13 ]


I am writing a fragment where I should dump my data to stdout, both under Windows and *nix:
The superb NAF tool has this portable code already:
Code:#ifdef __MINGW32__
if (_setmode(_fileno(stdout), O_BINARY) == -1) { die("can't set output stream to binary mode\n"); }
#else
if (!freopen(NULL, "wb", stdout)) { die("can't set output stream to binary mode\n"); }
#endifHowever, I need to know whether the *nix part can be omitted as in my current code:
Code:// 2020-Jan-13 [
// https://stackoverflow.com/questions/16888339/what-is-the-simplest-way-to-write-to-stdout-in-binary-mode
// The line below crashes under Windows XP?!
//if (!freopen(NULL, "wb", stdout)) { printf("Can't set output stream to binary mode.\n"); exit(23); }
//https://stackoverflow.com/questions/23107609/is-there-way-to-set-stdout-to-binary-mode
//#ifdef _WIN32
#if defined(_WIN32_ENVIRONMENT_)
setmode(fileno(stdout),O_BINARY);
setmode(fileno(stdin),O_BINARY);
#endif
//https://github.com/KirillKryukov/naf/blob/4e737ce8852f5bde2ca5fb31ee6d2b9c34f1a5cb/unnaf/src/files.c#L29
if (TargetSize <= OneMB) {
fwrite(TargetBlock, 1, TargetSize, stdout);
} else {
for (DoOffset = 0; DoOffset+OneMB < TargetSize; DoOffset=DoOffset+OneMB) {
fwrite(TargetBlock+DoOffset, 1, OneMB, stdout);
}
//if (DoOffset+OneMB >= TargetSize) {
fwrite(TargetBlock+DoOffset, 1, TargetSize - DoOffset, stdout);
}
fclose(stdout);
// 2020-Jan-13 ]