在C++中关于protobuf的问题使用

news/2024/4/19 0:59:29/文章来源:https://blog.csdn.net/qq_38156743/article/details/130387629

第一次接触这个玩意,正在记录,本人的系统是ubuntu20.04。

0 首先进行安装这个编译器

1安装 protobuf

打开终端,输入以下命令来安装 protobuf:

sudo apt-get update
sudo apt-get install protobuf-compiler libprotobuf-dev
查看是不是安装成功了
protoc --version
如果出现这个
libprotoc 3.6.1  数字表述版本号

2安装好了后进行数据格式的定义

创建一个文件

touch addressbook.proto

在这个文本中输入下面的代码,保存

// [START declaration]
syntax = "proto3";
package tutorial;import "google/protobuf/timestamp.proto";
// [END declaration]// [START messages]
message Person {string name = 1;int32 id = 2;  // Unique ID number for this person.string email = 3;enum PhoneType {MOBILE = 0;HOME = 1;WORK = 2;}message PhoneNumber {string number = 1;PhoneType type = 2;}repeated PhoneNumber phones = 4;google.protobuf.Timestamp last_updated = 5;
}// Our address book file is just one of these.
message AddressBook {repeated Person people = 1;
}
// [END messages]

3 对上述文件进行编译

protoc -I=. --cpp_out=. addressbook.proto

在当前目录下进行编译,会生成两个文件一个.cc一个.h文件。

4重新创建一个文件testwrite.cc

#include <ctime>
#include <fstream>
#include <google/protobuf/util/time_util.h>
#include <iostream>
#include <string>#include "addressbook.pb.h"using namespace std;using google::protobuf::util::TimeUtil;// This function fills in a Person message based on user input.
void PromptForAddress(tutorial::Person *person)
{cout << "Enter person ID number: ";int id;cin >> id;person->set_id(id);cin.ignore(256, '\n');cout << "Enter name: ";getline(cin, *person->mutable_name());cout << "Enter email address (blank for none): ";string email;getline(cin, email);if (!email.empty()){person->set_email(email);}while (true){cout << "Enter a phone number (or leave blank to finish): ";string number;getline(cin, number);if (number.empty()){break;}tutorial::Person::PhoneNumber *phone_number = person->add_phones();phone_number->set_number(number);cout << "Is this a mobile, home, or work phone? ";string type;getline(cin, type);if (type == "mobile"){phone_number->set_type(tutorial::Person::MOBILE);}else if (type == "home"){phone_number->set_type(tutorial::Person::HOME);}else if (type == "work"){phone_number->set_type(tutorial::Person::WORK);}else{cout << "Unknown phone type.  Using default." << endl;}}*person->mutable_last_updated() = TimeUtil::SecondsToTimestamp(time(NULL));
}// Main function:  Reads the entire address book from a file,
//   adds one person based on user input, then writes it back out to the same
//   file.
int main(int argc, char *argv[])
{// Verify that the version of the library that we linked against is// compatible with the version of the headers we compiled against.GOOGLE_PROTOBUF_VERIFY_VERSION;if (argc != 2){cerr << "Usage:  " << argv[0] << " ADDRESS_BOOK_FILE" << endl;return -1;}tutorial::AddressBook address_book;{// Read the existing address book.fstream input(argv[1], ios::in | ios::binary);if (!input){cout << argv[1] << ": File not found.  Creating a new file." << endl;}else if (!address_book.ParseFromIstream(&input)){cerr << "Failed to parse address book." << endl;return -1;}}// Add an address.PromptForAddress(address_book.add_people());{// Write the new address book back to disk.fstream output(argv[1], ios::out | ios::trunc | ios::binary);if (!address_book.SerializeToOstream(&output)){cerr << "Failed to write address book." << endl;return -1;}}// Optional:  Delete all global objects allocated by libprotobuf.google::protobuf::ShutdownProtobufLibrary();return 0;
}

5.1如果你不是在IDE下进行编译的就直接G++编译

