JavaScript を使いたくない人のための C++ バージョンがあります。標準の C++ ライブラリのみを使用します。
#include <stdio.h>
#include <io.h>
#include <string.h>
#include <vector>
#include <string>
void Usage(const char* msg = NULL)
{
if (msg)
printf("%s\n", msg);
printf("Usage: coderep (prefix) (infile) (listfile) (outfile)\n");
}
char* OpenAndReadFile(const char* filename)
{
FILE* fp = fopen(filename, "rb");
if (!fp)
return NULL;
fseek(fp, 0, SEEK_END);
int size = (int)ftell(fp);
fseek(fp, 0, SEEK_SET);
char* buf = new char[size + 2];
fread(buf, 1, size, fp);
buf[size] = '\0';
fclose(fp);
return buf;
}
void ReplaceAll(std::string& str, const std::string& from, const std::string& to)
{
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos)
{
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
}
char* rndCh = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int rndLen = 62;
// Generate random string from number
void genRand(int index, std::string* str)
{
std::vector<int> ni;
while (index > 0)
{
ni.push_back(index % 62);
index = index / 62;
}
if (!ni.size())
ni.push_back(0);
std::vector<int>::reverse_iterator ip;
for (ip = ni.rbegin(); ip != ni.rend(); ++ip)
(*str) += rndCh[*ip];
}
int main(int argc, char* argv[])
{
if (argc != 5)
{
Usage();
return 1;
}
// Read inputs and check parms
const char* prefix = argv[1];
char* code = OpenAndReadFile(argv[2]);
if (!code || !*code)
{
Usage("Failed reading code");
return 1;
}
char* list = OpenAndReadFile(argv[3]);
if (!list || !*list)
{
delete[] code;
Usage("Failed reading list");
return 1;
}
const char* outfile = argv[4];
if (!outfile || !*outfile)
{
Usage("Need output file");
return 1;
}
// Split list
std::string scode(code);
std::vector<std::string> vlist;
std::string acc;
const char* lp = list;
while (*lp)
{
if (*lp == L',')
{
vlist.push_back(acc);
acc.clear();
}
else
{
acc += *lp;
}
++lp;
}
if (acc.size() > 0)
vlist.push_back(acc);
// Do translation
int index = 0;
std::string rstr;
std::vector<std::string>::iterator ilist;
for (ilist = vlist.begin(); ilist != vlist.end(); ++ilist)
{
rstr = prefix;
genRand(index, &rstr);
++index;
ReplaceAll(scode, *ilist, rstr);
}
// Write results
FILE* outp = fopen(outfile, "wb");
if (!outp)
{
Usage("Error creating output file");
return 1;
}
fwrite(scode.c_str(), sizeof(char), scode.size(), outp);
fclose(outp);
return 0;
}