1 つのファイルを別のファイルに追加する

このトピックのコード例では、ファイルの開きと閉じ、ファイルの読み取りと書き込み、ファイルのロックとロック解除を行う方法を示します。

この例では、アプリケーションは 1 つのファイルを別のファイルの末尾に追加します。 最初に、アプリケーションがファイルに書き込みを許可するアクセス許可を追加するファイルを開きます。 ただし、追加プロセス中に、他のプロセスは読み取り専用アクセス許可を使用してファイルを開くことができます。これにより、追加されるファイルのスナップショットビューが提供されます。 その後、ファイルに書き込まれるデータの整合性を確保するために、実際の追加プロセス中にファイルがロックされます。

この例では、トランザクションは使用しません。 トランザクション操作を使用していた場合は、読み取り専用アクセス権のみを持つことができます。 この場合、トランザクション コミット操作が完了した後にのみ、追加されたデータが表示されます。

この例では、 アプリケーションが CreateFile を使用して 2 つのファイルを開くことも示しています。

  • One.txtが読み取り用に開かれます。
  • Two.txtは、書き込みと共有の読み取りのために開かれます。

その後、アプリケーションは ReadFileWriteFile を使用して、4 KB ブロックの読み取りと書き込みを行ってTwo.txtの末尾にOne.txtの内容を追加します。 ただし、2 番目のファイルに書き込む前に、アプリケーションは SetFilePointer を使用して 2 番目のファイルのポインターをそのファイルの末尾に設定し、 LockFile を 使用して書き込まれる領域をロックします。 これにより、書き込み操作の進行中に、重複するハンドルを持つ別のスレッドまたはプロセスが領域にアクセスできなくなります。 各書き込み操作が完了すると、ロック領域のロックを解除するために UnlockFile が使用されます。

#include <windows.h>
#include <stdio.h>

void main()
{
  HANDLE hFile;
  HANDLE hAppend;
  DWORD  dwBytesRead, dwBytesWritten, dwPos;
  BYTE   buff[4096];

  // Open the existing file.

  hFile = CreateFile(TEXT("one.txt"), // open One.txt
            GENERIC_READ,             // open for reading
            0,                        // do not share
            NULL,                     // no security
            OPEN_EXISTING,            // existing file only
            FILE_ATTRIBUTE_NORMAL,    // normal file
            NULL);                    // no attr. template

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

  // Open the existing file, or if the file does not exist,
  // create a new file.

  hAppend = CreateFile(TEXT("two.txt"), // open Two.txt
              FILE_APPEND_DATA | FILE_GENERIC_READ,    // open for appending and locking
              FILE_SHARE_READ,                         // allow multiple readers
              NULL,                                    // no security
              OPEN_ALWAYS,                             // open or create
              FILE_ATTRIBUTE_NORMAL,                   // normal file
              NULL);                                   // no attr. template

  if (hAppend == INVALID_HANDLE_VALUE)
  {
     printf("Could not open two.txt."); 
     return;
  }

  // Append the first file to the end of the second file.
  // Lock the second file to prevent another process from
  // accessing it while writing to it. Unlock the
  // file when writing is complete.

  while (ReadFile(hFile, buff, sizeof(buff), &dwBytesRead, NULL)
      && dwBytesRead > 0)
    {
    dwPos = SetFilePointer(hAppend, 0, NULL, FILE_END);
    if (!LockFile(hAppend, dwPos, 0, dwBytesRead, 0))
    {
       printf("Could not lock two.txt");
    }
    WriteFile(hAppend, buff, dwBytesRead, &dwBytesWritten, NULL);
    UnlockFile(hAppend, dwPos, 0, dwBytesRead, 0);
    }

  // Close both files.

  CloseHandle(hFile);
  CloseHandle(hAppend);
}