Export (0) Print
Expand All
div
eof
Expand Minimize
2 out of 5 rated this helpful - Rate this topic

_lock_file 

Locks a file, preventing other processes from accessing the file.


void _lock_file(
   FILE* file
);

Parameters

file

File handle.

The _lock_file function locks the file specified by file. Locking a file prevents access to the file by other processes. Use _unlock_file to release the lock on the file. Calls to _lock_file and _unlock_file must be matched in a thread. Attempting to lock a file that is already locked or unlock a file that is not locked can result in a deadlock.

Routine Required header Compatibility

_lock_file

<stdio.h>

Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium Edition, Windows NT 4.0, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003

For more compatibility information, see Compatibility in the Introduction.

// crt_lock_file.c
// This program will Lock a file,
// preventing other processes or threads
// from gaining access to the file until 
// it's unlocked.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE    *pFile = NULL;
    char    *fileName = "crt_lock_file.txt";
    char    commandLine[256];

    // Open the file in write mode
    fopen_s(&pFile, fileName ,"w+");
    if (!pFile)
    {
        printf("Error opening file %s!\n", fileName);
        exit(1);
    }

    // Lock the file.
    _lock_file(pFile);
    printf("Locking the file %s.\n", fileName);

    // Add some data to the file
    fprintf(pFile, "The sound of bagpipes in the distant glen...\n");

    printf("\nAttempting to access the file from another process:\n");
    sprintf_s(commandLine, sizeof(commandLine), "type %s", fileName);
    system(commandLine);

    // Unlock the file
    _unlock_file(pFile);

    // Close the file
    fclose(pFile);

    printf("\nAttempting to access the file again:\n");
    system(commandLine);
}

Sample Output

Locking the file crt_lock_file.txt.

Attempting to access the file from another process:
The process cannot access the file because it is being used by another process.

Attempting to access the file again:
The sound of bagpipes in the distant glen...

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.