CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2004
    Posts
    3

    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?

  2. #2
    Join Date
    Apr 2004
    Posts
    76
    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

  3. #3
    Join Date
    Jul 2004
    Posts
    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

  4. #4
    Join Date
    May 2000
    Location
    Langesund, Telemark in Norway!
    Posts
    292
    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.
    ==========================
    Lars Werner aka Large
    http://lars.werner.no/
    ==========================

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured