1. 程序说明
在中文操作系统中ANSI编码默认表示GBK。 本程序可以实现检索当前目录以及其子目录下所有满足特定后缀的文件,并且判断这些文件编码格式是否为ANSI编码(GBK),如果是,则转换为UTF-8格式,如果是UTF-8格式,则不作操作。
注意:本程序不能转换GB2312编码格式的文件。
2.测试
下图为测试目录,此程序可以搜索当前目录Debug
下所有满足特定后缀(*.c
*.cpp
*.h
*.hpp
)的所有文件。
下图为测试结果打印输出
3. 代码
// Encoding ansi (编码格式: ANSI)
// 当前文件必须是 ANSI,才能正常运行
#include <iostream>
#include <string>
#include <fstream>
#include <io.h>
#include <windows.h>
#include <direct.h>
#include<vector>
using namespace std;
/* 无 BOM 检测 UTF-8
UCS-4 range (hex.) UTF-8 octet sequence (binary)
0000 0000-0000 007F 0xxxxxxx
0000 0080-0000 07FF 110xxxxx 10xxxxxx // 110 表示 2个字节,一个UTF-8
0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx // 1110 表示3个字节,一个UTF-8
0001 0000-001F FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // 11110 表示4个,字节一个 UTF-8
0020 0000-03FF FFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx // 111110 表示5个字节,一个 UTF-8
0400 0000-7FFF FFFF 1111110x 10xxxxxx ... 10xxxxxx // 1111110 表示 6个字节 ,一个 UTF-8
*/
BOOL CheckNoBOM_utf8(BYTE *pText, long length)
{
int i;
DWORD nBytes = 0;
UCHAR chr;
BOOL bAllAscii = TRUE;
// all chars
for (i = 0; i < length; i++)
{
chr = *(pText + i);
if ((chr & 0x80) != 0) bAllAscii = FALSE;// 0xxxxxxx
if (nBytes == 0)
{
// check 1st
if (chr >= 0x80)
{
if (chr >= 0xFC && chr <= 0xFD) nBytes = 6;
else if (chr >= 0xF8) nBytes = 5;
else if (chr >= 0xF0) nBytes = 4;
else if (chr >= 0xE0) nBytes = 3;
else if (chr >= 0xC0) nBytes = 2;
else return FALSE;
nBytes--;
}
}
else
{
// 10xxxxxx
if ((chr & 0xC0) != 0x80) return FALSE;// not 10xxxxxx
nBytes--;// next "10xxxxxx"
}
}
// more "10xxxxxx" than nBytes
if (nBytes > 0) return FALSE;
// all bytes is ascii
if (bAllAscii) return FALSE;
//
return TRUE;
}
enum class Encode {
ANSI = 1, UNICODE_LE, UNICODE_BE, UTF8, UTF8_NOBOM };
BOOL CheckUnicodeWithoutBOM(const PBYTE pText, long length)
{
int i;
DWORD nBytes = 0;
UCHAR chr;
BOOL bAllAscii = TRUE;
for (i = 0; i < length; i++)
{
chr = *(pText + i);
if ((chr & 0x80) != 0)
bAllAscii = FALSE;
if (nBytes == 0)
{
if (chr >= 0x80)
{
if (chr >= 0xFC && chr <= 0xFD)
nBytes =