I have to write config info to a file in Linux, while the config info contains Chinese characters.
Instead of using wchar_t
,I just using char array, is this correct?
Here is my code :
#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;
}
If the source code encoding is ISO-8859-1, generate the example.txt and using cat to show with some????.
But change the source code encoding with utf-8, everything works well.
My question is:
Is there any elegant way to deal with the Chinese character, since I cannot ensure the source file encoding.
I want the example.txt looks always right.
[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]#