安裝GnuWin32 libiconv
1. 至GnuWin32網站下載libiconv套件 http://gnuwin32.sourceforge.net/downlinks/libiconv.php
2. 下載完執行安裝檔
設定自行開發的專案
1. 控制台→系統→進階→環境變數→path→編輯→加入;C:\Program Files\GnuWin32\bin
2. Visual C++專案→屬性→組態屬性→C/C++→一般→其他Include目錄→加入C:\Program Files\GnuWin32\include
Visual C++專案→屬性→組態屬性→ 連結器→一般→其他程式庫目錄→加入C:\Program Files\GnuWin32\lib
Visual C++專案→屬性→組態屬性→ 連結器→輸入→其他相依性→加入libiconv.lib
// 範例一使用內建的iconv轉檔
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iconv.h>
#define MAX 32768
int convertFile(const char*,const char*,const char*,const char*,char*,char*);
int main(){
const char* tocode = "GBK";
const char* fromcode = "UTF-8";
const char* infilename = "utf8.txt";
const char* outfilename = "gbk.txt";
char inbuf[MAX];
char outbuf[MAX*4];
int ret;
ret = convertFile(tocode,fromcode,infilename,outfilename,inbuf,outbuf);
if (ret == 0){
printf("File conversion is successful\n");
}
//system("PAUSE");
}
int convertFile(const char* tocode,const char* fromcode,const char* infilename,const char* outfilename,char* inbuf,char* outbuf){
iconv_t cd = iconv_open(tocode,fromcode);
if (cd == (iconv_t)(-1)){
printf("iconv: conversion from %s to %s unsupported\n",fromcode,tocode);
return -1;
}
else{
FILE* fromfile = fopen(infilename,"r");
FILE* tofile = fopen(outfilename,"w");
if (fromfile != NULL){
size_t status;
size_t inbytesleft;
size_t outbytesleft;
size_t insize = fread(inbuf,sizeof(char),MAX,fromfile);
const char* inptr = inbuf;
char* outptr = outbuf;
inbuf[insize] = '\0';
inbytesleft = strlen(inbuf);
outbytesleft = inbytesleft * 4;
status = iconv(cd,(const char**)&inptr,&inbytesleft,&outptr,&outbytesleft);
if (status == (size_t)(-1)){
printf("iconv: conversion from %s to %s error\n",fromcode,tocode);
return -1;
}
else{
fwrite(outbuf,sizeof(char),outptr-outbuf,tofile);
iconv_close(cd);
//printf("%s\n",outptr);
fclose(fromfile);
fclose(tofile);
}
}
else{
perror("This file is not exist");
return -1;
}
}
return 0;
}
圖一原先input之檔案utf8.txt
轉換後
圖二output之檔案gbk.txt
你會發現字看起來長的有點不太一樣
若是用記事本開gbk.txt將會是一堆看不懂的亂碼
代表已經轉檔成功
// 範例二使用extra資料夾的iconv_string轉檔
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iconv.h>
#include "iconv_string.h"
#define MAX 65536
int main(){
char str[MAX];
const char* tocode = "GBK";
const char* fromcode = "UTF-8";
const char* result = NULL;
FILE* fromfile = fopen("utf8.txt","r");
FILE* tofile = fopen("gbk.txt","w");
if (fromfile != NULL){
int status;
size_t insize = fread(str,sizeof(char),strlen(str),fromfile);
str[insize] = '\0';
printf("%s\n",str);
status = iconv_string(tocode,fromcode,str,str+strlen(str)+1,&result,NULL);
printf("%s",result);
if (status == -1){
perror("Conversion failure");
}
else{
fwrite(result,sizeof(char),strlen(result),tofile);
fclose(fromfile);
fclose(tofile);
}
}
else{
perror("No existing file");
}
//system("PAUSE");
}
在Visual C++專案原始程式檔及標頭檔分別加入icon_string.c及iconv_string.h後編譯
圖三原先input之檔案utf8.txt
轉換後
圖四output之檔案gbk.txt
转载于:https://www.cnblogs.com/ping-grep/archive/2013/03/29/2989803.html