第二个参数flag指定操作的模式,可以设置为READ说明以只读的方式打开一个文件,或者设置为WRITE,这种情况下,如果文件不存在,则创建一个文件,如果文件已经存在,则会清空当前文件里的内容。还可以设置为APPEND用来打开一个存在的文件,并且可以在原来基础上写入。
第三个参数用来指定文件的编码格式,一般都为UTF-8。
而open成员函数的接口与第二个构造函数接口一致。
bool FileStorage::open(const string& filename, int flags, const string& encoding=string())
2,读取文件内的数据,FileStorage重载的操作符[],用来获得指定的节点内容。
FileNode FileStorage::operator[](const string& nodename) const FileNode FileNode::operator[](const string& nodename) const
上面两个操作符都返回FileNode类型,它是一个子节点类型。
比如:我们想读取<book>结点下的<name>结点,则可以:
FileStorage fs("../config.xml", FileStorage::READ); string book_name; fs["book"] ["name"]>> book_name;
如果要取出A节点下的B结点下的C结点则为fs["A"]["B"]["C"]>>content;要记住所有节点都是在根结点opencv_storage下的,但是访问时忽略它。
而如果需要将数据写入,则简单的写入可以直接用<<运算符,比如增加一个节点为book,内容为theOpenCV:
string book_name=”theOpenCV”; fs<<”book”<<book_name;
最后给出我们程序中读取配置参数的,我们需要4项配置项,上面已经介绍过了:
1 FileStorage fs("../config.xml", FileStorage::WRITE); 2 3 string videoPath; 4 string videoSuffix; 5 Rect roiRect; 6 string imgSavePath; 7 8 fs["videoReadPath"] >> videoPath; 9 fs["videoSuffix"] >> videoSuffix; 10 fs["imgSavePath"] >> imgSavePath; 11 fs["roi"] >> roiRect;