Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Expand Minimize
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.


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

void _lock_file(
   FILE* 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



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);

    // Lock the file.
    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);

    // Unlock the file

    // Close the file

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

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

© 2015 Microsoft