1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#include <fstream>
#include <iostream>
#include <string>
#include <iterator>
#include <boost/regex.hpp>
using namespace std;
// purpose:
// takes the contents of a file in the form of a string
// and insert a string after each match with your regex
void load_file(std::string& s, std::istream& is)
{
s.erase();
s.reserve(is.rdbuf()->in_avail());
char c;
while(is.get(c))
{
if(s.capacity() == s.size())
s.reserve(s.capacity() * 3);
s.append(1, c);
}
}
void insertFlags(std::string& stringFile, const boost::regex& expression)
{
std::string::iterator start, end;
std::string test("insertTest;");
start = stringFile.begin();
end = stringFile.end();
boost::match_results<std::string::iterator> what;
while(regex_search(start, end, what, expression, boost::format_first_only))
{
int pos = std::distance(stringFile.begin(), what[0].second);
// insère le tag à cette position
stringFile.insert(pos, test);
// attention après un insert il faut redéfinir start et end
start = stringFile.begin() + pos + test.size();
end = stringFile.end();
}
}
int main(int argc, const char** argv){
// the first regex matchs all C/C++ if bloc
// the second regex matchs all else bloc
boost::regex expression(
"\\<if\\s*\\([\\s\\w=<>/!%&,:~\\-\\'\\\"\\`\\^\\.\\[\\]\\$\\(\\)\\*\\+\\|\\\\]+\\)\\s*\\{|"
"\\<else\\s*\\{"
);
std::cout << "Processing file " << argv[1] << std::endl;
std::ifstream fs(argv[1]);
std::string stringFile;
load_file(stringFile, fs);
std::string out_name(std::string(argv[1]) + std::string(".c"));
std::ofstream outputFile(out_name.c_str());
insertFlags(stringFile,expression);
outputFile << stringFile;
outputFile.close();
return 0;
} |
Partager