Is the below code efficient for parsing the file, or do I face performance issues? If the latter, please offer suggestions.
#include <iostream>
#include <fstream>
#include <map>
using namespace std;
ofstream outfile;
void writedata(string data, string file)
{
outfile.open(file.c_str(), ios::app);
outfile << data;
outfile.close();
}
int main()
{
ifstream input("data.txt", ios::in);
ofstream out;
string line;
string tmp;
string data;
string filename;
string name;
size_t found;
map<string, string> MyFileMap;
map<string, string>::iterator it;
while (input >> line)
{
found = line.find_last_of("pmf");
if (found != string::npos)
{
name = line.substr(found + 1, line.length());
filename = line.substr(found + 1, line.length());
cout << "filename without txt " << filename << endl;
for (it = MyFileMap.begin(); it != MyFileMap.end(); ++it)
{
if (name.compare(it->first) == 0)
{
while (input >> tmp && tmp.compare("pme"))
{
data += tmp;
}
cout << "Data push " << data << " to " << it->second << endl;
writedata(data, it->second);
data.clear();
break;
}
}
if (it == MyFileMap.end() || MyFileMap.empty())
{
cout << "No match in map" << endl;
filename = filename + ".txt";
cout << "Filename " << filename << endl;
while (input >> tmp && tmp.compare("pme"))
{
data += tmp;
}
cout << "Data push " << data << " to " << it->second << endl;
out.open(filename.c_str());
MyFileMap[name] = filename;
for (it = MyFileMap.begin(); it != MyFileMap.end(); ++it)
{
if (name.compare(it->first) == 0)
{
writedata(data, it->second);
data.clear();
break;
}
}
}
}
}
system("pause");
}
sample file : data.txt
pmfwork1
data1
data1
pme
pmfwork2
data2
data2
pme
pmfwork3
data3
data3
pme
pmfwork4
data4
data4
pme
In the above code, I am trying to parse the sample file with pmf
and pme
as begin and end flags, work
as the file name, and data
as file contents. Below is the sample file.
I would like to reduce the use of open call for multiple times. It would be of great help if you provide any suggestions.
Above code is generating four different text files: work1, work2 and so on.