Thread: fstream lets you open a file for output twice (?!)

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    12

    fstream lets you open a file for output twice (?!)

    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:
    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main(int argc, char* argv[])
    {
    	fstream fs("test.txt", ios::in | ios::out | ios::binary);
    	if(!fs.is_open())
    		cerr << "Cannot open test file." << endl;
    	fstream fs2("test.txt", ios::in | ios::out | ios::binary);
    	if(!fs2.is_open())
    		cerr << "Cannot open (that same) test file." << endl;
    	fs.write("a", 1);
    	if(!fs.good())
    		cerr << "Cannot write to test file." << endl;
    	fs2.write("b", 1);
    	if(!fs2.good())
    		cerr << "Cannot write to (that same) test file." << endl;
    }
    When I run this program, I get no complaints, though only one of "a" or "b" is ever written to the file. WTF?

    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?

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Multithreading and synchronization.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  2. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  3. Simple File encryption
    By caroundw5h in forum C Programming
    Replies: 2
    Last Post: 10-13-2004, 10:51 PM
  4. file processing updating record error
    By uuser in forum C Programming
    Replies: 2
    Last Post: 04-27-2003, 12:13 AM