1 |
torben |
1231 |
#include <iostream> |
2 |
|
|
#include <fstream> |
3 |
|
|
#include <sstream> |
4 |
|
|
#include <string> |
5 |
|
|
#include <vector> |
6 |
|
|
|
7 |
|
|
#include <boost/algorithm/string.hpp> |
8 |
|
|
#include <boost/filesystem.hpp> |
9 |
|
|
|
10 |
|
|
using namespace std; |
11 |
|
|
|
12 |
|
|
const int BUFSIZE = 1024*1024; |
13 |
|
|
|
14 |
|
|
string getLastWord(string input) { |
15 |
|
|
vector<string> words; |
16 |
|
|
words = boost::split(words, input, boost::is_any_of(" ") ); |
17 |
|
|
|
18 |
|
|
string last = words.back(); |
19 |
|
|
|
20 |
|
|
boost::erase_all(last, ";"); |
21 |
|
|
boost::trim(last); |
22 |
|
|
|
23 |
|
|
|
24 |
|
|
|
25 |
|
|
return last; |
26 |
|
|
} |
27 |
|
|
|
28 |
|
|
|
29 |
|
|
int main(int argc, char** argv) { |
30 |
|
|
if (argc != 2) { |
31 |
|
|
cout << "Usage: splitter <file>" << endl; |
32 |
|
|
return 1; |
33 |
|
|
} |
34 |
|
|
|
35 |
|
|
char linebuf[BUFSIZE]; |
36 |
|
|
|
37 |
|
|
ifstream in(argv[1]); |
38 |
|
|
ofstream out; |
39 |
|
|
|
40 |
|
|
ostringstream header; |
41 |
|
|
|
42 |
|
|
if (!in.is_open() ) { |
43 |
|
|
cout << "Could not open " << argv[1] << endl; |
44 |
|
|
return 2; |
45 |
|
|
} |
46 |
|
|
|
47 |
|
|
while ( in.good() ) { |
48 |
|
|
in.getline(linebuf, BUFSIZE); |
49 |
|
|
|
50 |
|
|
string line(linebuf); |
51 |
|
|
|
52 |
|
|
|
53 |
|
|
//if (line.substr(0, 15) == "CREATE DATABASE" ) { |
54 |
|
|
if ( boost::starts_with(line, "CREATE DATABASE") ) { |
55 |
|
|
|
56 |
|
|
if (out.is_open() ) { |
57 |
|
|
out.close(); |
58 |
|
|
} |
59 |
|
|
|
60 |
|
|
boost::trim(line); |
61 |
|
|
string dbname = getLastWord(line); |
62 |
|
|
cout << ">" << dbname << endl; |
63 |
|
|
|
64 |
|
|
|
65 |
|
|
ostringstream oss; |
66 |
|
|
oss << dbname << "_dump.sql";
|
67 |
|
|
|
68 |
|
|
string filename = oss.str(); |
69 |
|
|
|
70 |
|
|
bool did_exist = boost::filesystem::exists(filename); |
71 |
|
|
|
72 |
|
|
out.open( filename.c_str(), ios::app ); |
73 |
|
|
|
74 |
|
|
|
75 |
|
|
|
76 |
|
|
if (!out.is_open() ) { |
77 |
|
|
cout << "could not create outfile " << filename << endl; |
78 |
|
|
return 3; |
79 |
|
|
} |
80 |
|
|
|
81 |
|
|
if (!did_exist) { |
82 |
|
|
out << header.str() << endl; //write preamble in new file |
83 |
|
|
} |
84 |
|
|
|
85 |
|
|
} |
86 |
|
|
|
87 |
|
|
|
88 |
|
|
if (out.is_open() ) { |
89 |
|
|
out << line << endl; |
90 |
|
|
} else { |
91 |
|
|
header << line << endl; //collect preamble for later use |
92 |
|
|
} |
93 |
|
|
|
94 |
|
|
} |
95 |
|
|
|
96 |
|
|
|
97 |
|
|
if(out.is_open()) |
98 |
|
|
out.close(); |
99 |
|
|
|
100 |
|
|
|
101 |
|
|
in.close(); |
102 |
|
|
} |