批量转化utf8文件为utf8-bom文件格式

背景:最近经常遇到移植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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值