g++ testwrite.cc addressbook.pb.cc -o testwrite -lprotobuf -lthread
生成一个testwrite文件,可以进行运行。

5.2运行命令

./testwrite addressbook.data
后面跟着这个addressbook.data意思是创建一个addressbook.data这样的二进制文件,进行数据储存。
运行后进行数据的写入,写入的内容就是你刚才定义的那个数据格式。
全部写完后结束。

6 下面进行读取刚才写入的数据

创建一个代码读的代码
touch testread.cc

#include <fstream>
#include <google/protobuf/util/time_util.h>
#include <iostream>
#include <string>#include "addressbook.pb.h"using namespace std;using google::protobuf::util::TimeUtil;// Iterates though all people in the AddressBook and prints info about them.
void ListPeople(const tutorial::AddressBook &address_book)
{for (int i = 0; i < address_book.people_size(); i++){const tutorial::Person &person = address_book.people(i);cout << "Person ID: " << person.id() << endl;cout << "  Name: " << person.name() << endl;if (person.email() != ""){cout << "  E-mail address: " << person.email() << endl;}for (int j = 0; j < person.phones_size(); j++){const tutorial::Person::PhoneNumber &phone_number = person.phones(j);switch (phone_number.type()){case tutorial::Person::MOBILE:cout << "  Mobile phone #: ";break;case tutorial::Person::HOME:cout << "  Home phone #: ";break;case tutorial::Person::WORK:cout << "  Work phone #: ";break;default:cout << "  Unknown phone #: ";break;}cout << phone_number.number() << endl;}if (person.has_last_updated()){cout << "  Updated: " << TimeUtil::ToString(person.last_updated()) << endl;}}
}// Main function:  Reads the entire address book from a file and prints all
//   the information inside.
int main(int argc, char *argv[])
{// Verify that the version of the library that we linked against is// compatible with the version of the headers we compiled against.GOOGLE_PROTOBUF_VERIFY_VERSION;if (argc != 2){cerr << "Usage:  " << argv[0] << " ADDRESS_BOOK_FILE" << endl;return -1;}tutorial::AddressBook address_book;{// Read the existing address book.fstream input(argv[1], ios::in | ios::binary);if (!address_book.ParseFromIstream(&input)){cerr << "Failed to parse address book." << endl;return -1;}}ListPeople(address_book);// Optional:  Delete all global objects allocated by libprotobuf.google::protobuf::ShutdownProtobufLibrary();return 0;
}

7创建完了进行编译直接G++编译

g++ testread.cc addressbook.pb.cc -o testwrite -lprotobuf -lthread

8然后运行

./testread addressbook.data

就会打印出来你刚才的数据。

*******如果用IDE的就添加CMakeLists.txt

cmake_minimum_required(VERSION 3.1)set(CMAKE_CXX_STANDARD 14)
project(write)include_directories(${CMAKE_CURRENT_SOURCE_DIR})add_executable(write testwrite.cpp testread.cpp addressbook.pb.cc addressbook.pb.h )target_link_libraries(write PRIVATE protobuf pthread)

作者 :https://blog.csdn.net/qq_41950508/article/details/127126215

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_103874.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Win11打开移动热点后电脑无法上网怎么办?

Win11打开移动热点后电脑无法上网怎么办&#xff1f;有用户将自己的电脑开启移动热点来使用的时候&#xff0c;发现自己的电脑出现了无法上网的情况。那么为什么开启热点之后&#xff0c;就会无法进行上网呢&#xff1f;来看看以下的解决方法分享吧。 Win11打开移动热点无法上网…

【Python】matplotlib画散点图,并根据目标列的类别来设置颜色区间(含源代码及参数解释)

最近在进行绘图时&#xff0c;遇到了matplotlib画散点图&#xff0c;并根据目标列的类别来设置颜色区间的问题&#xff0c;但是实现的过程较为艰辛。 文章目录 一、数据准备二、第一次尝试&#xff08;失败及其原因&#xff09;2.1 失败2.2 原因 三、第二次尝试&#xff08;成功…

