Problems writing to the end of a binary file

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 ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 #include <iostream>
#include <fstream>
using namespace 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");
}

thanks in advance to anyone who can help
it just seems to write a new file,
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.
Topic archived. No new replies allowed.