gpt4 book ai didi

c - 使用fopen/write时出现汉字问题

转载 作者:行者123 更新时间:2023-11-30 14:36:22 30 4
gpt4 key购买 nike

我必须将配置信息写入Linux中的文件,而配置信息包含中文字符。

我不使用 wchar_t,而是使用 char 数组,这是正确的吗?

这是我的代码:

code in paster.ubuntu

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#define MSG_LEN 4096

int save_config_info(const char *path, char* message)
{
FILE *fp = NULL;

fp = fopen(path, "wb");
if (!fp)
{
//print error message
return -1;
}

if (fwrite(message, 1, strlen(message), fp) != strlen(message))
{
//print error message
fclose(fp);
return -1;
}

fclose(fp);
return 0;
}

int main()
{
//config contain chinese character
char str[MSG_LEN] = "配置文件中包含中文";
char path[PATH_MAX] = "example.txt";
save_config_info(path,str);

return 0;
}

如果源代码编码是ISO-8859-1,则生成example.txt并使用cat显示一些???。

但是将源代码编码更改为utf-8,一切正常。

我的问题是:

有没有什么优雅的方法来处理中文字符,因为我无法确保源文件编码。

我希望 example.txt 看起来总是正确的。

[root workspace]#file fork.c
fork.c: C source, ASCII text
[root workspace]#gcc -g -o fork fork.c
[root workspace]#
[root workspace]#./fork
[root workspace]#
[root workspace]#
[root workspace]#file example.txt
example.txt: ASCII text, with no line terminators
[root workspace]#
[root workspace]#cat example.txt
?????????[root workspace]#
[root workspace]#
[root workspace]#
[root workspace]#file fork.c
fork.c: C source, UTF-8 Unicode text
[root workspace]#
[root workspace]#gcc -g -o fork fork.c
[root workspace]#./fork
[root workspace]#
[root workspace]#file example.txt
example.txt: UTF-8 Unicode text, with no line terminators
[root workspace]#cat example.txt
配置文件中包含中文[root workspace]#

最佳答案

是否有一种优雅的方式仅使用 ASCII 字符来表示 ASCII 中未找到的字符?没有。

但有可能以一种不优雅的方式做到这一点。

char str[MSG_LEN] = "\xE9\x85\x8D\xE7\xBD\xAE\xE6\x96\x87\xE4\xBB\xB6\xE4\xB8\xAD\xE5\x8C\x85\xE5\x90\xAB\xE4\xB8\xAD\xE6\x96\x87";

当然,就像您的原始程序一样,这假设查看文件名的人(例如使用 ls)具有基于 UTF-8 的区域设置。

关于c - 使用fopen/write时出现汉字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58109711/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com