1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Programming Tutorial - C++ Strings

By , About.com Guide

2 of 9

Binary Files in C++

A binary file is a file of any length that holds bytes with values in the range 0 to 0xff. (0 to 255). These bytes have no other meaning. In a text file a value of 13 means carriage return, 10 means line feed, 26 means end of file. Software reading or writing text files has to deal with line ends. In Linux these are just separated by line feeds but Windows uses carriage returns and line feeds.

In modern terms we can call a binary file a stream of bytes and more modern languages tend to work with streams rather than files. The important part is the data rather than where it came from! This example shows that you can write text to a binary file.

Download Example 1
.

RandomAccess ra( filename) ;
if ( ra.OpenWrite() )
  {
    if (!ra.Write( mytext ))
cout << "Failed to write to file " << filename << endl;
    ra.Close() ;
  }
else
    cout << "Failed to open " << filename << " fior writing " << endl;

This uses the class RandomAccess to open a binary file for writing, then writes a string into it. The RandomAccess class uses a FILE to do the main work. It's opened in "wb " mode (refer to the C tutorial for more information on that) and then writes the text to the file. It's actually writing sequentially though it could be made to write anywhere in the file. However, because the "wb" mode creates the file (or deletes all content of an existing file) there isn't much point.

If you try to move the file pointer to a place in the file that doesn't exist, the results aren't defined. It might create a file to fill in the gaps or it might just not work. That depends upon the operating system so if you want to write software that is portable don't use it!

On the next page : How Example 1 Works

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Binary Files in C++

©2009 About.com, a part of The New York Times Company.

All rights reserved.