Share via


將一個檔案附加至另一個檔案

本主題中的程式碼範例示範如何開啟和關閉檔案、讀取和寫入檔案,以及鎖定和解除鎖定檔案。

在此範例中,應用程式會將一個檔案附加至另一個檔案的結尾。 首先,應用程式會開啟附加檔案的許可權,只允許應用程式寫入該檔案。 不過,在附加程式期間,其他進程可以使用唯讀許可權開啟檔案,以提供所附加檔案的快照集檢視。 然後,在實際附加程式期間鎖定檔案,以確保寫入檔案的資料完整性。

此範例不使用交易。 如果您使用交易作業,則只能有唯讀存取權。 在此情況下,您只會在交易認可作業完成之後看到附加的資料。

此範例也會顯示應用程式使用 CreateFile開啟兩個檔案:

  • One.txt開啟以供讀取。
  • Two.txt開啟以進行寫入和共用閱讀。

然後,應用程式會使用 ReadFileWriteFile ,藉由讀取和寫入 4 KB 區塊,將One.txt的內容附加至Two.txt結尾。 不過,在寫入第二個檔案之前,應用程式會使用 SetFilePointer 將第二個檔案的指標設定為該檔案的結尾,並使用 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);
}