I'm trying to overwrite my text file with map contents, can anyone give me the idea on that upto to now i did
#include <string.h>
#include <iostream>
#include <map>
#include <utility>
using namespace std;
int main()
{
map<int, string> mymap;
mymap[34] = "hero";
mymap[74] = "Clarie";
mymap[13] = "Devil";
for( map<int,string>::iterator i=mymap.begin(); i!=mymap.end(); ++i)
{
cout << (*i).first << ":" << (*i).second << endl;
}
// write the map contents to file .
// mymap &Emp;
FILE *fp;
fp=fopen("bigfile.txt","w");
if(fp!=NULL)
{
for(map<int,string>::iterator it =mymap.begin();it!=mymap.end();++it)
{
fwrite(&mymap,1,sizeof(&mymap),fp);
}
fclose(fp);
}
}
I'm new to containers. Am i in correct procedure and while writing the map contents to file it is giving me garbage content in file. thanks in advance
Your call to fwrite()
is pretty broken.
fwrite()
will write a series of bytes to the given file. For example, if we wanted to write an int
to the file, we would need to do something like:
int x = 10;
char text[10];
snprintf(text, 10, "%d", x);
fwrite(text, 1, strlen(text), fp);
And for a std::string
, we would need to do something like:
std::string y = "Hello";
fwrite(y.c_str(), 1, y.size(), fp);
Alternatively, you could use fprintf()
:
int x = 10;
std::string y = "Hello";
fprintf(fp, "%d:%s\n", x, y.c_str());
If we use C++'s std::ofstream
, then things are much simpler. In fact, the code will look almost identical to how we use std::cout
.
#include <cassert>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <utility>
using namespace std;
int main() {
map<int, string> mymap;
mymap[34] = "hero";
mymap[74] = "Clarie";
mymap[13] = "Devil";
for(map<int,string>::iterator i=mymap.begin(); i!=mymap.end(); ++i)
cout << i->first << ":" << i->second << "\n";
// write the map contents to file.
std::ofstream output("bigfile.txt");
assert(output.good());
for(map<int,string>::iterator it =mymap.begin();it!=mymap.end();++it)
output << it->first << ":" << it->second << "\n";
}
This will output to the screen and write to bigfile.txt
this:
13:Devil
34:hero
74:Clarie