FileStorage 文件读写操作

本片博客重点利用FileStorage 进行文件读写操作练习;

创建一个common.hpp文件,存放结构体

#ifndef common_hpp
#define common_hpp

#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core/core.hpp>
typedef struct my_struct
{
    int     m_value;
    CvPoint st_Point;
    CvRect  st_Rect;
}MY_STRUCT;

extern void write_my_struct(CvFileStorage * fs,const char * name,MY_STRUCT *ms);
extern void read_my_struct(CvFileStorage * fs,CvFileNode * ms_node,MY_STRUCT *ms);

创建main函数进行文件读写操作

 #include <iostream>
    #include "common.hpp"

    using namespace std;
    using namespace cv;

    void write_my_struct(FileStorage fs,const char *name,my_struct *mt)
    {
        fs <<name<< "[";//结构数组开始的标志
        fs<<"{:";//一个结构体开始的标志,yml才有:,xml自动忽略
        fs<<"val"<<mt->m_value;
        fs<<"ptx"<<mt->st_Point.x;
        fs<<"pty"<<mt->st_Point.y;
        fs<<"rtx"<<mt->st_Rect.x;
        fs<<"rty"<<mt->st_Rect.y;
        fs<<"}";//结构体结束的标志,自动换行
        fs << "]";//结构体数组结束的标志。
        
    }

    void read_my_struct(FileStorage fs,FileNode my_node,my_struct *mt)
    {
        
        FileNodeIterator fni = my_node.begin();
        FileNodeIterator fniEnd = my_node.end();
        for(;fni != fniEnd;fni++)//遍历
        {
            mt->m_value    = (int )(*fni)["val"];
            mt->st_Point.x = (int )(*fni)["ptx"];
            mt->st_Point.y = (int)(*fni) ["pty"];
            mt->st_Rect.x  = (int)(*fni) ["rtx"];
            mt->st_Rect.y  = (int)(*fni) ["rty"];
        }
    }

    int main(int argc, const char * argv[]) {
        const char filename[] = "OpenCV.yml";
        const char stname[]   = "My_Strcut";
        /*1.结构体初始化*/
        my_struct mt = {0};
        mt.m_value = 10;
        mt.st_Point.x = 20;
        mt.st_Point.y = 30;
        mt.st_Rect.x  = 40;
        mt.st_Rect.y  = 50;
        
        /*2.FileStorage文件写操作*/
        FileStorage fs(filename, FileStorage::WRITE);
        write_my_struct(fs,stname,&mt);
        fs.release(); //重要
        
        /*3.文件读操作*/
        cv::FileStorage fs2(filename,FileStorage::READ);
        FileNode features = fs2[stname];//读取结构体数组
        my_struct st_new = {0};
        read_my_struct(fs2,features,&st_new);
        fs2.release();
        
        /*4.显示读取结果*/
        cout<<st_new.m_value<<endl;
        cout<<st_new.st_Point.x<<endl;
        cout<<st_new.st_Point.y<<endl;
        cout<<st_new.st_Rect.x<<endl;
        cout<<st_new.st_Rect.y<<endl;
        return 0;
    }

注意:

写函数中Open.yml的存储位置:在xcode的工程Debug文件夹下


该文件的存储 内容:


读取文件的结果:


发布了177 篇原创文章 · 获赞 13 · 访问量 13万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章