你现在是一个 C++ 专家,请帮我用 C++ 写一个函式,它需要做到 将文件的编码从GBK编码转换为UTF-8编码
时间: 2024-05-05 18:20:20 浏览: 8
好的,以下是将GBK编码转换为UTF-8编码的 C 语言函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void GBK_to_UTF8(const char* gbk_filename, const char* utf8_filename) {
FILE* gbk_file = fopen(gbk_filename, "rb");
if (!gbk_file) {
printf("Error: Failed to open file '%s'.\n", gbk_filename);
return;
}
// Get the file size.
fseek(gbk_file, 0, SEEK_END);
size_t gbk_size = ftell(gbk_file);
fseek(gbk_file, 0, SEEK_SET);
// Allocate memory for the file content.
char* gbk_content = calloc(gbk_size + 1, sizeof(char));
if (!gbk_content) {
printf("Error: Failed to allocate memory.\n");
fclose(gbk_file);
return;
}
// Read the file content.
size_t bytes_read = fread(gbk_content, sizeof(char), gbk_size, gbk_file);
if (bytes_read != gbk_size) {
printf("Error: Failed to read file '%s'.\n", gbk_filename);
free(gbk_content);
fclose(gbk_file);
return;
}
// Close the file.
fclose(gbk_file);
// Convert the content from GBK to UTF-8.
const char* gbk_encoding = "GBK";
const char* utf8_encoding = "UTF-8";
size_t utf8_size = iconv(gbk_encoding, utf8_encoding, gbk_content, gbk_size, NULL, 0);
char* utf8_content = calloc(utf8_size + 1, sizeof(char));
if (!utf8_content) {
printf("Error: Failed to allocate memory.\n");
free(gbk_content);
return;
}
char* inbuf = gbk_content;
char* outbuf = utf8_content;
size_t inbytesleft = gbk_size;
size_t outbytesleft = utf8_size;
iconv_t conv = iconv_open(utf8_encoding, gbk_encoding);
if (conv == (iconv_t)-1) {
printf("Error: Failed to initialize iconv.\n");
free(utf8_content);
free(gbk_content);
return;
}
size_t result = iconv(conv, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
if (result == (size_t)-1) {
printf("Error: Failed to convert encoding.\n");
free(utf8_content);
free(gbk_content);
iconv_close(conv);
return;
}
// Close the iconv conversion context.
iconv_close(conv);
// Write the UTF-8 content to the file.
FILE* utf8_file = fopen(utf8_filename, "wb");
fwrite(utf8_content, sizeof(char), utf8_size, utf8_file);
fclose(utf8_file);
// Free the memory.
free(utf8_content);
free(gbk_content);
printf("Successfully converted file '%s' from GBK to UTF-8.\n", gbk_filename);
}
```
调用方式:
```c
GBK_to_UTF8("input.txt", "output.txt");
```
以上函数将把`input.txt`文件(假设它是用GBK编码)的内容转换为UTF-8编码,并将转换后的内容写入`output.txt`文件。如需要转换其他编码,可在相应参数更改编码名称。