Created
August 6, 2014 04:54
-
-
Save komasaru/93df247231e6ddcd766c to your computer and use it in GitHub Desktop.
Gist - C++ source code to convert ShiftJIS to UTR-8.
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
/*********************************************************** | |
* 文字コード変換 (ShiftJIS -> UTF-8) | |
**********************************************************/ | |
#include <fstream> | |
#include <iostream> // for cout, endl | |
#include <stdio.h> // for fopen | |
#include <string.h> // for strlen | |
#include <iconv.h> // for iconv | |
#define ENC_SRC "Shift_JIS" // Encoding ( Src ) | |
#define ENC_DST "UTF-8" // Encoding ( Dst ) | |
#define FILE_S "sjis.txt" // Textfile ( Src ) | |
#define FILE_D "utf8.txt" // Textfile ( Dst ) | |
#define B_SIZE 1024 // Buffer size | |
using namespace std; | |
/* | |
* [CLASS] Process | |
*/ | |
class Proc | |
{ | |
// Private Declaration | |
ifstream ifs; | |
ofstream ofs; | |
string sLine; | |
char sSrc[B_SIZE], sDst[B_SIZE]; | |
bool bRet; | |
bool convert(); | |
public: | |
int execMain(); // Main Process | |
}; | |
/* | |
* Main Process | |
*/ | |
int Proc::execMain() | |
{ | |
try { | |
// Open In-file | |
ifs.open(FILE_S); | |
if (ifs.fail()) { | |
cerr << "[ERROR] Could not open " << FILE_S << endl; | |
return 1; | |
} | |
// Open Out-file | |
ofs.open(FILE_D); | |
if (ofs.fail()) { | |
cerr << "[ERROR] Could not open " << FILE_D << endl; | |
return 1; | |
} | |
// Convert for each lines | |
while (getline(ifs, sLine)) { | |
bRet = convert(); | |
if (bRet) { | |
ofs << sDst << endl; | |
} else { | |
cerr << "[ERROR] Convert failed!" << endl; | |
} | |
} | |
} catch (char *e) { | |
cerr << "EXCEPTION : " << e << endl; | |
return 1; | |
} | |
return 0; | |
} | |
/* | |
* Convert for each lines | |
*/ | |
bool Proc::convert() | |
{ | |
char *pSrc, *pDst; | |
size_t nSrc, nDst; | |
iconv_t icd; | |
try { | |
strcpy(sSrc, sLine.c_str()); | |
pSrc = sSrc; | |
pDst = sDst; | |
nSrc = strlen(sSrc); | |
nDst = B_SIZE - 1; | |
while (0 < nSrc) { | |
icd = iconv_open(ENC_DST, ENC_SRC); | |
iconv(icd, &pSrc, &nSrc, &pDst, &nDst); | |
iconv_close(icd); | |
} | |
*pDst = '\0'; | |
return true; | |
} catch (char *e) { | |
cerr << "EXCEPTION : " << e << endl; | |
return false; | |
} | |
} | |
/* | |
* Execution | |
*/ | |
int main(){ | |
try { | |
Proc objMain; | |
int iRetCode = objMain.execMain(); | |
if (iRetCode == 0) { | |
cout << "SUCCESS!" << endl; | |
} else { | |
cout << "FAILED!" << endl; | |
} | |
} catch (char *e) { | |
cerr << "EXCEPTION : " << e << endl; | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment