contrib/mul/mbl/mbl_load_text_file.txx
Go to the documentation of this file.
00001 #ifndef mbl_load_text_file_txx_
00002 #define mbl_load_text_file_txx_
00003 //:
00004 // \file
00005 // \brief Functions to load objects from text file
00006 // \author dac
00007 
00008 #include "mbl_load_text_file.h"
00009 #include <mbl/mbl_exception.h>
00010 #include <vcl_fstream.h>
00011 #include <vcl_iterator.h>
00012 #include <vcl_algorithm.h>
00013 #include <vcl_cerrno.h>
00014 
00015 //: Load vector from file with format "v1 v2 .. vn"
00016 // \throws on error, or returns false if exceptions are disabled.
00017 template <class T>
00018 bool mbl_load_text_file(vcl_vector<T>& v, const vcl_string& path)
00019 {
00020   vcl_ifstream ifs(path.c_str());
00021   if (!ifs)
00022     mbl_exception_throw_os_error(path, "Whilst trying to open data file for reading.");
00023 
00024   try
00025   {
00026     bool rv = mbl_load_text_file( v, ifs );
00027     if (!rv && errno)
00028       mbl_exception_throw_os_error(path, "Whilst trying to read data file.");
00029   }
00030   catch (const mbl_exception_parse_error& e)
00031   {
00032     mbl_exception_warning(  mbl_exception_parse_file_error(e.what(), path));
00033     return false;
00034   }
00035 
00036   return true;
00037 }
00038 
00039 //: Load vector from file with format "v1 v2 .. vn"
00040 // \throws on error, or returns false if exceptions are disabled.
00041 template <class T>
00042 bool mbl_load_text_file(vcl_vector<T>& v, vcl_istream& is)
00043 {
00044   v.resize(0);
00045 
00046   if (!is)
00047   {
00048     mbl_exception_warning( mbl_exception_parse_error( "mbl_load_text_file: IO error" ));
00049     return false;
00050   }
00051 
00052   vcl_copy(vcl_istream_iterator<T> (is), vcl_istream_iterator<T>(),
00053            vcl_back_insert_iterator< vcl_vector<T> > (v) );
00054   if (!is.eof())
00055   {
00056     mbl_exception_warning( mbl_exception_parse_error( "mbl_load_text_file: failed to finished loading" ));
00057     return false;
00058   }
00059 
00060   if (v.empty())
00061   {
00062     mbl_exception_warning( mbl_exception_parse_error("Could not parse indices file."));
00063     return false;
00064   }
00065 
00066   return true;
00067 }
00068 
00069 #undef MBL_LOAD_TEXT_FILE_INSTANTIATE_PATH
00070 #define MBL_LOAD_TEXT_FILE_INSTANTIATE_PATH(T ) \
00071 template bool mbl_load_text_file(vcl_vector<T >& v, const vcl_string& path)
00072 #undef MBL_LOAD_TEXT_FILE_INSTANTIATE_STREAM
00073 #define MBL_LOAD_TEXT_FILE_INSTANTIATE_STREAM(T ) \
00074 template bool mbl_load_text_file(vcl_vector<T >& v, vcl_istream& is)
00075 
00076 #endif //mbl_load_text_file_txx_