• C

File locking on Windows

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.
sa9824Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
rajeev_devinConnect With a Mentor Commented:
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
 
rajeev_devinCommented:
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
 
rajeev_devinCommented:
>> 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
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
rajeev_devinCommented:
0
 
sa9824Author Commented:
I want to lock the entire file, not just a part of it....
0
 
rajeev_devinCommented:
Then use the CreateFile(...) as I showed above.
0
 
rajeev_devinCommented:
0
 
PaulCaswellCommented:
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
 
NopiusCommented:
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
 
sa9824Author Commented:
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
 
rajeev_devinCommented:
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
 
rajeev_devinCommented:
After CreateFile you don't need LockFile to lock it.
0
 
sa9824Author Commented:
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
 
sa9824Author Commented:
It worked fine without the call to LockFile!

How can I release the lock on the file?
0
 
rajeev_devinCommented:
>> Will this work between different instances of my application (there will be multiple instances running at the same >> time)?
Yes, it will work
0
 
rajeev_devinCommented:
>> How can I release the lock on the file?
To release the lock simply use on that handle
CloseHandle(hDevice)
0
 
sa9824Author Commented:
Thanx rajeev_devin! You will get the points!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.