Boost logo

Boost Users :

From: Benjamin Collins (ben.collins_at_[hidden])
Date: 2007-10-14 15:58:35


I'm trying to use a stream and open/close the underlying device on the
fly. Here's my test code:

#include <iostream>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/iostreams/stream.hpp>
namespace io = boost::iostreams;

namespace {
  const uint32_t block_size = io::mapped_file_source::alignment();
}

bool test1()
{
  io::mapped_file_params mfp("rand.bin");
  mfp.mode = std::ios_base::in | std::ios_base::binary;
  mfp.length = block_size;

  io::mapped_file mf(mfp);
  io::stream<io::mapped_file> in(mf);

  int blocks = fs::file_size("rand.bin")/block_size;
  if (fs::file_size("rand.bin") % block_size)
    ++blocks;

  for (int i=0;i<blocks;++i)
      {
        in->close();
        mfp.offset = block_size*i;

      std::cout << "mapping bytes ["
                << block_size*i << " - " << block_size*(i+1) - 1
                << "]\n";
      in->open(mfp);
      in.clear();

      std::cout << "stream is in state: [ ";
      if(in.rdstate() | std::ios::goodbit)
        std::cout << "good ";
      if(in.rdstate() | std::ios::badbit)
        std::cout << "bad ";
      if(in.rdstate() | std::ios::failbit)
        std::cout << "fail ";
      if(in.rdstate() | std::ios::eofbit)
        std::cout << "eof ";
      std::cout << "]\n";

      int count=0;
      char x;
      while(!in.eof())
        {
          if(io::stream<io::mapped_file>::traits_type::eof() == (x = in.get()))
            throw std::runtime_error("unexpected eof");
          std::cout << '.';
          ++count;
        }
      if(0==count)
        throw std::runtime_error("unable to read characters in this map");
      else
        std::cout << count << "bytes read.\n";
    }
}

If you don't like to see code in email, see here: http://pastebin.com/m40e9432b

This program prints the following:
------------------------------------------------
mapping bytes [0 - 4095]
stream is in state: [ bad fail eof ]
terminate called after throwing an instance of 'std::runtime_error'
  what(): unexpected eof
Aborted

So what gives? Why isn't boost::iostreams::stream clearing its state properly?

-- 
Benjamin A. Collins <ben.collins_at_[hidden]>
http://bloggoergosum.us

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net