Commit ffe11679 authored by Davis King's avatar Davis King

Made deserialize print more informative error messages.

parent 57b6cd1b
......@@ -1498,22 +1498,87 @@ namespace dlib
public:
explicit proxy_deserialize (
const std::string& filename
)
) : filename(filename)
{
fin.reset(new std::ifstream(filename.c_str(), std::ios::binary));
if (!(*fin))
throw serialization_error("Unable to open " + filename + " for reading.");
// read the file header into a buffer and then seek back to the start of the
// file.
fin->read(file_header,4);
fin->clear();
fin->seekg(0);
}
template <typename T>
inline proxy_deserialize& operator>>(T& item)
{
try
{
if (fin->peek() == EOF)
throw serialization_error("No more objects were in the file!");
deserialize(item, *fin);
}
catch (serialization_error& e)
{
std::string suffix;
if (looks_like_a_compressed_file())
suffix = "\n *** THIS LOOKS LIKE A COMPRESSED FILE. DID YOU FORGET TO DECOMPRESS IT? *** \n";
if (objects_read == 0)
{
throw serialization_error("An error occurred while trying to read the first"
" object from the file " + filename + ".\nERROR: " + e.info + "\n" + suffix);
}
else if (objects_read == 1)
{
throw serialization_error("An error occurred while trying to read the second"
" object from the file " + filename +
".\nERROR: " + e.info + "\n" + suffix);
}
else if (objects_read == 2)
{
throw serialization_error("An error occurred while trying to read the third"
" object from the file " + filename +
".\nERROR: " + e.info + "\n" + suffix);
}
else
{
throw serialization_error("An error occurred while trying to read the " +
std::to_string(objects_read+1) + "th object from the file " + filename +
".\nERROR: " + e.info + "\n" + suffix);
}
}
++objects_read;
return *this;
}
private:
int objects_read = 0;
std::string filename;
std::shared_ptr<std::ifstream> fin;
// We don't need to look at the file header. However, it's here because people
// keep posting questions to the dlib forums asking why they get file load errors.
// Then it turns out that the problem is they have a compressed file that NEEDS TO
// BE DECOMPRESSED by bzip2 or whatever and the reason they are getting
// deserialization errors is because they didn't decompress the file. So we are
// going to check if this file looks like a compressed file and if so then emit an
// error message telling them to unzip the file. :(
char file_header[4] = {0,0,0,0};
bool looks_like_a_compressed_file(
) const
{
if (file_header[0] == 'B' && file_header[1] == 'Z' && file_header[2] == 'h' &&
('0' <= file_header[3] && file_header[3] <= '9') )
{
return true;
}
return false;
}
};
inline proxy_serialize serialize(const std::string& filename)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment