Thinking in C++

My C++ code snips.

Posts Tagged ‘writing a map’

File To Map Input/Output C++

Posted by Abhi on April 16, 2012

Here are a couple of function that will allow you to write a map to a file that you specify. Currently the type of the map supported is map. The data in the file is separated by “|”. For example: key|value.

This file uses the splitString() function I wrote earlier to split the string while reading into the map from the file.

The header file :


#ifndef FileMapIO_H
#define FileMapIO_H

#include <map>
#include <string>

bool mapToFile(const std::string &, const std::map<std::string,std::string> &);
bool fileToMap(const std::string &, std::map<std::string,std::string> &);

#endif

Implementation :

#include "fileMapIO.h"
#include <string>
#include <map>
#include <fstream>
#include <vector>
#include "splitString.h"

using std::string;
using std::map;
using std::ofstream;
using std::ifstream;
using std::vector;

typedef map<string,string> stringMap;

bool mapToFile(const string &filename,const stringMap &fileMap)		//Write Map
{
	ofstream ofile;
	ofile.open(filename.c_str());
	if(!ofile)
	{
		return false;			//file does not exist and cannot be created.
	}
	for(stringMap::const_iterator iter= fileMap.begin(); iter!=fileMap.end(); ++iter)
	{
		ofile<<iter->first<<"|"<<iter->second;
		ofile<<"\n";
	}
	return true;
}
bool fileToMap(const std::string &filename, stringMap &fileMap)  //Read Map
{
	ifstream ifile;
	ifile.open(filename.c_str());
	if(!ifile)
		return false;  	//could not read the file.
	string line;
	string key;
	vector<string> v_str;
	while(ifile>>line)
	{
		splitString(v_str,line,'|');
		for(vector<string>::iterator iter = v_str.begin();;++iter)		//First vector element is the key.
		{
			if(iter == v_str.begin())
			{
				fileMap[*iter]="Unavailable";
				key= *iter;
				continue;
			}
			fileMap[key]= *iter;
			break;
		}
	}
	return true;
}

Advertisements

Posted in C++ | Tagged: , , , , , | Leave a Comment »