C++读写文件之在Json数组追加元素
2018-02-09 12:03
519 查看
#include <iostream> #include <string> #include <fstream> #include <sstream> #include <cassert> #include "json/json.h" #include <vector> #include <unistd.h> using namespace std; struct Person{ string name; string ID; int age; }pinfo; void parseFile(string &path, Json::Value &root, struct Person info){ std::ifstream ifs; Json::Reader reader; ifs.open(path); if(reader.parse(ifs, root,false) != true){ cout <<"line: " << __LINE__ << " parse error..." << " root.size = " << root.size() << endl; ifs.close(); } if(ifs.is_open()) ifs.close(); } void writeJson(string &path, struct Person info) { std::ofstream fout; Json::Value root; Json::Reader reader; std::ifstream ifs; parseFile(path, root, info); Json::Value array = root["array"]; Json::Value item; item["name"] = info.name; item["ID"] = info.ID; array.append(item); root["array"] = array; fout.open(path); fout << root.toStyledString(); fout.close(); } void readJson(string &path, Json::Value &root) { std::ifstream ifs; Json::Reader reader; //Json::Value root; ifs.open(path); if (!reader.parse(ifs, root,false)){ ifs.close(); return; } ifs.close(); } int main(){ string path = "123.txt"; Json::Value root; pinfo.name = "小黑"; pinfo.ID = "0.8 0.7 0.6 0.5 0.4 0.3"; writeJson(path, pinfo); readJson(path, root); Json::Value arrayObj = root["array"]; cout << "arrayObj.size = " << arrayObj.size() << endl; for(unsigned int i = 0; i < arrayObj.size(); i++){ cout << "name = " << arrayObj[i]["name"].asString() << endl; cout << "ID = " << arrayObj[i]["ID"].asString() << endl; } } jsoncpp库:https://gitee.com/Tocy/SampleCode/tree/master/JsonCppTutorial
相关文章推荐
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C/C++ 二进制 追加读写文件
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- 【转载】C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- c++简单读写文本,统计文件的行数,读取文件数据到数组
- 读取读写C++文件读写操作(四)读取文件数据到临时数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ Json 对文件的读写操作
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- [C++]读写txt文件和从txt文件中读取数据写入数组中
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组 (转)
- C++通过jsoncpp类库读写JSON文件
- C++文件读写操作(四)读取文件数据到临时数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组