This example will demonstrate how you can lock a file for writing on Windows. This is useful especially if your application involves of multiple process and each process will access to the same file simultaneously. The LockFile function locks the file for exclusive access by the calling process only.  Once it finish its writing process it then will unlock the file for other process to access it. Let’s include the header files first
1
2
3
4
5
#include "Windows.h"
#include <iostream>
#include <string>

using namespace std;
This is the main function in the demo console app
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
int _tmain(int argc, char* argv[])
{
  HANDLE hFile;
  string strData;
  DWORD  dwBytesRead, dwBytesWritten, dwPos;

  // Open or create a new file
  hFile = CreateFile(TEXT("data.txt")// open Two.txt
        FILE_APPEND_DATA,   // open for writing
        FILE_SHARE_READ,    // allow multiple readers
        NULL,         // no security
        OPEN_ALWAYS,      // open or create
        FILE_ATTRIBUTE_NORMAL,  // normal file
        NULL);          // no attr. template

  if (hFile == INVALID_HANDLE_VALUE)
  {
     printf("Could not open data.txt.");
     return 0;
  }

  // Read data from console
  getline(cin, strData);
 
  // The app. will quit if we type "EOF" in the console
  while(strData != "EOF")
  {
    // Pack a carriage return so that
    // it write to next line in the file
    strData += "\r\n";

    // Get the length of string
    dwBytesRead = strData.length();

    // Get the last index position from file
    // so that we know where to append the new data
    dwPos = SetFilePointer(hFile, 0, NULL, FILE_END);

    // Star locking the file for writing
    LockFile(hFile, dwPos, 0, dwBytesRead, 0);

    // Write data to file
    WriteFile(hFile, strData.c_str(), dwBytesRead, &dwBytesWritten, NULL);
   
    // Unlock the file
    UnlockFile(hFile, dwPos, 0, dwBytesRead, 0);

    // Read data from console again
    getline(cin, strData);
  }

  // Close file
  CloseHandle(hFile);

  return 0;
}
Download sample source code: FileLockTest