Click to See Complete Forum and Search --> : Reading/Writing structure to file and at particular positions


paulina_lui
May 7th, 2003, 04:44 PM
Hi All,


I want to Read/Write a structure like this from/to a file


struct{

char[12] id;
int height;
int width;
}


Now some times the structure with same id will be written to the file more then once, so I wan't to write all the structures with same id together.


But the structures with same ids don't come together for example the program flow can be like this...


write strcut1 (id="hey")
write strcut2(id="hola")
write strcut3(id="aloha")
write strcut4 (id="hi")
write strcut5 (id="hey")


So I wan't to write all the structs with id hey together, as I have to read from this file later on to print a summary report of how many times one particular id came and corresponding struct values.

So if I write them one after the other as they come without any sorting, I will have to parse the whole file again and again for each id, but however if all of the same ids are written together, I can get the repetition count for the moment the id changes


if(struct id is not different)
count++;


I am not very good at c, but have been told that for file io its the fastest and is the way to go, because in my case the file can get big.

Have worked in C++/MFC, but never really with the file ios and stuff.

So any help is greatly appreciated and VERY MUCH NEEDED :-)


Pauli

kuphryn
May 7th, 2003, 05:19 PM
One solution is read() and seekg(). Pass read() the size of the structure. Call seekg() to transfer memory in terms of each structure in memory, not byte.

Kuphryn

paulina_lui
May 7th, 2003, 06:05 PM
Also with these functions will I be able to write at a specific position in the file,like if there are three structures already there,

can I write after the 2nd one, so that the structure that was third earlier now becomes fourth and so one....


I am not at all familiar to file IO and more so in c/c++ only,
if you can send some example it would be great...

Also can MFC be used here, I know it might be right place to ask this, but would using MFC be easier.



Thanks for your time....

kuphryn
May 8th, 2003, 12:54 AM
MFC can be simplier via CArchive. However, i recommend C++ core fstream for this problem.


ofstream output;
output.open("filename.dat", ios::binary);
output.seekp(0, 2*sizeof(data));
output.write(reinterpret_cast<char *>(&data), sizeof(data));
output.close();


Kuphryn

paulina_lui
May 8th, 2003, 01:13 AM
so data is the structure that I plan to use right,

also now I am planning to sort before writingto file,is there a way of storing and sorting data using some standard c++


Thanks a lot for your time

kuphryn
May 8th, 2003, 01:18 AM
One solution is an STL container such as a set. There is no elegant solution as far as sorting data already saved to disk.

Kuphryn