Created
July 18, 2014 02:39
-
-
Save hyperair/8b82650199622248d8ce to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <sstream> | |
#include <unordered_map> | |
#include <string> | |
#include <cstring> | |
#include <exception> | |
#include <memory> | |
struct InvalidLine : public std::exception | |
{ | |
virtual const char *what () const throw () | |
{ | |
return "Invalidly formatted line"; | |
} | |
}; | |
std::string get_filename (const std::string &prefix,const std::string &line) | |
{ | |
std::ostringstream ss; | |
if (line.size () < 10 || std::strncmp (line.c_str (), "201", 3) != 0 || | |
line[4] != '-' || line[7] != '-') | |
throw InvalidLine (); | |
ss << prefix | |
<< line.substr (0, 4) | |
<< line.substr (5, 2) | |
<< line.substr (8, 2); | |
return ss.str (); | |
} | |
int main (int argc, char **argv) | |
{ | |
typedef std::shared_ptr<std::ofstream> outfile_t; | |
typedef std::unordered_map<std::string, outfile_t> handle_t; | |
handle_t handles; | |
for (char **i = argv + 1; *i; ++i) { | |
std::ifstream infile (*i); | |
std::string line; | |
std::string prefix = std::string (*i) + "-"; | |
outfile_t outfile; | |
while (std::getline (infile, line)) { | |
try { | |
std::string outfilename = get_filename (prefix, line); | |
handle_t::iterator iter = handles.find (outfilename); | |
if (iter == handles.end ()) { | |
outfile = outfile_t (new std::ofstream ( | |
outfilename.c_str ())); | |
handles.insert (std::make_pair (outfilename, outfile)); | |
} else | |
outfile = iter->second; | |
} catch (InvalidLine &e) { | |
} | |
if (!outfile) | |
continue; | |
*outfile << line << '\n'; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment