Hello guys, i'm having trouble with a program that involves writing a structure to the end of a binary file. I've condensed it to just the basics, but the concept is still the same. Below I have one main function with 3 separate parts, the first will get 3 structures from the user and store them to a binary file, the second is "supposed" to add one more structure to the end of the file, then the third simply displays whats on the file. I cannot get the second file to work correctly, it just seems to write a new file, any suggestions on how I can fix this ?
#include <iostream>
#include <fstream>
usingnamespace std;
struct num
{
int number;
};
int main()
{
num object;
// write three simply structures to the file
fstream open("number.dat", ios::out | ios::binary);
if(!open){ "error opening file\n"; }
for (int i = 0; i < 3; i++)
{
cout << "enter number for structure" << i+1 <<endl;
cin >> object.number;
open.write(reinterpret_cast<char *>(& object), sizeof(object));
}
open.close();
/***********************************************************************/
// now I want to add one more to the end of the file
fstream openagain("number.dat", ios::out | ios::binary);
if (!openagain){ "error opening file\n"; }
cout << "enter number for 4th spot\n";
cin >> object.number;
openagain.write(reinterpret_cast<char *>(&object), sizeof(object));
openagain.close();
/**************************************************************************/
// now display all four
fstream look("number.dat", ios::in | ios::binary);
if (!look) {cout << "Error opening file.\n";}
look.read(reinterpret_cast<char *>(&object), sizeof (object));
while (!look.eof())
{
cout << object.number << endl;
look.read(reinterpret_cast<char *>(&object), sizeof(object));
}
look.close();
system("pause");
}
Sure thing, you are opening your file for rewriting, so it is expected for it to replace previous object. Use either ios::app or ios::ate to append information to your file instead of rewriting current info.