Hello,

I am saving data to a file "myfile.dat". Every time I save new data, I want to eliminate the existing file and start a new file. From what I know, setting the ios::trunc flag should do this. However, I also want to create the file if no file exisits. So, the first the program is run, a new file "myfile.dat" is created, and every subsequent time, the data in this file should be eliminated and new data should be written.

But just setting the ios::trunc flag does not seem to create a new file if the file does not exist. If I don't set the ios::trunc flag, then it does create a new file if one does not exist - but then the existing data in the file is not erased, and the new data is simply appendd to the end.

Thanks.

Here is my code, which writes 4 integars and then reads back the last integar in the file.

Code:
        int length = sizeof(int);
	ofstream out("myfile.dat", ios::out | ios::binary | ios::app | ios::trunc);
	for (int x = 0; x < 5; x++)
	{
		out.write((char*)&x, sizeof(int));
	}
	out.close();

	ifstream in("myfile.dat", ios::in | ios::binary);
	if (!in.is_open())
	{
		cout << "Cannot open file." << endl;
	}
	int y;
	in.seekg(-length, ios::end);
	in.read((char*)&y, sizeof(int));
	in.close();