#include <windows.h>
#include <stdio.h>
void Utf8ToGbk(char* utf8, int len_utf8, char* gbk, int len_gbk) {
int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
wchar_t* wszGBK = (wchar_t*)malloc(sizeof(wchar_t) * len);
memset(wszGBK, 0, len * sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wszGBK, len);
len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, gbk, len, NULL, NULL);
if (wszGBK) {
free(wszGBK);
}
}
void convert_file(const char* filename) {
// Open file in binary mode, read into buffer
FILE* file = fopen(filename, "rb");
fseek(file, 0, SEEK_END);
long fsize = ftell(file);
fseek(file, 0, SEEK_SET);
char* string = (char*)malloc(fsize + 1);
fread(string, fsize, 1, file);
fclose(file);
string[fsize] = 0;
// Convert buffer from UTF-8 to GBK
char* gbk = (char*)malloc(fsize * 2 + 1); // allocate enough space
Utf8ToGbk(string, fsize + 1, gbk, fsize * 2 + 1);
// Check if a backup already exists, if not, create one
char backupFileName[260];
snprintf(backupFileName, sizeof(backupFileName), "%s.bak", filename);
if (fopen(backupFileName, "r") == NULL) {
rename(filename, backupFileName);
}
// Write the converted buffer into original file
file = fopen(filename, "wb");
fwrite(gbk, strlen(gbk), 1, file);
fclose(file);
printf("已修复的文件:%s\n", filename);
free(string);
free(gbk);
}
int main() {
WIN32_FIND_DATAA findData;
HANDLE hFind = FindFirstFileA(".\\*.lua", &findData);
if (hFind == INVALID_HANDLE_VALUE) {
printf("FindFirstFile failed (%d)\n", GetLastError());
return -1;
}
do {
if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
printf("%s\n", findData.cFileName);
convert_file(findData.cFileName);
}
} while (FindNextFileA(hFind, &findData) != 0);
FindClose(hFind);
printf("按回车键退出...");
getchar();
return 0;
}