Sublime Text3对中文处理的一向不好,主要归功于微软的系统GBK编码,使得g++/gcc的调试信息都是GBK编码的,在Sublime Text3的终端看来就是一团乱码。

该如何处理这个问题?

  • 首先,你需要升级到最新的ST3,以避免一些已知的BUG。
  • 其次,你需要将toutf8.exe这个文件放入MinGW的bin目录(MinGW\bin)当中
  • 然后,修改您的Sublime Text3的编译系统,修改shell命令中的g++为toutf8 g++ 或者 gcc 为 toutf8 gcc 如:toutf8 g++ -Wall -std=c++0x -Wshadow -Wunreachable-code -fexec-charset=GBK "$file" -o "$file_base_name"
  • 最后,enjoy~~

您可以在文章的最后下载toutf8.exe 或者点此下载toutf8.7z

toutf8.exe的原理是?

  • 获取传入的参数,然后使用shell执行传入的命令并将输出重定向到temp目录
  • 按行获取返回文本,如果匹配到C:\或者D:\等等则进行转换(从GBK到UTF-8)
  • 输出所有返回

下面是toutf8.exe文件的源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <stdio.h>   //popen()
#include <string.h> //memset()
#include <stdlib.h>
#include <windows.h>

int GBK2UTF8(char *szGbk,char *szUtf8,int Len)
{
// 先将多字节GBK(CP_ACP或ANSI)转换成宽字符UTF-16
// 得到转换后,所需要的内存字符数
int n = MultiByteToWideChar(CP_ACP,0,szGbk,-1,NULL,0);
// 字符数乘以 sizeof(WCHAR) 得到字节数
WCHAR test[sizeof(WCHAR) * n];
WCHAR *str1 = test;
// 转换
MultiByteToWideChar(CP_ACP,// MultiByte的代码页Code Page
0, //附加标志,与音标有关
szGbk, // 输入的GBK字符串
-1, // 输入字符串长度,-1表示由函数内部计算
str1, // 输出
n // 输出所需分配的内存
);

// 再将宽字符(UTF-16)转换多字节(UTF-8)
n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
if (n > Len)
{
return -1;
}
WideCharToMultiByte(CP_UTF8, 0, str1, -1, szUtf8, n, NULL, NULL);
str1 = NULL;
return 0;
}

int main(int argc, char **argv)
{
char canshu[1000];
canshu[0]=0;
for (int i = 1; i < argc; ++i)
{
strcat(canshu,argv[i]);
strcat(canshu," ");
}
strcat(canshu,">%tmp%\\output.txt 2>&1");
int fanhui = system(canshu);
//取出执行结果
FILE *fp;
//获取临时目录
char OutPath[100];
GetTempPath(100, OutPath);
strcat(OutPath,"\\output.txt");
fp=fopen(OutPath,"r");
char ch;
char hang[1000];
int i = 0;
while((ch=fgetc(fp))!=EOF)
{
hang[i++]=ch;
if (ch=='\n')
{
//一行结束,开始处理
hang[i++]=0;//赋上结束符
if (hang[1]==':' && hang[2]=='\\')
{
//这一行需要进行处理
GBK2UTF8(hang,canshu,1000);
printf("%s", canshu);
}else
{
//直接输出
printf("%s",hang);
}
i = 0;
}
}
fclose(fp);
return fanhui;
}

toutf8.7z