473,698 Members | 2,972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

binary output to stdout in Windows

I have a C program that writes binary output to stdout,
which works fine in Unix/Linux. But when someone else
compiled and ran it in Windows, every time the program
emitted a 0x0A, Windows interpreted it as an lf, and
preceded it with a spurious 0x0D cr. Cute. Is there
some way I can freopen() (so to speak) stdout in binary
mode under Windows so that doesn't happen? Hopefully,
the fix would be portable, so it could compile and
execute under Unix, too, with no ill effects.
Thanks,
--
John Forkosh ( mailto: j@f.com where j=john and f=forkosh )
Nov 14 '05 #1
8 6078
try _setmode()

Search _setmode (third hit) in

http://msdn.microsoft.com/library

with respect,
Toni Uusitalo

"John Forkosh" <jo**@SeeSigFor Address.invalid .com> wrote in message
news:c0******** **@reader2.pani x.com...
I have a C program that writes binary output to stdout,
which works fine in Unix/Linux. But when someone else
compiled and ran it in Windows, every time the program
emitted a 0x0A, Windows interpreted it as an lf, and
preceded it with a spurious 0x0D cr. Cute. Is there
some way I can freopen() (so to speak) stdout in binary
mode under Windows so that doesn't happen? Hopefully,
the fix would be portable, so it could compile and
execute under Unix, too, with no ill effects.
Thanks,
--
John Forkosh ( mailto: j@f.com where j=john and f=forkosh )

Nov 14 '05 #2
In article <news:c0******* ***@reader2.pan ix.com>
John Forkosh <jo**@SeeSigFor Address.invalid .com> writes:
I have a C program that writes binary output to stdout,
which works fine in Unix/Linux. But when someone else
compiled and ran it in Windows, every time the program
emitted a 0x0A, Windows interpreted it as an lf, and
preceded it with a spurious 0x0D cr. Cute. Is there
some way I can freopen() (so to speak) stdout in binary
mode under Windows so that doesn't happen? Hopefully,
the fix would be portable, so it could compile and
execute under Unix, too, with no ill effects.


In C99 there is a way (I think -- it is not in my draft; I should
probably buy the actual C99 .pdf file):

FILE *result;
...
result = freopen(NULL, "wb", stdout);

Here, "result" should compare equal to stdout on success, and NULL
on failure.

Unfortunately, passing NULL to freopen() in C89 results in undefined
behavior -- and in many real implementations , a crash and/or
core-dump.

You might use the theoretically-portable freopen() method as your
"standard" technique that is rarely used today but more frequently
tomorrow, and meanwhile resort to some nonstandard method(s) for
existing implementations . (I have no idea what those might be
beyond something spelled something like "setmode".)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #3
Chris Torek <no****@torek.n et> wrote:
John Forkosh <jo**@SeeSigFor Address.invalid .com> writes:
<snip>
[How to transparently write binary data to stdout.]
In C99 there is a way (I think -- it is not in my draft; I should
probably buy the actual C99 .pdf file):

FILE *result;
...
result = freopen(NULL, "wb", stdout);

Here, "result" should compare equal to stdout on success, and NULL
on failure.

Unfortunatel y, passing NULL to freopen() in C89 results in undefined
behavior -- and in many real implementations , a crash and/or
core-dump.


Unfortunately, even in C99 this is not as portable as
one might think (or wish):

C99 7.19.5.4#3:
---------------
If filename is a null pointer, the freopen function
attempts to change the mode of the stream to that
specified by mode, as if the name of the file
currently associated with the stream had been used.
It is implementation-defined which changes of mode
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^
are permitted (if any), and under what circumstances.
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^

FWIW, on at least one popular platform this C99 program:

#include <stdio.h>
int main( void )
{
FILE *fp = freopen( NULL, "wb", stdout );
fputs( fp ? "Ok.\n" : "Dang!\n", stderr );
return 0;
}

