PRODUCT : Borland C++ NUMBER : 1294 VERSION : 3.x OS : DOS DATE : October 25, 1993 PAGE : 1/2 TITLE : Example of using streams in binary mode. EXAMPLE OF USING STREAMS IN BINARY MODE ======================================= C++ streams are opened as text streams by default. The IOS::BINARY flag allows a stream to be opened in binary mode. Note that opening a stream in binary mode will not change the behavior of the insertion operator, which converts the data element to a string before writing it. The write method is used to output the element in its native form. This is useful when the data does not need to be viewed from an ASCII editor and hard disk space needs to be conserved. For example, 3.14159 requires eight bytes as a string ( including NULL terminator ), while it only requires four bytes as a float. The included file, stream.cpp, shows an example of opening a stream in binary mode, as well as using the write method. Notice that most text editors will display the file bin.txt and text.txt the same. However, the bin.txt file is two bytes smaller because it does not save the CR LF pair, just the CR ( which most text editors will interpret as the CR LF pair ). Do a 'dir *.txt' in the same directory where the stream.cpp example is executed - notice the sizes of the files. //*********************************************************** // Stream.cpp // // This is an example of using binary mode streams. // //*********************************************************** #include #include #include #include int main( void ) { ofstream ofilet ; ofstream ofileb ; float ff = 3.14159 ; ofilet.open( "text.txt" ) ; PRODUCT : Borland C++ NUMBER : 1294 VERSION : 3.x OS : DOS DATE : October 25, 1993 PAGE : 2/2 TITLE : Example of using streams in binary mode. ofileb.open( "bin.txt", ios::binary ) ; // Write to text-mode file ofilet << "Float as String: " << ff << "\n" ; ofilet << "Float as Binary: " ; ofilet.write( (char *) &ff, sizeof( ff ) ) ; ofilet << "\n" ; // Write to binary-mode file ofileb << "Float as String: " << ff << "\n" ; ofileb << "Float as Binary: " ; ofileb.write( (char *) &ff, sizeof( ff ) ) ; ofileb << "\n" ; // Write to screen cout << "Float as String: " << ff << "\n" ; cout << "Float as Binary: " ; cout.write( (char *) &ff, sizeof( ff ) ) ; cout << "( Garbage Expected )\n" ; return 0 ; } // ***** end of stream.cpp ******************************** DISCLAIMER: You have the right to use this technical information subject to the terms of the No-Nonsense License Statement that you received with the Borland product to which this information pertains.