c语言 读取json 文件 文件时GB2312的
如果要读取GB2312编码的JSON文件,可以使用以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main() {
char buffer[BUFFER_SIZE];
FILE *file = fopen("data.json", "rb");
if (file == NULL) {
printf("Failed to open file\n");
return 1;
}
size_t bytesRead;
while ((bytesRead = fread(buffer, 1, BUFFER_SIZE, file)) > 0) {
// Convert GB2312 to UTF-8
char *utf8 = (char *)malloc(bytesRead * 3 + 1);
size_t utf8Length = gb2312_to_utf8(buffer, bytesRead, utf8, bytesRead * 3 + 1);
utf8[utf8Length] = '\0';
// Parse JSON
cJSON *json = cJSON_Parse(utf8);
if (json == NULL) {
printf("Failed to parse JSON\n");
free(utf8);
fclose(file);
return 1;
}
// Do something with the JSON
// ...
cJSON_Delete(json);
free(utf8);
}
fclose(file);
return 0;
}
size_t gb2312_to_utf8(const char *gb2312, size_t gb2312Length, char *utf8, size_t utf8Size) {
iconv_t converter = iconv_open("UTF-8", "GB2312");
if (converter == (iconv_t)-1) {
printf("Failed to open converter\n");
return 0;
}
size_t utf8Length = utf8Size - 1;
char *inPtr = (char *)gb2312;
char *outPtr = utf8;
size_t inBytesLeft = gb2312Length;
size_t outBytesLeft = utf8Length;
size_t result = iconv(converter, &inPtr, &inBytesLeft, &outPtr, &outBytesLeft);
if (result == -1) {
printf("Conversion error\n");
utf8Length = 0;
} else {
utf8Length = utf8Size - outBytesLeft - 1;
}
*outPtr = '\0';
iconv_close(converter);
return utf8Length;
}
这个代码片段使用了iconv库将GB2312编码的字符串转换为UTF-8编码的字符串,并使用cJSON库解析JSON字符串。注意,这个代码片段假设文件中的JSON对象不会跨越多个缓冲区。如果要处理这种情况,需要使用额外的代码来拼接缓冲区中的字符串。
原文地址: https://www.cveoy.top/t/topic/bSGF 著作权归作者所有。请勿转载和采集!