Share via


_lock_file

更新 : 2007 年 11 月

他のプロセスがファイルにアクセスできないようにファイルをロックします。

void _lock_file(
   FILE* file
);

パラメータ

  • file
    ファイル ハンドル。

解説

_lock_file 関数は、file が指定するディレクトリをロックします。ファイルをロックすることによって、他のプロセスはファイルにアクセスできなくなります。ファイルのロックを解除するには、_unlock_file を使用します。_lock_file と _unlock_file の呼び出しは、同じスレッド内で対応している必要があります。既にロックされているファイルをロックするか、またはロックされていないファイルをアンロックしようとすると、デッドロックが発生することがあります。

必要条件

ルーチン

必須ヘッダー

_lock_file

<stdio.h>

互換性の詳細については、「C ランタイム ライブラリ」の「互換性」を参照してください。

使用例

// 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 の相当するアイテム

System::IO::FileStream::Lock

参照

参照

ファイル処理

_creat、_wcreat

_open、_wopen

_unlock_file