How to open a file that does not exist? For writing...

Hi,

I need to open a binary files like this:

1
2
fstream f;
f.open(p, ios::binary | ios::in | ios::out  );


but it fails because the file does not exist! I need to open in a way that if not exists it will create it, otherwise it will open the existing file.

Regards,
Juan
Last edited on
I think with ios::out alone, or with ios::in|ios::out|ios::app the non-existing file should be created:
https://en.cppreference.com/w/cpp/io/basic_filebuf/open
Last edited on
You could also use std::ofstream f("blah", ios::binary);
If you want to open a file for i/o even if it does not exist, try to open first for inp/out and if that fails then open for output (which will create the file) and then try again to open for inp/out. If that fails a second time then there is a problem. Something like (in this example ofn is file name and rout is error code):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	const auto outopt { std::ios::binary | std::ios::in | std::ios::out};

	// Try to open output file assuming already exists
	if (ofs.open(ofn, outopt); !ofs.is_open())
		// If output open fail, try to open for output without specifying in as may not already exist
		if (ofs.open(ofn, std::ios::binary | std::ios::out); ofs.is_open()) {
			// If new file created OK, then close and re-open for input/output
			ofs.close();
			ofs.open(ofn, outopt);		// Try to open output file for input/output again
		}

	// Has the output file opened ok?
	if (!ofs.is_open())
		return (std::cout << "Cannot open output file " << ofn << '\n'), rout;

Last edited on
Topic archived. No new replies allowed.