in reply to Unable to write to a file opened in read only mode

Okay, I finally got a chance to test this under WinNT... and I got the same results I got under Win2K. With a file open for read-only access in Perl, notepad and gvim don't care in the least and will still open, edit, and save the file.

It is nice that several people have chimed in with how "this is just how Windows works", but I don't believe any of them. (: I've certainly seen cases where shared access was denied when I had hoped that it wouldn't be, but a quick test shows that this isn't such a case.

It is true that, unlike Unix, Windows gives you the option of requesting that no other program do certain things to the file while you are using it and of having that request enforced by the operating system (not requiring all tasks dealing with the file to cooperate nor requiring special tagging of the file to get this).

It is also true that many Windows programs, especially those not written in C, chose to request no sharing when they open files (or at least less sharing than you sometimes would like).

The details are that you can request three types of sharing: read, write, and delete. ("Delete" sharing doesn't apply prior to WinNT.) You specify zero or more of these types of sharing be allowed whenever you open a file in Windows. When using C code, the default is to request only "read" and "write" sharing.

If you don't request "read" sharing, then you won't be able to open the file if anyone else has the file open for reading and once you have the file open, nobody else will be allowed to open it for reading. "write" sharing is exactly the same except you replace "reading" with "writing".

See Win32API::File for some more information on this and how to use Perl to play with opening files specifying different types of sharing.

        - tye (but my friends call me "Tye")
  • Comment on (tye)Re: Unable to write to a file opened in read only mode

Replies are listed 'Best First'.
Re: (tye)Re: Unable to write to a file opened in read only mode
by cgrinder (Initiate) on Nov 05, 2001 at 19:58 UTC
    Thanks for taking the effort to try it. My version of notepad and gvim must be using the "no sharing" option. I have tried it on nt workstation and server with the same locking problems. I'm not sure how it is working for you.

    If I understand you correctly, your saying it depends on how the application is opening the file for writes. This will determine if it can write to the file or not. So...If the app writing to a log file doesn't allow anyone to be reading the file, I'm out of luck right?

    It sounds like the solution might be for me to not open the file at all. I guess I can create a temp file and save my last position read each time I create and read the temp file. Based on the position, I can read only the new lines that have been added.

    I think this will work, but it is not as clean as the original solution.

    Thanks.