Jason
Jason

Reputation: 1613

several different ways to read unsigned char from file

I want to read unsigned char from file and have search many different ways to execute. But I don't know the reason why they work or don't work.

1. ifstream input(ios::in | ios::binary) //seems to not work, but why?

I have set the ios::binary which supposed to prevent the conversion.

2. unsigned char buffer[BUFFER_SIZE];

myfile.read((unsigned char *) buffer, BUFFER_SIZE);//error!fail

myfile.read((char *) buffer, BUFFER_SIZE);//work, the data type is unsigned char

why do I have to convert it to char*? The data stored in the array won't be converted to char not unsigned char? What does it do during conversion?

3. vector//it work but I don't know what it have done.

Upvotes: 0

Views: 1559

Answers (2)

user132748
user132748

Reputation:

For the first part, the constructor also expects a file name. For example,

ifstream input("myfile.dat", ios::in | ios::binary);

I believe you can omit the ios::in, as it is the default for ifstream.

And for the second part, istream::read expects a char* pointer (or some equivalent type). After reading the data, you can cast the elements to unsigned char*.

Upvotes: 1

bmargulies
bmargulies

Reputation: 100133

The read function declares a prototype of 'char *'. This is just what some author did in the mists of time. It does not mean that any 'conversion' is going to take place. There is no 'conversion' from char * to unsigned char *, in any case; both are pointers to bytes, and any conversion semantics of I/O classes are going to be controlled by other factors.

Upvotes: 1

Related Questions