I am writing a program that uses a file on the disk to store configuration data, and this program both reads and writes to this file during execution. I want users to be able to run multiple instances of my program, but it is highly undesirable for both instances to believe they have write access to the configuration file. In anticipation of this problem, I had planned for my application to attempt to open the file for writing, and, if it finds that the open operation failed, it goes into a contingency state where it forgoes use of the configuration file.
Unfortunately, this scheme doesn't work, because fstream is more than happy to open the same file, for writing, multiple times!
Here is a test program I wrote:
When I run this program, I get no complaints, though only one of "a" or "b" is ever written to the file. WTF?
using namespace std;
int main(int argc, char* argv)
fstream fs("test.txt", ios::in | ios::out | ios::binary);
cerr << "Cannot open test file." << endl;
fstream fs2("test.txt", ios::in | ios::out | ios::binary);
cerr << "Cannot open (that same) test file." << endl;
cerr << "Cannot write to test file." << endl;
cerr << "Cannot write to (that same) test file." << endl;
What is going on here? If there's no way for my program to secure exclusive write access to a file, could anyone suggest an alternative solution to my problem?