squashed.bugaboo
squashed.bugaboo

Reputation: 1356

Binary input/output in C++

I am trying a reasonably simple program to test binary input/output. I am basically writing a file with a header (string) and some data (doubles). The code is as follows:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>


int main() {
   typedef std::ostream_iterator<double> oi_t;
   typedef std::istream_iterator<double> ii_t;
   std::ofstream ofs("data.bin", std::ios::in);
   //-If file doesn't exist, create a new one now
   if(!ofs) {
      ofs.open("data.bin", std::ios::out|std::ios::binary|std::ios::app);
   }
   else {
      ofs.close();
      ofs.open("data.bin", std::ios::out|std::ios::binary|std::ios::app);
   }

   //-Write a header consisting of length of grid subdomain and its name
   ///*
   const std::string grid = "Header";
   unsigned int olen = grid.size();
   ofs.write(reinterpret_cast<const char*>(&olen), sizeof(olen));
   ofs.write(grid.c_str(), olen);
   //*/

   //-Now write the data
   ///*
   std::vector<double> data_out;
   //std::vector<std::pair<int, int> > cell_ids;
   for(int i=0; i<100; ++i) {
      data_out.push_back(5.0*double(i) + 100.0);
   }
   ofs << std::setprecision(4);
   std::copy(data_out.begin(), data_out.end(), oi_t(ofs, " "));
   //*/
   ofs.close();

   //-Now read the binary file; first header then data
   std::ifstream ifs("data.bin", std::ios::binary);
   ///*
   unsigned int ilen;
   ifs.read(reinterpret_cast<char*>(&ilen), sizeof(ilen));
   std::string header;
   if(ilen > 0) {
      char* buf = new char[ilen];
      ifs.read(buf,ilen);
      header.append(buf,ilen);
      delete[] buf;
   }
   std::cout << "Read header: " << header << "\n";
   //*/

   ///*
   std::vector<double> data_in;
   ii_t ii(ifs);
   std::copy(ii, ii_t(), std::back_inserter(data_in));
   std::cout << "Read data size: " << data_in.size() << "\n";
   //*/
   ifs.close();

   //-Check the result
   ///*
   for(int i=0; i < data_out.size(); ++i) {
      std::cout << "Testing input/output element #" << i << " : "
                << data_out[i] << "  " << data_in[i] << "\n";
   }
   std::cout << "Element sizes: " << data_out.size() << "  " << data_in.size() <<  
            "\n";
   //*/
   return 0;
}

The problem is that when I try to write and read (and then print) both the header and the data it fails (I confirmed that it doesn't read the data then, but displays the header correctly). But when I comment out one of the write sections (header and/or data), it displays that part correctly indicating the read worked. I am sure I am not doing the read properly. Perhaps I am missing the usage of seekg somewhere.

Upvotes: 0

Views: 4420

Answers (2)

Curious
Curious

Reputation: 21530

This should work

#include <iostream>
using std::cout;
using std::cerr;
using std::cin;
using std::endl;
#include <fstream>
using std::ifstream;
#include <cstdint>

int main() {

    ifstream fin;
    fin.open("input.dat", std::ios::binary | std::ios::in);
    if (!fin) {
        cerr << "Cannot open file " << "input.dat" << endl;
        exit(1);
    }

    uint8_t input_byte;
    while (fin >> input_byte) {
        cout << "got byte " << input_byte << endl;
    }

    return 0;
}

Upvotes: 0

David Brown
David Brown

Reputation: 13526

The code runs fine for me. However you never check if the file is successfully opened for writing, so it could be silently failing on your system. After you open ofs you should add

if (!ofs) {
    std::cout << "Could not open file for writing" << std::endl;
    return 1;
}

And the same thing after you open ifs

if (!ifs) {
    std::cout << "Could not open file for reading" << std::endl;
    return 1;
}

Or something along those lines. Also I do not understand why you check if the file exists first since you do the same whether it exists or not.

Upvotes: 1

Related Questions