|
-
July 12th, 2004, 03:04 PM
#1
ifstream.read into unsigned char* ?
I'd like to use a certain md5-class. It reads a filestream into an unsigned char array, like this:
Code:
void MD5::update(ifstream& stream)
{
unsigned char buffer[1024];
while (stream.good())
{
stream.read(buffer, 1024);
update(buffer, stream.gcount());
}
}
That code won't compile in Visual C++, because stream.read only accepts a char* and not a unsigned char* as a first parameter.
I noticed that the microsoft implementation uses this:
Code:
typedef basic_ifstream<char, char_traits<char> > ifstream;
So i created this typedef:
Code:
typedef basic_ifstream<unsigned char, char_traits<unsigned char> > ifucstream;
Using 'ifucstream' does compile, but somehow the stream fails after a few loops.
So then i tried using reinterpret_cast to cast buffer as a char* and i also tried 'C'-casting:
Code:
stream.read(reinterpret_cast<char*>(buffer), 1024);
stream.read((char*)buffer, 1024);
Both work fine. However, i've read somewhere that these kind of typecasts are dangerous. Is that true in this case? And does anyone know why my typedef solution doesn't work? And finally, could using reinterpret_cast or 'C'-casting (like above) make the hash calculation slower, and which type of casting should i prefer?
-
July 12th, 2004, 03:55 PM
#2
Hi SNikita,
I think the solution I would prefer is to static_cast the buffer to char* on read(). It appears to me this is harmless since each type is an octet.
> And finally, could using reinterpret_cast or 'C'-casting (like
> above) make the hash calculation slower ...
Probably not. You could look at code generation of a cast and non-cast compile - but I don't expect a difference.
Jeff
-
July 13th, 2004, 08:28 AM
#3
Thx jwalto1,
Visual C++ doesn't allow me to static_cast an unsigned char* to a char* (unrelated types), so that's why i used the reinterpret_cast.
I'd still like to understand why the typedef-solution didn't work. Ideas anyone? For now ill be using the reinterpret_cast, although it looks pretty ugly
-
July 13th, 2004, 08:54 AM
#4
Take a look at this article: http://www.codeguru.com/Cpp/Cpp/algo...cle.php/c5087/
It may be something to look at, it does have a "fileread" example on it.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|