Discussion:
read does not work with basic_ifstream< unsigned char >
Luciano Montanaro
2006-10-06 10:20:11 UTC
Permalink
Hi all,
while trying to avoid a cast when reading from a file to a buffrer,
I changed the type of the input file from ifstream to basic_ifstream<
unsigned char >, and suddenly read() does not work anymore.

Is this the expected behaviour? and if it is so, why?

This is a small test program that shows the problem:

#include <fstream>
#include <iostream>

using namespace std;

typedef char mytype;
//typedef unsigned char mytype;

int main(int argc, char **argv)
{
basic_ifstream< mytype > in("testfile", ios::binary);

mytype buf[100];
in.read(buf, 100);
cout << in.gcount() << " bytes read." << endl;

in.close();
}

If mytype is char, the program prints "6" (the number of characters in
testfile), if it is defined as unsigned char, it prints out 0.

Thanks for any clarification,
Luciano
John Love-Jensen
2006-10-06 11:38:25 UTC
Permalink
Hi Luciano,

You haven't plumbed up the facet, the locale, and/or the codecvt facilities
for your new stream's base type.

Some C++ compilers give you those things for char, and plumb char up to
locale facilities provided by the OS (e.g., the LC_ALL environment
variable).

Most C++ compilers give you those things for char and wchar_t, and, again,
plumb char and wchar_t up to locale facilities provided by the OS.

I don't know of any C++ compilers that provide you those things for unsigned
char, nor do I know of any OS that provides those facilities for unsigned
char.

Take a look at "Standard C++ IOStreams and Locales" by Angelika Langer and
Klaus Kreft, for all the gory details.

You'll be whipping up your own custom std::basic_ifstream<float> and
std::basic_ifstream<MyBigStruct> in no time.

HTH,
--Eljay

Loading...