21 #ifndef GRT_FILE_PARSER_HEADER 22 #define GRT_FILE_PARSER_HEADER 32 #include "../DataStructures/Vector.h" 39 FileParser():infoLog(
"[FileParser]"),warningLog(
"[WARNING FileParser]"){
46 return fileContents[index];
49 bool parseCSVFile(std::string filename,
bool removeNewLineCharacter=
true){
50 return parseFile(filename,removeNewLineCharacter,
',');
53 bool parseTSVFile(std::string filename,
bool removeNewLineCharacter=
true){
54 return parseFile(filename,removeNewLineCharacter,
'\t');
61 bool getConsistentColumnSize(){
62 return consistentColumnSize;
65 unsigned int getRowSize(){
66 return (
unsigned int)fileContents.size();
69 unsigned int getColumnSize(){
73 std::deque< Vector< std::string > >& getFileContents(){
79 consistentColumnSize =
false;
85 static bool parseColumn(
const std::string &row,
Vector< std::string > &cols,
const char seperator =
',' ){
87 const unsigned int N = (
unsigned int)row.length();
88 if( N == 0 )
return false;
90 size_t lastSize = cols.size();
92 if( lastSize > 0 ) cols.reserve( lastSize );
93 std::string columnString =
"";
94 const int sepValue = seperator;
95 for(
unsigned int i=0; i<N; i++){
96 if(
int(row[i]) == sepValue ){
97 cols.push_back( columnString );
99 }
else columnString += row[i];
103 cols.push_back( columnString );
106 if( cols.size() >= 1 ){
107 size_t K = cols.size()-1;
108 size_t foundA = cols[ K ].find(
'\n');
109 size_t foundB = cols[ K ].find(
'\r');
110 if( foundA != std::string::npos || foundB != std::string::npos ){
111 cols[ K ] = cols[ K ].substr(0,cols[K].length()-1);
120 bool parseFile(
const std::string &filename,
const bool removeNewLineCharacter,
const char seperator){
125 std::ifstream file( filename.c_str(), std::ifstream::in );
126 if ( !file.is_open() ){
127 warningLog <<
"parseFile(...) - Failed to open file: " << filename << std::endl;
132 std::streampos begin,end;
133 begin = file.tellg();
134 file.seekg (0, std::ios::end);
136 file.seekg (0, std::ios::beg);
142 while ( getline( file, line ) )
144 if( !parseColumn(line, vec, seperator) ){
146 warningLog <<
"parseFile(...) - Failed to parse column!" << std::endl;
152 if( columnSize == 0 ){
153 consistentColumnSize =
true;
155 }
else if( columnSize != vec.
getSize() ) consistentColumnSize =
false;
157 fileContents.push_back( vec );
170 bool consistentColumnSize;
171 unsigned int columnSize;
174 std::deque< Vector< std::string > > fileContents;
180 #endif //GRT_FILE_PARSER_HEADER