Binary Files


Text files are not the only type of flat files you can use. You can also use binary files. Binary files are still flat files; however, they are in basic binary format rather than ASCII. Remember that everything in a computer is binary (1’s and 0’s). The binary format has each file stored in a byte-by-byte format. This produces some odd-looking results if you try to view binary files like plain text. For example, an integer might be represented by four separate characters, because it occupies four bytes. You might ask why anyone would want to open a binary file. There are a number of reasons, the most prominent being that there is still old data stored this way. However, one useful thing you can do is to open any file in binary mode and count the bytes in it, to see how big the file is. This next example demonstrates this.

Example 6.5

Step 1: Enter the following code in your favorite text editor.

#include <iostream> using namespace std;   #include <fstream> int main ()  {  long start,end;  // Recall from chapter one, that a long is simply  // large integers  ifstream myfile ("test.txt", ios::in|ios::binary);  start = myfile.tellg();  myfile.seekg (0, ios::end);  end = myfile.tellg();  myfile.close();  cout << "size of " << "test.txt";  cout << " is " << (end-start) << " bytes.\n";  return 0; }

Step 2: Compile this code.

Step 3: Run the executable. You should see something like Figure 6.2.

click to expand
Figure 6.2: Binary file size.

This code is relatively straightforward, let’s take a look. To begin with, we open a file just as we would normally do, except we open it as binary, with the following line of code.

ifstream myfile ("test.txt", ios::in|ios::binary);

Next, we retrieve the beginning point for the file.

start = myfile.tellg(); 

And then we get the endpoint of the file, by first moving to the end of the file then getting the position.

myfile.seekg (0, ios::end); end = myfile.tellg();

The first line says to start at the 0 byte/character and search until the end of the file. If you wanted to start at another point such as the 10th character or byte, you could simply put in a 10 where the 0 is. Now it’s just a matter of subtracting the beginning point from the endpoint and that’s how many bytes of data the file has in it. The process is not particularly complicated. However, you might be wondering about the ios you keep seeing. That is simply C++’s way of saying “input/output stream.”




C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net