背景:最近经常遇到移植linux c源码到visual studio上编译,由于linux上默认都是utf8编码里面的汉字编译的时候经常报错,需要转化为utf8-bom格式。特此记录一下批量转化的实现。
源码如下:
// utf8bomConvert.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<Windows.h>
#include<iostream>
using namespace std;
int ConvertFile(char* chfile_path,char* convert_fila_path)
{
FILE *fp = fopen(chfile_path,"rb");
FILE* fpconvert=NULL;
char chflags[3] = {0xef,0xbb,0xbf};
long file_size =0;
char* file_buff=NULL;
int ret=0;
if(fp==NULL)
{
ret = -1;
goto bail;
}
fseek(fp,0L,SEEK_END);
file_size = ftell(fp);
fseek(fp,0L,SEEK_SET);
file_buff = (char*)malloc(file_size);
if(file_buff==NULL)
{
ret = -2;
goto bail;
}
fread(file_buff,file_size,1,fp);
fclose(fp);
fpconvert = fopen(convert_fila_path,"ab+");
if(fpconvert==NULL)
{
ret = -3;
goto bail;
}
fwrite(chflags,3,1,fpconvert);
fwrite(file_buff,file_size,1,fpconvert);
fclose(fpconvert);
fpconvert =NULL;
fclose(fp);
fp = NULL;
bail:
if(fp)
{
fclose(fp);
}
if(fpconvert)
{
fclose(fpconvert);
}
if(file_buff)
{
free(file_buff);
}
return 0;
}
void test()
{
char *src_path = "d:\\cjson.h";
char *des_path = "d:\\utf8_bom_cjson.h";
ConvertFile(src_path,des_path);
}
int _tmain(int argc, _TCHAR* argv[])
{
/*test();
system("pause");
return 0;*/
char src_path[MAX_PATH] = {0};
char des_path[MAX_PATH] = {0};
char temp[MAX_PATH] = {0};
char *start_pos,*end_pos;
start_pos = end_pos =NULL;
printf("请输入要转码的文件夹路径:\r\n");
scanf("%s",src_path);
start_pos = src_path;
end_pos = strrchr(src_path,'\\');
memcpy(temp,src_path,end_pos-start_pos);
sprintf_s(des_path,"%s\\utf8_bom",temp);
if(TRUE == CreateDirectoryA(des_path,NULL))
{
WIN32_FIND_DATAA fd;
SetCurrentDirectoryA(src_path);
HANDLE hFind = ::FindFirstFileA("*.*", &fd);
if ( hFind != INVALID_HANDLE_VALUE )
{
do{
if ( !(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )
{//非目录,即文件
cout << fd.cFileName << endl;
char *file_tag=NULL;
char src_file_path[MAX_PATH] = {0};
char des_file_path[MAX_PATH] = {0};
file_tag = strrchr(fd.cFileName,'.');
if(stricmp(file_tag,".h")==0||stricmp(file_tag,".c")==0)
{
sprintf_s(src_file_path,MAX_PATH,"%s\\%s",src_path,fd.cFileName);
sprintf_s(des_file_path,MAX_PATH,"%s\\%s",des_path,fd.cFileName);
int ret = ConvertFile(src_file_path,des_file_path);
if(ret!=0)
{
printf("%s 转码失败\r\n",src_file_path);
}else{
printf("%s success \r\n",fd.cFileName);
}
}
}
}while (::FindNextFileA(hFind, &fd));
::FindClose(hFind);
}
}
system("pause");
return 0;
}
源码链接:
https://download.csdn.net/download/cx1990820/88745713?spm=1001.2014.3001.5501