ros消息寫入文件和用g++編譯roscpp程序從而讀取消息文件


1.將點雲消息和geometry_msgs消息寫入文件:

    std::stringstream buffer;
    std::time_t t = std::time(nullptr);
    std::tm tm    = *std::localtime(&t);
    buffer << "/home/robot/data/PointCloud." << std::put_time(&tm, "%Y-%m-%d-%H-%M-%S");
    std::string file_name = buffer.str();
    int size     = raw_points_.size();
    int size_int = sizeof(int);
    mkdir("/home/robot/data", S_IRWXU | S_IRWXG | S_IRWXO);
    std::ofstream ofs(file_name, std::ios::binary | std::ios::ate);//std::ios::ate從文件尾部加入
    ofs.write((char *)&size, size_int);//寫入int代表點雲數
    ofs.write((char *)&raw_points_[0], sizeof(RawPoint) * size);
    ofs.close();
    LOG_INFO("Save point cloud to:%s", file_name.c_str());

//std::stringstream 的clear()函數不清空緩存區,所以使用buffer.str("")清空。 buffer.str(""); buffer << "/home/robot/data/RTK." << std::put_time(&tm, "%Y-%m-%d-%H-%M-%S"); file_name.clear();
   file_name
=buffer.str(); size=1;//這里先假定pose大小為1,后期可調為實際緩存的大小。 std::ofstream ofs_gps(file_name,std::ios::binary|std::ios::ate); ofs_gps.write((char *)&size,size_int);//把數據大小以int寫入文件 ofs_gps.write((char *)&gps_,sizeof(geometry_msgs::Pose)*size);//sizeof測量的是數據結構的大小 ofs_gps.close(); LOG_INFO("Save GPS to:%s",file_name.c_str());

2.不使用cmake來編譯包含ros頭文件的程序,使用該程序測試下保存的數據是否有問題

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <ros/ros.h>
#include <geometry_msgs/Pose.h>
int main(){
    std::vector<geometry_msgs::Pose> gps_;
    std::ifstream ifs ("/home/robot/data/RTK.2020-08-27-18-47-15", std::ios::binary | std::ios::in);
    if (ifs.is_open()) {
        size_t size = 0;
        ifs.read(reinterpret_cast<char *>(&size), sizeof(int));
        std::cout<<size<<std::endl;
        gps_.resize(size);//調整容器的大小以裝文件中的消息。
        ifs.read(reinterpret_cast<char *>(&gps_[0]), sizeof(geometry_msgs::Pose) * size);
        ifs.close();
        for (int i=0;i<gps_.size();i++){ 
            std::cout<<"position:"<<gps_[i].position.x<<std::endl
<<gps_[i].position.y<<std::endl
<<gps_[i].position.z<<std::endl
<<"orientation:"<<std::endl
<<gps_[i].orientation.x<<std::endl
<<gps_[i].orientation.y<<std::endl
<<gps_[i].orientation.z<<std::endl
<<gps_[i].orientation.w<<std::endl; } } return 0; }

編譯方式(告知g++庫的位置即可):

g++ -std=c++11 readTimeStamp.cpp -o read -I/opt/ros/kinetic/include -L/opt/ros/kinetic/lib


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM