fstream - combine file modes

Hello,

I am trying to open a file using an fstream object.

- I want to open the file with binary access.
- if the file does not exist, I want to create it.
- if the file exists however, I don't want to overwrite it. I would like to edit it.
- I need random access, ios::app does not help.


I tried the following combinations:

1
2
3
4
5
file.open(filename, ios::out | ios::binary);
// This combination works fine but overwrites the file if it already exists.

file.open(filename, ios::in | ios::out | ios::binary);  
// This combination does not create the file if it doesn't exist. It fails to open then. 



I am now using this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// try to open with random access
file.open(filename, ios::in | ios::out | ios::binary);	

// if random access fails, try to create file and re-open
if (!file.is_open())				
{
	// create
	file.open(filename, ios::out | ios::binary); 

	// close
	if (file.is_open())
		file.close();

	// re-open
	file.open(filename, ios::in | ios::out | ios::binary); 
} 



It does what I want but I am wondering if there actually is a combination of file modes to achieve this in an easier way.


Thanks a lot for your help,
Xoric
Last edited on
What input do you expect to get from a non existent file? If you need to read from a file and it doesn't exist, you probably should flag that as an error or throw an exception.

Now,

1
2
file.open(filename, ios::out | ios::binary);
// This combination works fine but overwrites the file if it already exists. 

This isn't quite so. When you open a file for writing, your put pointer is set to position 0. So, if you write, you overwrite whatever is already there. You can use ios::app to append, that is, to set the put pointer to the current end of file.
Last edited on
Topic archived. No new replies allowed.