MSDN Documentation Contact

Transactional I/O (Windows API)

The Transactional I/O API enables applications to perform file operations within a transaction, guaranteeing atomicity and durability. These functions are part of the TxF (Transaction Files) subsystem and are available on Windows Vista and later.

Syntax

BOOL WINAPI CreateFileTransactedW(
    LPCWSTR               lpFileName,
    DWORD                 dwDesiredAccess,
    DWORD                 dwShareMode,
    LPSECURITY_ATTRIBUTES lpSecurityAttributes,
    DWORD                 dwCreationDisposition,
    DWORD                 dwFlagsAndAttributes,
    HANDLE                hTemplateFile,
    HANDLE                hTransaction,
    PVOID                 pExtendedParameter,
    LPSECURITY_ATTRIBUTES lpSecurityAttributes);

All standard CreateFile parameters apply, with the addition of hTransaction and pExtendedParameter.

Parameters

ParameterDescription
lpFileNameName of the file or device to be created or opened.
dwDesiredAccessAccess rights (e.g., GENERIC_READ, GENERIC_WRITE).
dwShareModeSharing mode flags.
lpSecurityAttributesPointer to a SECURITY_ATTRIBUTES structure.
dwCreationDispositionAction to take on files that exist or do not exist.
dwFlagsAndAttributesFile attributes and flags.
hTemplateFileHandle to a template file with attributes to copy.
hTransactionHandle to an open transaction (from CreateTransaction).
pExtendedParameterReserved; must be NULL.

Remarks

Transactional I/O ensures that a set of file operations either all succeed or all fail as a single unit. This is useful for scenarios such as:

Key points:

Example

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

int main(void)
{
    HANDLE hTx = CreateTransaction(NULL, 0, 0, 0, 0, 0, L"Sample Tx");
    if (hTx == INVALID_HANDLE_VALUE) {
        wprintf(L"CreateTransaction failed: %lu\\n", GetLastError());
        return 1;
    }

    HANDLE hFile = CreateFileTransactedW(
        L"C:\\Temp\\test.txt",
        GENERIC_WRITE,
        0,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL,
        hTx,
        NULL,
        NULL);

    if (hFile == INVALID_HANDLE_VALUE) {
        wprintf(L"CreateFileTransactedW failed: %lu\\n", GetLastError());
        RollbackTransaction(hTx);
        CloseHandle(hTx);
        return 1;
    }

    const char *msg = "Hello, Transactional World!";
    DWORD written;
    WriteFile(hFile, msg, (DWORD)strlen(msg), &written, NULL);
    CloseHandle(hFile);

    if (!CommitTransaction(hTx)) {
        wprintf(L"CommitTransaction failed: %lu\\n", GetLastError());
        RollbackTransaction(hTx);
    }

    CloseHandle(hTx);
    wprintf(L"Transaction completed successfully.\\n");
    return 0;
}

Compile with cl /EHsc /link /DUNICODE transaction.c.