算法记录lday3 LinkedList 链表移除 + 链表构建 + 链表反转reverse

今日任务 ● 链表理论基础 ● 203.移除链表元素 ● 707.设计链表 ● 206.反转链表 链表理论基础 建议&#xff1a;了解一下链接基础&#xff0c;以及链表和数组的区别 文章链接&#xff1a;https://programmercarl.com/%E9%93%BE%E8%A1%A8%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A…

JavaWeb搭建| Tomcat配置| Maven依赖|这一篇就够了(超详细)

&#x1f648;作者简介&#xff1a;练习时长两年半的Java up主 &#x1f649;个人主页&#xff1a;老茶icon &#x1f64a; ps:点赞&#x1f44d;是免费的&#xff0c;却可以让写博客的作者开兴好久好久&#x1f60e; &#x1f4da;系列专栏&#xff1a;Java全栈&#xff0c;计…

记录自己第一次项目管理(附件:WBS计划与会议纪要模板)

记录自己第一次项目管理 前言 20**年新入职到一家公司&#xff0c;刚到就接到紧急任务&#xff0c;因为上一个后端跑路&#xff0c;现在系统上出现接口报错、假接口的问题&#xff0c;客户又着急验收&#xff0c;所以入职之后&#xff0c;一直在着急改代码。最后因为系统没有…

思科模拟器 | 生成树协议STP、RSTP、HSRP配置

一、生成树协议STP 概念介绍&#xff1a; 生成树协议是一种网络协议&#xff0c;用于在交换机之间建立逻辑上的树形拓扑结构避免产生环路。为了完成这个功能&#xff0c;生成树协议需要进行些配置&#xff0c;包括根桥的选举、端口的状态切换等。 步骤明细&#xff1a; 使用思…

游戏测试的面试技巧

游戏测试的面试技巧 1.自我介绍 回答提示&#xff1a;一般人回答这个问题过于平常&#xff0c;只说姓名、年龄、爱好、工作经验 &#xff0c;这些在简历上都有&#xff0c;其实&#xff0c;企业最希望知道的是求职者能否胜任工作&#xff0c;包括&#xff1a;最强的技能、最深入…

实现PXE批量网络装机及kickstrat无人值守安装(富士山终究留不住欲落的樱花)

一、PXE概述和部署PXE批量装机 1.PXE简介 PXE&#xff08;预启动执行环境&#xff0c;在操作系统之前运行&#xff09;是由Intel公司开发的网络引导技术&#xff0c;c/s架构&#xff0c;允许客户机通过网络从远程服务器下载引导镜像&#xff0c;并加载安装文件或者整个操作系统…

燃气管道定位83KHZ地下电子标识器探测仪ED-8000操作指南

1、电子标识器探测工作 燃气管道定位83KHZ地下电子标识器探测仪ED-8000&#xff0c;探测时周边 3 米范围内不能有其他探测仪&#xff0c;保持探测仪垂直向 下&#xff0c;探测仪的末端距离地面 5~10cm 左右&#xff0c;延估计的埋地管线走向水平移动探测仪。当发现持续信号且信…

RuntimeError: “LayerNormKernelImpl“ not implemented for ‘Long‘解决方法

问题出现的场景&#xff1a; 输入&#xff1a; import torch import torch.nn as nn atorch.randint(10,[3,4]) # atorch.DoubleTensor(a) # aa.double() print(a) layer_normnn.LayerNorm(4) layer_norm(a) 我就是想测试一下经过layernorm之后的输出会变成什么样 但是报错…

量表题如何分析?

量表是一种测量工具&#xff0c;量表设计标准有很多&#xff0c;并且每种量表的设计都有各自的特性&#xff0c;不同量表的特性也决定了测量尺度&#xff0c;在数据分析中常用的量表为李克特量表。李克特量表1932年由美国社会心理学家李克特在当时原有总加量表的基础上进行改进…

