xml和yml文件 读写操作

#include<opencv2/opencv.hpp>
#include <Windows.h>
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
	system("color 4E");
	String filename = "datas.yml";
	//cv::  增加代码可读性    如文件不存在 XML或YML文件会自动生成
	cv:: FileStorage fwrite(filename, cv:: FileStorage::WRITE);
	//存入矩阵mat类型的数据
	Mat mat = Mat::eye(3, 3, CV_8U);
	//使用write()函数写入数据
	fwrite.write("mat", mat);
	float x = 100;
	fwrite << "x" << x;
	//存入字符串型数据,节点名称为str
	String str = "Learn Opencv 4";
	fwrite << "str" << str;
	//存入数据,节点名称为number_array
	fwrite << "number_array" << "[" << 4 << 5 << 6 << "]";
	//存入多node节点数据,主名称为multi_nodes
	fwrite << "multi_nodes" << "{" << "month" << 8 << "day" << 28 << "year" << 2021 << "time"
		<< "[" << 0 << 1 << 2 << 3 << "]" << "}";
	//数据写完后  关闭文件
	fwrite.release();
    /*************************************************************************************************/
	
	//以读取的模式打开文件
	cv::FileStorage fread(filename, FileStorage::READ);
	//判断是否成功打开了文件
	if (!fread.isOpened())
	{
		::MessageBox(NULL, L"文件不存在!", L"错误信息", MB_OK);
		return -1;
	}
	//读取文件中的数据
	float xRead;
	fread["x"] >> xRead;//读取浮点型数据
	cout << "x=" << xRead << endl;
	//读取字符串数据
	String strRead;
	fread["str"] >> strRead;
	cout << "str=" << strRead << endl;
	//读取含有多个数据的number_array节点
	FileNode fileNode = fread["number_array"];
	int c = 0;
	cout << "number_array=["  ;
	for (FileNodeIterator i = fileNode.begin(); i !=fileNode.end(); i++)
	{
	
		float a;
		*i >> a;
		cout << a ;
		++c;
	/*	if (c== sizeof(fread) / sizeof(fread[0]))*/
	/*	if (c== fileNode.size())*/
		if (c== fileNode.end() - fileNode.begin())
		{
           break ;
		}
			
		cout << ",";
	}
	cout <<"]"<< endl;
  ////读取含有多个子节点的节点数据,不使用FileNode 和 迭代器进行读取
   FileNode fileNode1 = fread["multi_nodes"];
   int month = (int)fileNode1["month"];
   int day = fileNode1["day"];
   int year = fileNode1["year"];

   cout << "month=" << month << "  day=" << day << " year=" << year;
   cout << " time= [";
 
   //for (int i = 0; i < 4; i++)
   //{
	  // int a = fileNode1["time"][i];
	  // cout << a;
	  // if (i == 3)
		 //  break;
	  // cout<< ",";
   //}
   //cout << "]" << endl;
   FileNode fileNode2 = fread["multi_nodes"]["time"];
   c = 0;
   for (FileNodeIterator i = fileNode2.begin(); i != fileNode2.end(); i++)
   {

	   float a;
	   *i >> a;
	   cout << a;
	   ++c;
	   /*	if (c== sizeof(fread) / sizeof(fread[0]))*/
	   	/*	if (c== fileNode.size())*/
	   if (c == fileNode2.end() - fileNode2.begin())
	   {
		   break;
	   }

	   cout << ",";
   }
   cout << "]" << endl;



	return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值