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

This is a discussion on fstream lets you open a file for output twice (?!) within the C++ Programming forums, part of the General Programming Boards category; I am writing a program that uses a file on the disk to store configuration data, and this program both ...

  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,662
    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, 02:19 PM
  2. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 09:39 AM
  3. Simple File encryption
    By caroundw5h in forum C Programming
    Replies: 2
    Last Post: 10-13-2004, 11:51 PM
  4. file processing updating record error
    By uuser in forum C Programming
    Replies: 2
    Last Post: 04-27-2003, 01:13 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21