Is there a function in C ++ that creates a .bin file, or is this code missing something?
I have some code that looks like this:
int main () {
fstream file;
file.open("test.bin", ios::out | ios::binary);
if(!file.is_open())
{
return -1;
}
int n = 3;
file.write(reinterpret_cast<char*>(&n), sizeof(n));
file.close();
return 0;
}
when i run it alone it exits at -1, so obviously it failed to open "test.bin". However, if I save a blank notepad as "test.bin" and run it, it works fine. I'm wondering how I can get my C ++ program to automatically generate an empty "test.bin" file if a file named "test.bin" doesn't exist yet.
Your code snippet is not correct as it is trying to write the file you opened for input. If you want to write a file, just use ios::out
instead ios::in
.
If you want to open the file for reading, but create it if it doesn't exist, you can use:
file.open("test.bin", ios::in | ios::binary);
if(!file.is_open()) {
file.open("test.bin", ios::out | ios::binary);
int n = 3;
file.write(reinterpret_cast<char*>(&n), sizeof(n));
file.close();
file.open("test.bin", ios::in | ios::binary);
if(!file.is_open()) {
return -1;
}
}
This will initialize the file with integer 3 as the default content if it doesn't already exist.
If it exists, it will leave the content alone. In any case, you will open the file in the first byte.
a source to share