Partager via


_lock_file

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

void _lock_file(
   FILE* file
);

Parameters

  • file
    File handle.

Remarks

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.

Requirements

Routine

Required header

_lock_file

<stdio.h>

For more compatibility information, see Compatibility in the Introduction.

Example

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

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...

.NET Framework Equivalent

System::IO::FileStream::Lock

See Also

Concepts

File Handling

_creat, _wcreat

_open, _wopen

_unlock_file