How to use basic_filebuf with element type other than char?

Say I want to read the contents of a file using basic_filebuf . I have a type boost::uintmax_t whose size is 8 bytes . I am trying to write the following:

 typedef basic_filebuf<uintmax_t> file; typedef istreambuf_iterator<uintmax_t> ifile; file f; vector<uintmax_t> data, buf(2); f.open("test.txt", std::ios::in | std::ios::binary); f.pubsetbuf(&buf[0], 1024); ifile start(&f), end; while(start != end) { data.push_back(*start); start++; } 

The problem is that some of the bytes are read, others not. For example, suppose there are 9 bytes in file number 1-9 :

 |1|2|3|4|5|6|7|8|9| 

When I run the above code, only one element is returned in data , which contains 4 bytes from only the original data in f :

 [0|0|0|0|4|3|2|1] --> only element in [data] 

What am I doing wrong? This is my first time using basic_filebuf directly, although I know how to use filebuf .

+4
source share
2 answers

Basic_filebuf deals with the "internal" type of char and the "external". "External" is the contents of the file and is always bytes. "Internal" is the template parameter and is the one used in its interface with the program. To convert between the two, basic_filebuf uses the codecvt face of its locale.

So, if you want him to write directly the bytes that you give him, you have two options:

  • use a "degenerate" codecvt that only executes between "internal" and "external" encodings instead of trying to perform the conversion.
  • use basic_filebuf, don't forget to use the "classic" language and do a char listing yourself
+4
source

Objects of type basic_filebuf are type char * created with an internal buffer, regardless of char_type, specified by the type parameter Elem. This means that a Unicode String (containing wchar_t characters) is converted to ANSI String (containing char characters) before it is written to the internal buffer. To save Unicode strings in a buffer, create a new buffer of type wchar_t and set it using the basic_streambuf :: pubsetbuf () method.

from http://msdn.microsoft.com/en-us/library/tzf8k3z8(VS.80).aspx

0
source

All Articles