한 파일을 다른 파일에 추가

이 항목의 코드 예제에서는 파일을 열고 닫고, 파일을 읽고 쓰고, 파일을 잠그고 잠금 해제하는 방법을 보여줍니다.

이 예제에서 애플리케이션은 한 파일을 다른 파일의 끝에 추가합니다. 먼저 애플리케이션은 애플리케이션만 쓸 수 있는 권한이 추가된 파일을 엽니다. 그러나 추가 프로세스 중에 다른 프로세스는 추가되는 파일의 스냅샷 보기를 제공하는 읽기 전용 권한으로 파일을 열 수 있습니다. 그런 다음, 파일에 기록되는 데이터의 무결성을 보장하기 위해 실제 추가 프로세스 중에 파일이 잠깁니다.

이 예제에서는 트랜잭션을 사용하지 않습니다. 트랜잭션된 작업을 사용하는 경우 읽기 전용 액세스 권한만 가질 수 있습니다. 이 경우 트랜잭션 커밋 작업이 완료된 후에만 추가된 데이터가 표시됩니다.

또한 이 예제에서는 애플리케이션이 CreateFile을 사용하여 두 개의 파일을 여는 것을 보여 줍니다.

  • 읽기용으로 One.txt가 열립니다.
  • 쓰기 및 공유 읽기용으로 Two.txt가 열립니다.

그런 다음, 애플리케이션은 ReadFileWriteFile을 사용하여 4KB 블록을 읽고 작성하여 Two.txt 끝에 One.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);
}