owlps/owlps-positioning/src/csvfilereader.hh

83 lines
1.8 KiB
C++

/*
* This file is part of the Owl Positioning System (OwlPS).
* OwlPS is a project of the University of Franche-Comté
* (Université de Franche-Comté), France.
*/
#ifndef _OWLPS_POSITIONING_CSVFILEREADER_HH_
#define _OWLPS_POSITIONING_CSVFILEREADER_HH_
class Point3D ;
#include "textfilereader.hh"
#include "timestamp.hh"
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
/// Reads a CSV file, line by line, field by field
class CSVFileReader: public TextFileReader
{
protected:
const char separator ;
std::string current_line ;
boost::tokenizer<boost::escaped_list_separator<char> > *current_token ;
boost::tokenizer<boost::escaped_list_separator<char> >::const_iterator
token_iterator ;
unsigned int current_field_nb ;
void print_error_cast(void) const ;
public:
CSVFileReader(const std::string &filename,
const char _separator = ';'):
TextFileReader(filename), separator(_separator),
current_token(NULL), current_field_nb(0) {}
virtual ~CSVFileReader(void) ;
/** @name Operations */
//@{
/// Loads the first next non-blank line
bool next_line(void) ;
/// Reads the next field of the current line
template<class T> bool read_field(T &field) ;
/// Reads the next field that should be a Timestamp
bool read_timestamp(Timestamp &t) ;
/// Reads the next 3 fields that should form a Point3D
bool read_point3d(Point3D &p) ;
//@}
} ;
/* *** Operations *** */
template<class T>
inline bool CSVFileReader::read_field(T &field)
{
if (token_iterator == current_token->end())
return false ;
++current_field_nb ;
try
{
field = boost::lexical_cast<T>(*token_iterator) ;
}
catch (boost::bad_lexical_cast &e)
{
print_error_cast() ;
return false ;
}
++token_iterator ;
return true ;
}
#endif // _OWLPS_POSITIONING_CSVFILEREADER_HH_