How to Perform I/O With Binary Files in C++

Computer users are familiar with the ASCII or Unicode symbols on their screens. In reality, behind the scenes, computers process binary numbers and store files in binary data format. This format is unreadable by humans. The powerful fstream C++ class simplifies input/output operations. By the time you finish this article, you'll know how to use fstream to write and read binary data to and from a file.

Things You'll Need

  • Intermediate to advanced C++
  • C++ compiler with IDE, such as Visual Studio 2008
Show More

Instructions

    • 1

      Tell the preprocessor to introduce the C++ fstream class in your program, as follows:

      #include < fstream.h >

    • 2

      Become acquainted with the C++ format of the fstream constructor. It takes two parameters. The first, of type char*, is the name of the file. The second is a series of flags, separated by a vertical, that give the operating system extra information about the operation. Don't worry about the flags right now:

      fstream fs("fname", ios::in | ios::binary | ios::app);

    • 3

      Create or open a file called "data.txt." Set it for data write. Append the data to the end of the file:

      fstream fs("data.txt", ios::in);// Attempt to open it for reading.

      if (!fs){

      fs.open("data.txt", ios::out | ios::binary | ios::app); // File doesn't exist; create a new one.

      }

      else{

      fs.close(); // File exists; close and reopen for write.

      fs.open("data.txt", ios::out | ios::binary | ios::app);

      }

    • 4

      Write the first 10 integers into the file and close the file:

      for(int i = 0; i < 10; i++){

      fs.write(reinterpret_cast(&i), sizeof(int));

      }

      fs.close();

    • 5

      Open the text file using Windows Explorer. You should see the numerals 0 through 9 in a row. Even though the data was entered in binary format, your text editor is busy translating it to Unicode or ASCII numerical values.

    • 6

      Reopen the file and prepare it for reading. Display its content to the standard output:

      fs.open("data.txt", ios::in | ios::binary);

      if(!fs){

      throw SomeFileException;

      }

      int num;

      for(int i = 0; i < 10; i++){

      fs.read(reinterpret_cast(&num),sizeof(int));

      cout << num << endl;

      }

Tips & Warnings

  • These are basic I/O operations. More advanced ones include seeking and dereferencing the file pointer.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured