- #1
yungman
- 5,755
- 293
I am writing a program that I need to create a file the FIRST time the program is run, but not create one every time I run the program and NOT touch the data in the file if the file already exist. I know if the file does not exist, ios::in will not create the file, just give an error message that the file does not exist:
Only open in "out" mode will create a new file if it does not exist:
This is what I have so far to first test whether the file exist by first open in ios::in mode. If it fails, then I know the file does not exist, then I create the file by open in iosut mode. Will this destroy data if the file do exist but somehow failed to open:
Or is there a better way to test if the file exist, don't touch it. If it is the very first time running the program and the file is not created yet, then create the file. So after inputting the data, the next time, the file already exist and the program can just add and delete data and modify the file.
Thanks
C++:
fstream file;
file.open("demofile.dat", ios::in | ios::binary);//will give error if file does not exist.
C++:
fstream file;
file.open("demofile.dat", ios::out|ios::binary);//Will create file if it does not exist
This is what I have so far to first test whether the file exist by first open in ios::in mode. If it fails, then I know the file does not exist, then I create the file by open in iosut mode. Will this destroy data if the file do exist but somehow failed to open:
C++:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{ fstream file;
file.open("demofile.dat", ios::out|ios::in | ios::binary);//test for existence.
if (file.fail())
{
cout << " file does not exist.\n\n";
file.open("demofile.dat", ios::out|ios::binary);//create file if it does not exist.
file.close();
}
return 0;
}
Or is there a better way to test if the file exist, don't touch it. If it is the very first time running the program and the file is not created yet, then create the file. So after inputting the data, the next time, the file already exist and the program can just add and delete data and modify the file.
Thanks