关于Protobuf 输入输出中文到文件中的一系列问题

一、不含中文的常规处理

        

//定义
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;

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Vue 3使用Protobuf插件来自动生成Protobuf文件,可以通过以下步骤进行: 1. 首先,确保您已经安装了Vue 3项目所需的依赖,包括protobufjs和protobufjs/cli。您可以使用以下命令进行安装: ``` npm install protobufjs protobufjs/cli --save-dev ``` 2. 创建一个.proto文件,该文件定义了您的消息类型和服务等。例如,创建一个名为example.proto的文件,在其定义您的消息类型和服务: ```protobuf syntax = "proto3"; package example; message User { string name = 1; int32 age = 2; } service UserService { rpc GetUser(UserRequest) returns (UserResponse); } message UserRequest { string userId = 1; } message UserResponse { User user = 1; } ``` 3. 在项目的根目录下创建一个脚本文件,例如generate-protobuf.js,用来运行protobufjs/cli来生成Protobuf文件。在脚本文件添加以下内容: ```javascript const pbjs = require('protobufjs/cli/pbjs');const pbts = require('protobufjs/cli/pbts'); const fs = require('fs'); const protoFile = 'example.proto'; const outputDir = 'src/protobuf'; pbjs.main(['-t', 'static-module', '-w', 'commonjs', '-o', `${outputDir}/example.js`, protoFile], (err, output) => { if (err) { console.error(err); return; } console.log(output); pbts.main(['-o', `${outputDir}/example.d.ts`, `${outputDir}/example.js`], (err, output) => { if (err) { console.error(err); return; } console.log(output); }); }); ``` 4. 运行脚本文件以生成Protobuf文件。在命令行执行以下命令: ``` node generate-protobuf.js ``` 这将使用protobufjs/cli来生成相应的.js和.d.ts文件,并将其输出到指定的目录(在上述示例为src/protobuf)。 5. 现在,您可以在Vue 3项目使用生成的Protobuf文件。在需要使用Protobuf的组件或模块导入生成的.js和.d.ts文件,并使用其定义的消息类型和服务等。 ```javascript import { User, UserRequest, UserResponse } from '@/protobuf/example'; // 使用生成的Protobuf消息类型和服务等 const user = new User(); user.name = 'John'; user.age = 25; const userRequest = new UserRequest(); userRequest.userId = '123'; // ... ``` 通过上述步骤,您可以在Vue 3项目使用Protobuf插件来自动生成Protobuf文件,并使用生成的文件来进行Protobuf相关的操作。请确保按照您的项目结构和需要进行适当的调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值