TITLE: using streams for both text/binary output (Newsgroups: comp.lang.c++.moderated, 19 Aug 97) BUCK: Bob Buck > >I have been attempting to use STL binary file io in Visual C++ 5.0. > >Similarly I have attempted to use non-stl C++ io libs on both v5.0 and > >v4.1. None work. All produce ascii files, always. ... > > > >// code ... > > double data; > > data = 534.663; > > > ofstream os; > > os.open("outfile.dat", ios::out | ios::trunc, filebuf::sh_read); > > if( os.is_open() ) > > { > > os << "text" << data; > > os.close(); > > } > >//... > > >outfile is ascii, and displays: "text534.663" SHEK: Rodney Shek wrote: > > Your open mode should be: > > ios::out | ios::trunc | ios::binary. CLAMAGE: Steve Clamage That is not the main problem. By definition, the >> and << operators do formatted text conversion, just like scanf and printf in C stdio. To get binary I/O, use the "read" and "write" member functions. Mixing text and binary output in the same file may have odd results, unless you understand what you are doing. If "os" is opened in binary mode and you write os << "Hello, world\n"; what you get will depend on the particular implementation. On some systems, special conversion is needed for a newline character on output. When that is the case, some systems do the conversion in the stream member functions, and some do it in low-level I/O functions. Thus, depending on the system, the conversion might or might not occur when you write to a binary file. Similarly, if a stream is opened in text mode and you write a binary value using the "write" function, by accident some of the bytes might correspond to characters needing conversion.