Effective implementation of algorithms (Master Thesis)
Effective and error-free implementation of algorithms
src/strings/utils/sequence_loader.h
Go to the documentation of this file.
00001 #ifndef H_STRINGS_UTILS_SEQUNENCE_LOADER
00002 #define H_STRINGS_UTILS_SEQUNENCE_LOADER
00003 
00007 #include <stdio.h>
00008 #include <string>
00009 #include <map>
00010 #include <exception>
00011 #include <fstream>
00012 #include <stdexcept>
00013 #include "utils/preconditions/preconditions.h"
00014 
00015 namespace strings {
00016 namespace utils {
00024 class SequenceLoader{
00025  public:
00036   static std::vector<unsigned char> loadSequence(
00037       const char* filename,
00038       const std::map<unsigned char, unsigned char>& conversion_map) {
00039     Preconditions::check(filename != NULL);
00040     std::ifstream f(filename, std::ios::binary);
00041     if (!f) {
00042       throw std::runtime_error(std::string("Couldn't open file ") + filename);
00043     }
00044 
00045     std::vector<unsigned char> result;
00046 
00047     int cnt = 0;
00048     while (f.good()) {
00049       // Warning: statement "f >> c;"
00050       // is inherently bad, because default is to strip whitespace
00051       char tmp;
00052       f.get(tmp);
00053       unsigned char c = tmp;
00054       if (!f.good()) {
00055         if (f.bad()) {
00056           throw new std::runtime_error("Problem reading file.");
00057         }
00058         break;
00059       }
00060       cnt++;
00061       if (conversion_map.find(c) != conversion_map.end()) {
00062         // can't use conversion_map[c] as map is passed as const
00063         // and that call may modify it
00064         result.push_back(conversion_map.find(c)->second);
00065       }
00066     }
00067     f.close();
00068     return result;
00069   }
00070 };
00071 
00072 } // namespace utils
00073 } // namespace strings
00074 #endif
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines