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
| Parameter | Description |
|---|---|
lpFileName | Name of the file or device to be created or opened. |
dwDesiredAccess | Access rights (e.g., GENERIC_READ, GENERIC_WRITE). |
dwShareMode | Sharing mode flags. |
lpSecurityAttributes | Pointer to a SECURITY_ATTRIBUTES structure. |
dwCreationDisposition | Action to take on files that exist or do not exist. |
dwFlagsAndAttributes | File attributes and flags. |
hTemplateFile | Handle to a template file with attributes to copy. |
hTransaction | Handle to an open transaction (from CreateTransaction). |
pExtendedParameter | Reserved; 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:
- Database file updates
- Critical configuration changes
- Complex multi‑file operations where consistency is required
Key points:
- All handles involved must belong to the same transaction.
- Transactions can be committed with
CommitTransactionor rolled back withRollbackTransaction. - TxF is deprecated in Windows 8 and later; consider using
FSCTL_TXFS_CREATE_BACKUPor alternative mechanisms for new development.
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.