一、不含中文的常规处理
//定义
message Value
{
repeated uint32 uiMain = 1;
repeated uint32 uiSub = 2;
}
message Simulate
{
repeated Value data = 1;
}
//文件
data
{
uiMainAds : 36598
uiMainAds : 35675
uiMainAds : 36756
uiSubAds : 16924
uiSubAds : 16488
uiSubAds : 16984
}
data
{
uiMainAds : 36598
uiMainAds : 35675
uiMainAds : 36756
uiSubAds : 16924
uiSubAds : 16488
uiSubAds : 16984
}
1、从文件中读取
//适用于linux 平台,因为可以方便的获取文件描述符
int infile = open("./sys.cfg", O_RDONLY);
if (infile < 0)
{
printf("open sys.cfg failed.\n");
return;
}
google::protobuf::io::FileInputStream fileInput(infile);
if (!google::protobuf::TextFormat::Parse(&fileInput, &m_cfg)) //将文件内容转为m_cfg(SysConfig)
{
printf("Parse sys.cfg failed.\n");
close(infile);
return;
}
close(infile);
//c++ 通用模式
std::ifstream input("./cfg/debugger.cfg", std::ios::in );
if (!input)
{
return false;
}
DebugFile m_cfgFileData;
google::protobuf::io::IstreamInputStream istr( &input);
bool pa = google::protobuf::TextFormat::Parse(&istr, &m_cfgFileData);
2、写入文件(是人可读的,有点类似与json 格式那种)
//c++ 通用模式
std::ofstream ofs("./cfg/test.txt", std::ios_base::out | std::ios_base::binary);
if (!ofs)
{
return false;
}
DebugFile m_cfgFileData;
google::protobuf::io::OstreamOutputStream ostr( &ofs);
google::protobuf::TextFormat::Print(m_cfgFileData, &ostr);
二、如果定义中是bytes ,且值是中文的
//定义
message STParaInfo
{
required bytes strParaName = 1; //参数名称
required ParaType paraType = 2; //参数类型
required uint32 uiValue = 3; //参数值
};
message STSendPara
{
repeated STParaInfo stParaInfos = 1; //参数信息
};
//文件
stSendPara
{
stParaInfos
{
strParaName : "子功能2参数1"
paraType : ParaType_One
uiValue : 1
}
stParaInfos
{
strParaName : "子功能2参数2"
paraType : ParaType_Two
uiValue : 1
}
stParaInfos
{
strParaName : "子功能2参数3"
paraType : ParaType_Four
uiValue : 1
}
}
1、读取,还是可以正常读取,但是获取到的 strParaName 值,是八进制转义字符串,,如果是qt 等使用,使用QString 去转一下,还是可以直接获取到中文字符串的,
2、写入,,如果直接使用上述方式写入,,,文件中的中文 就是八进制转义字符串,,是人不可读的,,如下
strParaName : "\346\265\213\350\257\225\345\215\225\345\205\203 "
三、解决,只能通过自己转换的方式
//ai 编写的转换函数
std::string octalToChinese(const std::string& input) {
std::string result;
size_t i = 0;
while (i < input.length()) {
if (input[i] == '\\' && i + 3 < input.length() &&
input[i + 1] >= '0' && input[i + 1] <= '7' &&
input[i + 2] >= '0' && input[i + 2] <= '7' &&
input[i + 3] >= '0' && input[i + 3] <= '7') {
// Extract the octal sequence
std::string octal = input.substr(i + 1, 3);
// Convert octal string to integer
int octalValue = std::stoi(octal, nullptr, 8);
// Convert integer value to corresponding character
result += static_cast<char>(octalValue);
// Move to the next character after the octal sequence
i += 4;
} else {
// Append regular character to result
result += input[i];
i++;
}
}
return result;
}
//使用
std::ofstream ofs("./cfg/test.txt", std::ios_base::out | std::ios_base::binary);
if (!ofs)
{
return false;
}
//这里用Utf8DebugString 去获取proto mssage 的 字符串 ,然后使用转换函数转换 ,不用序列化是因为序列化的字符串是不可读的
std::string fout = octalToChinese(m_cfgFileData.Utf8DebugString());
ofs << fout;