从txt文件中读取出json格式的文本,用jsoncpp解析
一、读取文本文件
方法1:
#include// std::cout#include // std::ifstream
std::ifstream is ("test.txt", std::ifstream::binary); if (is) { // get length of file: is.seekg (0, is.end); int length = is.tellg(); is.seekg (0, is.beg); char * buffer = new char [length]; std::cout << "Reading " << length << " characters... "; // read data as a block: is.read (buffer,length); if (is) std::cout << "all characters read successfully."; else std::cout << "error: only " << is.gcount() << " could be read"; is.close(); // ...buffer contains the entire file... delete[] buffer; 上面的代码将txt文本读到了buffer中, 代码来自:istream::read - C++ Reference http://www.cplusplus.com/reference/istream/istream/read/ delete buffer之前,用jsoncpp转成json:
Json::Reader reader;
Json::Value root; bool parsingSuccessful = reader.parse(buffer, root );然后可以参考上篇Jsoncpp学习中的方法进行解析
二、 读取文本文件
string slocal_path = "e:\\temp\\wxxs001.txt";
std::ifstream is (slocal_path.c_str(), std::ifstream::binary);
if (!is) { return 0; }//读取"utf8.txt"
//in.open("utf8.txt"); //过滤文本开始efbbbf三个字节 //char b; //is>>b; //is>>b; //is>>b;
//注:上面过滤文本文件开始的三个字节,实际应用中发现有时候不用过滤,过滤反而出错,有时候却必须要过滤一下。
string strUtf8;
is>>strUtf8; is.close(); //cout<<Utf8ToGbk(strUtf8)<<endl;//转成gbk输出//转换成json
Json::Reader reader;
Json::Value root;
bool parsingSuccessful = reader.parse(strUtf8, root );