By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,816 Members | 1,332 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,816 IT Pros & Developers. It's quick & easy.

How to write a map to file.

P: 30
hi all,

i want to write a map to a file and then read it again.
but while reading it is not wrorking.

the map declaration is:
Expand|Select|Wrap|Line Numbers
  1. typedef map<int,LogSettings> MapType;
  2. typedef MapType::value_type ValuePair;
  3.  
  4. where LogSettings is a structure:
  5.  
  6. struct LogSettings
  7.       {
  8.             unsigned long dwSession; 
  9.             TCHAR *szFilePath; 
  10.             TCHAR *szInfection; 
  11.             TCHAR *szAction;
  12.             TCHAR *szMessage; 
  13.             TINFECTIONSTATE iAction;
  14.       };
where TINFECTIONSTATE is just a enum.

to write to a file th function is:
Expand|Select|Wrap|Line Numbers
  1. int DataToFile((LogSettings &lgsettings)
  2. {
  3.     MapType Map;
  4.     Map.insert(ValuePair(1,lgsettings));
  5.     FILE* f = fopen("C:\\sample.txt","wb");
  6.                 size_t n = fwrite(&Map,sizeof(Map),1,f);
  7.     fclose(f);
  8.                 return (int)n;
  9. }
while writing the sturcture is initialised to some values.

To read the map:
Expand|Select|Wrap|Line Numbers
  1. MapType Map1;
  2.     FILE* fd = fopen("C:\\sample.txt","rb");
  3.     size_t nm = fread(&Map1,sizeof(Map1),1,fd);
  4.     fclose(fd);
  5.     MapType::iterator iter = Map1.begin();
  6.     //while(iter !=Map1.end())
  7.     {
  8.         cout<<(*iter).first<<endl;
  9.         cout<<(*iter).second.dwSession<<endl;
  10.         cout<<(*iter).second.iAction<<endl;
  11.         cout<<(*iter).second.szAction<<endl;
  12.         cout<<(*iter).second.szFilePath<<endl;
  13.         cout<<(*iter).second.szInfection<<endl;
  14.         cout<<(*iter).second.szMessage<<endl;
  15.     }

if i try to write the sturcture to file and when i read it again it is working properly.but when i take that to map what is the problem??
May 24 '07 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
A map is a binary tree and you cannot write the map directly to disc becuse of the tree-ness and object-ness of the thing.

Instead, unload the map elements and write them do disc individually with separators so you can read them back.

To restore the map, read the disc file and insert the element into an empty map.

By writing to disc using the address of the map ASSUMES the elements are all following that address, like an array. This is not true. The map elements are objects and their data instances could be anywhere in memory.
May 24 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.