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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章