eBPF的发展演进---从石器时代到成为神(二)

3. 发展溯源 回顾技术的发展过程&#xff0c;就像观看非洲大草原日出日落一样&#xff0c;宏大的过程让人感动&#xff0c;细节部分引人深思。每天循环不辍&#xff0c;却又每天不同。 BPF的应用早已超越了它最初的设计&#xff0c;但如果要追溯BPF最初的来源&#xff0c;则必…

kubernetes为何需要默认的serviceaccount?

文章目录 什么是k8s的serviceAccount&#xff1f;为什么每一个ns下都有默认的sa&#xff1f;default sa yaml 默认的sa下都会挂一个secret&#xff0c;这个secret是从哪里来的&#xff1f;一道关于RBAC的CKA考题1、创建一个新的 ServiceAccount2、创建一个新的 Role3、创建一个…

2023_8.0.33版windows版MySql安装_配置远程连接_修改设置初始密码---MySql工作笔记0001

MySQL :: Download MySQL Community Server https://dev.mysql.com/downloads/mysql/ 首先去下载mysql 可以看到这里下载第一个就可以了,最新版的8.0.33 这里点击仅仅下载 just start my download 然后解压到一个文件夹,然后配置一下环境变量 然后新建一个my.ini文件 然后把…

【GNN】谱域图卷积

谱域图卷积 1. 谱域卷积的背景知识 1.1 谱域图卷积实现思路 f 1 ( t ) ⋆ f 2 ( t ) F − 1 [ F 1 ( w ) F 2 ( w ) ] f_1(t) \star f_2(t) F^{-1}[F_1(w)F_2(w) ] f1​(t)⋆f2​(t)F−1[F1​(w)F2​(w)] 1.2 如何定义图上的傅里叶变换 经典傅里叶变换&#xff1a; x ( …

速卖通正式推出全托管,卖家竞争进入新阶段

全托管来了&#xff0c;卖家就能安心做甩手掌柜吗&#xff1f; 正式推出全托管 显而易见&#xff0c;越来越多的平台正在转向全托管模式。 近日&#xff0c;速卖通在2023年度商家峰会上&#xff0c;正式推出了全托管服务模式。官方表示&#xff0c;托管是对速卖通平台商家服…

golang微服务项目通用流水线

golang微服务项目通用流水线 工作中随着业务越来越大&#xff0c;微服务的项目也越来越多&#xff0c;最开始的时候是一个服务一个流水线&#xff0c;然后还分了三个环境&#xff0c;也就是一个服务三个流水线&#xff0c;后面就越来越不利于管理维护了&#xff0c;因此&#…

持续集成——App自动化测试集成实战

这里写目录标题 一、app自动化测试持续集成的好处二、环境准备三、Jenkins节点挂载四、节点环境的配置1、JDK2、模拟器3、sdk环境4、Python3环境5、allure-commandline工具6、allure插件 五、本地运行待测代码(保证代码没有问题)六、库文件的导出七、Jenkins上运行代码配置1、指…

Visual Studio C# WinForm开发入门(4):概述

目录 一.Winform入门1.WinForm项目结构2.窗口设计与控件布局3.窗口事件4.时间显示器小练习 二.WinForm布局开发1.手动布局解决自适应问题2.WinForm布局属性3.WinForm布局器 三.WinForm常用控件1.界面展示2.实体类 Student(封装信息)3.逻辑事件代码Form.cs 四.图片框与项目资源1…

智慧班牌源码,使用springboot框架Java+vue2开发,二次开发方便快捷

智慧校园云平台电子班牌系统源码 智慧校园平台电子班牌系统源码在大数据平台下&#xff0c;对应用系统进行统一&#xff0c;以数据互联软硬结合的特点应用在校园&#xff0c;实现对校园、班级、教师、学生的管理。 智慧校园云平台电子班牌系统源码&#xff0c;使用springboot…