prints 'Dang!' and leaves stdout closed! :-(

Conclusion: the only portable way (I can think of)
to write binary data from a C program is writing it
to a file explicitly fopen()ed in "[w|a][+]b" mode.

<snip>

Regards
--
Irrwahn Grausewitz (ir*******@free net.de)
welcome to clc : http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
acllc-c++ faq : http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #4

"Chris Torek" <no****@torek.n et> wrote in message
news:c0******** *@enews3.newsgu y.com...
In article <news:c0******* ***@reader2.pan ix.com>
John Forkosh <jo**@SeeSigFor Address.invalid .com> writes:
I have a C program that writes binary output to stdout,
which works fine in Unix/Linux. But when someone else
compiled and ran it in Windows, every time the program
emitted a 0x0A, Windows interpreted it as an lf, and
preceded it with a spurious 0x0D cr. Cute. Is there
some way I can freopen() (so to speak) stdout in binary
mode under Windows so that doesn't happen? Hopefully,
the fix would be portable, so it could compile and
execute under Unix, too, with no ill effects.
You might use the theoretically-portable freopen() method as your
"standard" technique that is rarely used today but more frequently
tomorrow, and meanwhile resort to some nonstandard method(s) for
existing implementations . (I have no idea what those might be
beyond something spelled something like "setmode".)
--


I didn't know freopen could be used to change file mode in the newer
standard.
But I guess this doesn't help the OP in the present time. Luckily all
programmers
love to write tons of #ifdefs ;-)

I'll use "theoretica lly-portable" phrase next to "theoretica l performance"
numbers next time I advertise some piece of s**tware I've written ;-)

with respect,
Toni Uusitalo

Nov 14 '05 #5
Toni Uusitalo <to************ **@pandot.nu> wrote:
: "John Forkosh" wrote:
: > I have a C program that writes binary output to stdout,
: > which works fine in Unix/Linux. But when someone else
: > compiled and ran it in Windows, every time the program
: > emitted a 0x0A, Windows interpreted it as an lf, and
: > preceded it with a spurious 0x0D cr. Cute. Is there
: > some way I can freopen() (so to speak) stdout in binary
: > mode under Windows so that doesn't happen? Hopefully,
: > the fix would be portable, so it could compile and
: > execute under Unix, too, with no ill effects. Thanks,

: try _setmode()
: Search _setmode (third hit) in
: http://msdn.microsoft.com/library
: --
: Toni Uusitalo

Thanks, Toni. As suggested, I modified code to include,
essentially,
if ( _setmode(_filen o(stdout), _O_BINARY)
== -1 ) ; /* error */
guarded by an ugly #ifdef to determine whether or not
it's a Windows compilation.
Mailed fix to user who replied that he hasn't had time
to try it yet, but is "sure it will work" -- poor, naive soul!
I'll post another short followup when outcome is known,
especially if my cynical, Murphy's Law attitude bears its
usual fruits.

Chris Torek wrote:
: In C99 there is a way (I think -- it is not in my draft; I should
: probably buy the actual C99 .pdf file):
: FILE *result;
: result = freopen(NULL, "wb", stdout);
: Here, "result" should compare equal to stdout on success, and NULL
: on failure. Unfortunately, passing NULL to freopen() in C89 results
: in undefined behavior -- and in many real implementations , a crash
: and/or core-dump.
: You might use the theoretically-portable freopen() method as your
: "standard" technique that is rarely used today but more frequently
: tomorrow, and meanwhile resort to some nonstandard method(s) for
: existing implementations . (I have no idea what those might be
: beyond something spelled something like "setmode".)
: --
: Chris Torek, Wind River Systems, http://web.torek.net/torek/index.html

-- and --

Irrwahn Grausewitz <ir*******@free net.de> wrote:
: Unfortunately, even in C99 this is not as portable as
: one might think (or wish):
: C99 7.19.5.4#3:
: If filename is a null pointer, the freopen function
: attempts to change the mode of the stream to that
: specified by mode, as if the name of the file
: currently associated with the stream had been used.
: It is implementation-defined which changes of mode
: are permitted (if any), and under what circumstances.
: ^^^^^^^^^^^
: FWIW, on at least one popular platform this C99 program:
: #include <stdio.h>
: int main( void )
: { FILE *fp = freopen( NULL, "wb", stdout );
: fputs( fp ? "Ok.\n" : "Dang!\n", stderr );
: return 0; }
: prints 'Dang!' and leaves stdout closed! :-(
: Conclusion: the only portable way (I can think of)
: to write binary data from a C program is writing it
: to a file explicitly fopen()ed in "[w|a][+]b" mode.
: --
: Irrwahn Grausewitz (ir*******@free net.de)

Thanks Chris and Irrwahn. For the time being, at least,
I used Toni's suggestion since a non-portable solution
is better than a portable non-solution.
Can't write to a file because program is used as a
cgi, and therefore has to emit bytes directly to stdout
so Apache (or whatever) can pick them up.

Thanks again for help, guys,
--
John Forkosh ( mailto: j@f.com where j=john and f=forkosh )
Nov 14 '05 #6
In <ac************ *************** *****@4ax.com> Irrwahn Grausewitz <ir*******@free net.de> writes:
FWIW, on at least one popular platform this C99 program:

#include <stdio.h>
int main( void )
{
FILE *fp = freopen( NULL, "wb", stdout );
fputs( fp ? "Ok.\n" : "Dang!\n", stderr );
return 0;
}

prints 'Dang!' and leaves stdout closed! :-(
If this platform doesn't claim C99-conformance, the program invokes
undefined behaviour, anyway. As Chris mentioned, this is not a C89
feature.
Conclusion: the only portable way (I can think of)
to write binary data from a C program is writing it
to a file explicitly fopen()ed in "[w|a][+]b" mode.


What is preventing a conforming implementation from having an fopen()
that fails for all these modes?

Being a QoI issue, it is reasonable to expect conforming C99
implementations to allow mode changes when freopen() is invoked this way.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #7
In <c0*********@en ews3.newsguy.co m> Chris Torek <no****@torek.n et> writes:
In C99 there is a way (I think -- it is not in my draft; I should
probably buy the actual C99 .pdf file):


For this particular purpose, it is enough to upgrade to the last public
draft, N869:

[#3] If filename is a null pointer, the freopen function
attempts to change the mode of the stream to that specified
by mode, as if the name of the file currently associated
with the stream had been used. It is implementation-defined
which changes of mode are permitted (if any), and under what
circumstances.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #8
John Forkosh <jo**@SeeSigFor Address.invalid .com> wrote:
: Toni Uusitalo <to************ **@pandot.nu> wrote:
: : "John Forkosh" wrote:
: : > I have a C program that writes binary output to stdout,
: : > which works fine in Unix/Linux. But when someone else
: : > compiled and ran it in Windows, every time the program
: : > emitted a 0x0A, Windows interpreted it as an lf, and
: : > preceded it with a spurious 0x0D cr. Cute. Is there
: : > some way I can freopen() (so to speak) stdout in binary
: : > mode under Windows so that doesn't happen? Hopefully,
: : > the fix would be portable, so it could compile and
: : > execute under Unix, too, with no ill effects. Thanks,

: : try _setmode()
: : Search _setmode (third hit) in
: : http://msdn.microsoft.com/library
: : --
: : Toni Uusitalo

: Thanks, Toni. As suggested, I modified code to include,
: essentially,
: if ( _setmode(_filen o(stdout), _O_BINARY)
: == -1 ) ; /* error */
: guarded by an ugly #ifdef to determine whether or not
: it's a Windows compilation.
: Mailed fix to user who replied that he hasn't had time
: to try it yet, but is "sure it will work" -- poor, naive soul!
: I'll post another short followup when outcome is known,

User reports fix works exactly as intended.
Thanks again,
--
John Forkosh ( mailto: j@f.com where j=john and f=forkosh )
Nov 14 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
7591
by: Paul Watson | last post by:
How can I write lines to stdout on a Windows machine without having '\n' expanded to '\r\n'. I need to do this on Python 2.1 and 2.3+. I see the msvcrt.setmode function. Is this my only path? Is it valid to change the mode of stdout? The file.newlines is not writable.
7
2385
by: Bix | last post by:
As this is my very first post, I'd like to give thanks to all who support this with their help. Hopefully, this question hasn't been answered (too many times) before... If anyone could explain this behavior, I'd greatly appreciate it. I'm leaving the example at the bottom. There is a variable, fmt, within the test0 function which can be changed from -1 (pickle.HIGHEST_PROTOCOL) to 0 (ascii). The behavior between the two pickle...
5
6721
by: gof | last post by:
I'm pretty new to C++, and this seemingly simple thing is driving me crazy. I'm trying to write a CGI script to serve images on the fly. CGI requires the content to be sent through standard output, but since cout and printf convert LF line endings to CRLF (I'm on Windows), the resulting image ends up being corrupt. Is there ANY way to get around this? It seems writing CGI scripts in C++ on Windows is pretty much impossible. Here's an...
4
25663
by: Rouben Rostamian | last post by:
Consider the following demo program: #include <stdio.h> int main(void) { unsigned char c; for (c=0; c<15; c++) putchar(c);
5
7493
by: Charles F McDevitt | last post by:
I'm converting some old programs that use old iostreams. In one program, the program is using cout to output to the stdout stream. Part way through, the program wants to put some binary data out, and changes the iostream to binary like this: cout << "this is text" << eol; binary(cout); cout << "this is binary" << eol; text(cout); cout << "back to text mode" << eol;
40
2172
by: rayw | last post by:
I've been trying to write a program that converts an entered number into its binary representation using three different techniques - bit shifting, mod 2, and itoa.. However, I'm getting 'snow blind', and can't get the non-ISO itoa to work as I'd like. The snow blindness makes me think it's me, and not the function! The idea of the program was to be able to change #define I_TYPE char to any scalar type, re-compile, and then play. ...
4
3896
by: Barry | last post by:
Hi, guys Basiclly, it is automated testing system. There is a main python script that handles the testing campagin. This main script will call another script that will in turn runs a few hundered individual python scripts. Here is my problem. I want to log everything displayed in the screen after I start the main python script. Things include unhandled exceptions , message from print statement and other sources.
24
2808
by: Bartc | last post by:
The stdin/stdout files of C seem to be always in Text mode. Is there any way of running a C program so that these (but especially stdout) are in Binary mode instead? (I'm in the process of wrapping a different language around C which doesn't want the concept of text and binary files. But if I output a string such as "ONE\nTWO\n", this will behave differently between stdout and a regular (binary) file. Examples on my OS:
27
2960
by: CarlosMB | last post by:
Hello, I am writing code that uses a DLL which is supposed to print to console some useful information but for some reason it is not doing so. The environment is a bit complex to explain but here it goes: - I am using a C library called SYMPHONY, which I compiled myself. When using that
0
8611
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9170
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9031
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8904
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8876
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5867
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.