Solved

File locking on Windows

Posted on 2006-06-28
17
486 Views
Last Modified: 2012-06-21
Hi!

How do I lock a file for writing on a windows machine? On Unix based system I can use the lockf() function but I haven't been able to find something similar to this on windows. I Need functions for locking,unlocking and checking if a file is locked or not. I will use this to prevent simultaneous writing attempts to a logfile.
0
Comment
Question by:sa9824
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
17 Comments
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17000075
HANDLE hHandle = CreateFile(
"test.txt",
GENERIC_WRITE,
0,                                         // don't share, that means it is locked by you.
NULL,                                    // no security
OPEN_EXISTING,                    // existing file only
FILE_ATTRIBUTE_NORMAL,     // normal file
NULL);                                  // no attr. template
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17000082
>> lockf
I saw the documentation of lockf, it says it loacks a section of the file.
If your purpose is to lock a section of a file then better use this function

BOOL LockFile(
  HANDLE hFile,                   // handle to file
  DWORD dwFileOffsetLow,          // low-order word of offset
  DWORD dwFileOffsetHigh,         // high-order word of offset
  DWORD nNumberOfBytesToLockLow,  // low-order word of length
  DWORD nNumberOfBytesToLockHigh  // high-order word of length
);
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17000087
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:sa9824
ID: 17000089
I want to lock the entire file, not just a part of it....
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17000332
Then use the CreateFile(...) as I showed above.
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17000366
0
 
LVL 16

Expert Comment

by:PaulCaswell
ID: 17004961
Hi sa9824,

If you are using a Microsoft C compiler you may find:

            FILE * f = _fsopen("File","a+",0x20/*_SH_DENYWR*/);

To check for access, either use the same function (you will get a NULL pointer returned) or use 'access'.

Paul
0
 
LVL 27

Expert Comment

by:Nopius
ID: 17007010
sa9824, use BOOL LockFile

with dwFileOffsetLow=0, dwFileOffsetHigh=0, nNumberOfBytesToLockLow=1, nNumberOfBytesToLockHigh=1
across all programs, that need to aguire/test lock that's enough
0
 

Author Comment

by:sa9824
ID: 17008001
HI I cant get this to work... Am I missing something?

int getFileLock(char *path){
      HANDLE hDevice;
      
      if(statForRFile(path)==0)
            return -1;
      else {
               hDevice = CreateFile(path,

                                    GENERIC_READ | GENERIC_WRITE,

                                    FILE_SHARE_READ | FILE_SHARE_WRITE,

                                    0,

                                    OPEN_EXISTING,

                                    FILE_FLAG_OVERLAPPED,

                                    0);

            if(hDevice == INVALID_HANDLE_VALUE){
                  CloseHandle(hDevice);
                  return 1;
            }else{
                  CloseHandle(hDevice);
                  return 0;
            }
      }

}


ANd locking function:

void lock(){
      HANDLE hDevice;
       
       hDevice = CreateFile(      _ALOGFILE,
                                           GENERIC_READ | GENERIC_WRITE,
                                           FILE_SHARE_READ | FILE_SHARE_WRITE,
                                           0,
                                           OPEN_EXISTING,
                                           FILE_FLAG_OVERLAPPED,
                                           0);



      if(hDevice == INVALID_HANDLE_VALUE){
            printf("INVALID HANDLE...");
      }
      
      LockFile(hDevice,0,0,1,1);

}
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17009652
As I said before also, set the third parameter to 0.
In that case it is locked and no other application will be able to access

CreateFile(path,
            GENERIC_READ | GENERIC_WRITE,
            0,                                             // This is not required FILE_SHARE_READ | FILE_SHARE_WRITE
            0,
            OPEN_EXISTING,
            FILE_FLAG_OVERLAPPED,
            0);
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17009701
After CreateFile you don't need LockFile to lock it.
0
 

Author Comment

by:sa9824
ID: 17009737
Ok, I will try this!
 Will this work between different instances of my application (there will be multiple instances running at the same time)?
0
 
LVL 12

Accepted Solution

by:
rajeev_devin earned 125 total points
ID: 17009745
Another thing in your implementation after using CreateFile(...) you are simply closing it both the cases.

>> if(hDevice == INVALID_HANDLE_VALUE){
>>               CloseHandle(hDevice); // It is closed if it is invalid
>>               return 1;
>>          }else{
>>               CloseHandle(hDevice); // It is closed even if it is valid
>>               return 0;
>>          }

To keep the lock don't close it until you are over. A better implementation would have been something like this


HANDLE getFileLock(char *path)
{
      if(0)
            return NULL;
      else {
            hDevice = CreateFile(path,
                  GENERIC_READ | GENERIC_WRITE,
                  0,
                  0,
                  OPEN_EXISTING,
                  FILE_FLAG_OVERLAPPED,
                  0);
            
            if(hDevice == INVALID_HANDLE_VALUE){
                  return NULL;
            }
      }

      return hDevice;
}

void fileUnlock(HANDLE hDev)
{
      CloseHandle(hDev);
}


HANDLE hDev = getFileLock(_ALOGFILE); // Lock the file

// Do your stuff

fileUnlock(hDev); // Unlock it when you are over

0
 

Author Comment

by:sa9824
ID: 17009762
It worked fine without the call to LockFile!

How can I release the lock on the file?
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17009768
>> Will this work between different instances of my application (there will be multiple instances running at the same >> time)?
Yes, it will work
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17009787
>> How can I release the lock on the file?
To release the lock simply use on that handle
CloseHandle(hDevice)
0
 

Author Comment

by:sa9824
ID: 17009859
Thanx rajeev_devin! You will get the points!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

617 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question