New issue
Advanced search Search tips

Issue 1169 attachment: ReadDirectoryChanges.cpp (2.4 KB)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <Windows.h>
#include <cstdio>

VOID PrintHex(PBYTE Data, ULONG dwBytes) {
for (ULONG i = 0; i < dwBytes; i += 16) {
printf("%.8x: ", i);

for (ULONG j = 0; j < 16; j++) {
if (i + j < dwBytes) {
printf("%.2x ", Data[i + j]);
}
else {
printf("?? ");
}
}

for (ULONG j = 0; j < 16; j++) {
if (i + j < dwBytes && Data[i + j] >= 0x20 && Data[i + j] <= 0x7e) {
printf("%c", Data[i + j]);
}
else {
printf(".");
}
}

printf("\n");
}
}

DWORD ThreadRoutine(LPVOID lpParameter) {
// Wait for the main thread to call ReadDirectoryChanges().
Sleep(500);

// Perform a filesystem operation which results in two records (FILE_ACTION_RENAMED_OLD_NAME and FILE_ACTION_RENAMED_NEW_NAME)
// being returned at once.
MoveFile(L"a\\b", L"a\\c");

return 0;
}

int main() {
// Create a local "a" directory.
if (!CreateDirectory(L"a", NULL)) {
printf("CreateDirectory failed, %d\n", GetLastError());
return 1;
}

// Open the newly created directory.
HANDLE hDirectory = CreateFile(L"a", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (hDirectory == INVALID_HANDLE_VALUE) {
printf("CreateFile(a) failed, %d\n", GetLastError());
RemoveDirectory(L"a");
return 1;
}

// Create a new file in the "a" directory.
HANDLE hNewFile = CreateFile(L"a\\b", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
if (hNewFile != INVALID_HANDLE_VALUE) {
CloseHandle(hNewFile);
}

// Create a new thread which will modify the directory (rename a file within).
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadRoutine, NULL, 0, NULL);

// Wait for changes in the directory and read them into a 1024-byte buffer.
BYTE buffer[1024] = { /* zero padding */ };
DWORD BytesRead = 0;
if (!ReadDirectoryChangesW(hDirectory, buffer, sizeof(buffer), FALSE, FILE_NOTIFY_CHANGE_FILE_NAME, &BytesRead, NULL, NULL)) {
printf("ReadDirectoryChanges failed, %d\n", GetLastError());
DeleteFile(L"a\\c");
RemoveDirectory(L"a");
return 1;
}

// Dump the output on screen.
PrintHex(buffer, BytesRead);

// Free resources.
DeleteFile(L"a\\c");
RemoveDirectory(L"a");

return 0;
}