When reading binary data you generally want to open your std::ifstream
with the flag std::ios_base::binary
. The resulting differences are fairly small but they generally do matter.
There are a few oddities in your code you might want to fix:
- You always need to check after reading if the operation was successful, e.g., using
if (in.read(hashChars, hashLen)) { ... }
- There is no need to use
reinterpret_cast<...>()
which always has implementation defined semantics. You should usestatic_cast<unsigned char>(c)
instead. - You allocate an array of characters but you release it using
delete p
. You need to usedelete[] p
instead. Usingdelete p
results in undefined behavior. There isn't really any need to usenew
anddelete
at all, though, asstd::vector<char> hashChars(hashLen)
does automatic memory management.
There are a few [mutilated] questions otherwise embedded in the request above (so the questions/answers are guesses of what is being asked):
- Can you mix
std::istream::read()
andfread()
on the same stream (I suppose this is the question): not immediately unless the stream happens to bestd::cin
which reads from the same source asstdin
. If you want to use bothstd::istream::read()
andfread()
on the same file you'll need to wrap aFILE*
by a suitablestd::streambuf
and initialize anstd::istream
with the corresponding object. - How to read an arbitrary sized line with
fgets()
? You can't. The buffer tofgets()
gets allocated before attempting to fill it and can always be filled before reaching a newline. You can usestd::getline()
to read an arbitrary long line, however. If you just want to skip the line, you can usein.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
when usingstd::istream
. Off-hand I don't know if there is a similar operation forFILE*
.