MCPcopy Create free account
hub / github.com/dobin/RedEdr / tailFileW

Function tailFileW

RedEdr/logreader.cpp:22–81  ·  view source on GitHub ↗

Stupid but working tail-f implementation Just checks every second for new data

Source from the content-addressed store, hash-verified

20// Stupid but working tail-f implementation
21// Just checks every second for new data
22void tailFileW(const wchar_t* filePath) {
23 LOG_A(LOG_INFO, "LOG: Tail -f %ls", filePath);
24
25 HANDLE hFile = CreateFileW(filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
26 if (hFile == INVALID_HANDLE_VALUE) {
27 LOG_A(LOG_ERROR, "LOG: Failed to open file. Error: %lu", GetLastError());
28 return;
29 }
30
31 // Buffer for reading the file
32 const DWORD bufferSize = 1024;
33 wchar_t buffer[bufferSize / sizeof(wchar_t)];
34 DWORD bytesRead;
35 LARGE_INTEGER fileSize;
36 LARGE_INTEGER offset;
37
38 // Get the file size
39 if (!GetFileSizeEx(hFile, &fileSize)) {
40 LOG_A(LOG_ERROR, "LOG: Failed to get file size. Error: %lu", GetLastError());
41 CloseHandle(hFile);
42 return;
43 }
44
45 // Start reading from the end of the file
46 offset.QuadPart = fileSize.QuadPart;
47 while (!LogReaderThreadStopFlag) {
48 // Check if there's new data
49 LARGE_INTEGER newSize;
50 if (!GetFileSizeEx(hFile, &newSize)) {
51 LOG_A(LOG_ERROR, "LOG: Failed to get file size. Error: %lu", GetLastError());
52 break;
53 }
54
55 if (newSize.QuadPart > offset.QuadPart) {
56 // Move the file pointer to the last read position
57 SetFilePointerEx(hFile, offset, NULL, FILE_BEGIN);
58
59 // Read the new data
60 if (!ReadFile(hFile, buffer, bufferSize - sizeof(wchar_t), &bytesRead, NULL)) {
61 LOG_A(LOG_INFO, "LOG: Failed to read file. Error: %lu", GetLastError());
62 break;
63 }
64
65 // Null-terminate the buffer
66 buffer[bytesRead / sizeof(wchar_t)] = L'\0';
67
68 // Print the new data (including newline?)
69 g_EventAggregator.do_output(std::wstring(buffer));
70 //wprintf(L"%s", buffer);
71
72 // Update the offset
73 offset.QuadPart += bytesRead;
74 }
75
76 // Sleep for a while before checking again
77 Sleep(1000);
78 }
79

Callers 1

Calls 2

do_outputMethod · 0.80
LOG_AFunction · 0.70

Tested by

no test coverage detected