读取复杂文件以配对<字符串,对<映射<字符串,字符串>字符串> > C++
Read a complex file to pair <string,pair<map<string,string> string> > C++
所以我们基本上想要读取一个由一些不同段组成的文本文件到我们的程序中:
程序中的结构是一个缓存,带有:pair data>>
文件中的结构是(其中key既用作键又用作段之间的分隔符)
key
headerKey : headerValue
headerKey : headerValue
......................
headerKey : headerValue
key
data
data
...
data
key
我们一直在尝试使用以下方法读取此内容,但它不读取日期格式(RFC1123)。我们只得到headerValues中的日期为"08 Gmt"或类似的"XX Gmt"。下面我们的读取算法的问题是,我们使用作为分隔符,但它以不同的含义出现在日期格式中,即分割时间:
try{
// Create stream
ifstream ifs(this->cacheFile.c_str(), ios::binary);
// Read file to cache if stream is good
if(ifs.good()){
while (! ifs.eof() ){
map<string,string> headerPairs;
string tmp;
string key;
string data;
getline(ifs, tmp);
while(tmp.empty()){
getline(ifs, tmp);
cout << "Empty line..." << "n";
if(ifs.eof()){
cout << "End of File.."<< "n";
break;
}
}
//After empty lines get "Key"
key = tmp;
getline(ifs, tmp);
//Get segment of header pairs
while(tmp != key){
StringTokenizer headerPair(tmp, ":", StringTokenizer::TOK_TRIM);
//StringTokenizer::Iterator it = headerPair.begin();
std::cout << *(headerPair.begin()) <<": " << *(headerPair.end()-1)<< std::endl;
string headerKey = *(headerPair.begin());
string headerValue = *(headerPair.end()-1);
headerPairs.insert(make_pair(headerKey, headerValue));
getline(ifs, tmp);
}
cout << "Added " << headerPairs.size() << " header pairs from cache" << "n";
//tmp equals Key
while(tmp!=key){
getline(ifs, tmp);
cout << "Searching for header->data delimiter" << "n";
}
cout << "Found header->data delimiter" << "n";
//Get segment of data!
getline(ifs, tmp);
while(tmp != key){
data+=tmp;
getline(ifs, tmp);
}
cout << "DATA: " << data << "n";
cout << "Ending delimiter:" << tmp << "n";
this->add(key,make_pair(headerPairs, data));
cout << "Added: " << key << " to memory-cache" << endl;
}
ifs.close();
}
}
catch (Exception &ex){
cerr << ex.displayText() << endl;
}
请建议一个更好的方法来获取日期字符串:
DateTime now : Mon, 29 Apr 2013 08:15:57 GMT
DateRetrieved from file: 57 GMT
简而言之:问题是我们正在使用:作为标头的分隔符,我想建议另一个分隔符标志,即它不会在HTTP 1.0或1.1标头中找到。
你找不到一个故障安全分隔符,因为有人可能总是在数据中使用这个参数。
但是,在插入分隔符之前,应该转义数据中出现的任何分隔符。CSV是这样做的:"Date","Pupil","Grade"
"25 May","Bloggs, Fred","C"
"25 May","Doe, Jane","B"
"15 July","Bloggs, Fred","A"
"15 April","Muniz, Alvin ""Hank""","A"
(当数据中有双引号需要转义时,请注意双引号")
即使这种将字符加倍的方法是常用的,最常用的转义分隔符的方法是在字符前添加反斜杠''。
如果你想了解更多,你可以查看维基百科的相关页面