我正在制作一个程序,用 C++ 从 Windows 事件日志文件 (.evt) 中读取和存储数据。我正在使用电话 OpenBackupEventLog(ServerName, FileName)和 ReadEventLog(...) .还使用这个:PEVENTLOGRECORD
无论如何,在不提供所有代码的情况下,这里是基本思想:
1.我使用 OpenBackupEventLog() 获取 .evt 文件的句柄并传入文件名。
2.然后,我使用 ReadEventLog() 用未知数量的 EventLog 消息填充缓冲区。
3.我遍历缓冲区并将每条消息添加到一个 vector 中
4.我不断填充缓冲区(重复第 2 步和第 3 步),直到到达文件末尾。
这是我填充 vector 的代码:
vector<EVENTLOGRECORD> allRecords;
while(_status == ERROR_SUCCESS)
{
if(!ReadEventLog(...))
CheckStatus();
else
FillVectorFromBuffer(allRecords)
}
// Function FillVectorFromBuffer
FillVectorFromBuffer(vector(EVENTLOGRECORD) &allRecords)
{
int bytesExamined = 0;
PBYTE pRecord = (PBYTE)_lpBuffer; // This is one of the params in ReadEventLog()
while(bytesExamined < _pnBytesRead) // Another param from ReadEventLog
{
EVENTLOGRECORD currentRecord = (EVENTLOGRECORD)(pRecord);
allRecords.push_back(currentRecord);
pRecord += currentRecord->Length;
bytesExamined += currentRecord->Length;
}
}
无论如何,无论何时我运行它,它都会获取文件中的所有事件日志,并且 vector 将包含我想要的所有内容。但是只要这一行:
if(!ReadEventLog())
gets called and returns true (aka ReadEventLog() returns false), then every field in my vector gets set to zero.
The vector will still contain the correct number of elements, it's just that all of the fields in the PEVENTLOGRECORD struct are now zero.
Anyone with better debugging experience have any ideas?
Thanks.
Edit: I have updated the code per Michael Burr's suggestion. The above code now eliminates the original problem I was having.
Edit 2: Addressing Michael Burr's other suggestion: Because of the variable portion of the EVENTLOGRECORD, I will make a custom struct that has the EVENTLOGRECORD plus a few other variables that I am interested in:
struct CustomRecord
{
EVENTLOGRECORD recordHeader;
string sourceName;
string computerName;
string message;
};
提取可变部分并非易事,但这里有一个很好的例子可以帮助您入门: Querying for Event Information
最佳答案
我猜你的 vector (我认为应该读作 vector<PEVENTLOGRECORD>
,而不是 vector(PEVENTLOGRECORD)
)包含指向数据的指针而不是数据的拷贝。我认为拥有实际数据的任何人都会在 ReadEventLog()
时发布它。表示没有更多数据。
一个可能的解决方法是您应该将数据本身存储在 vector 中而不是指针中。使 vector 成为 vector<EVENTLOGRECORD>
并将 PEVENTLOGRECORD 指针的取消引用内容存储到 vector (应该创建一个拷贝)而不是指针本身:
allRecords.push_back(*currentRecord);
更新:仔细查看 MSDN,EVENTLOGRECORD
是那些令人讨厌的可变长度结构之一,编译器只知道“ header ”部分。可变长度数据跟在该 header 之后,但严格来说,就编译器而言,它不是结构的一部分。所以一个vector<EVENTLOGRECORD>
不会捕获数据的可变部分。您需要想出一个可以用 PEVENTLOGRECORD
初始化的自定义类并且知道如何正确处理可变数据,或者您需要将结构及其可变数据复制到大小合适、动态分配的字节数组中,并存储指向该分配 block 的指针(但不要释放阻塞直到 vector 完成 - 智能指针可以在这里提供帮助)。
想出可以智能处理事件日志记录数据的类可能需要做一些前期工作,但我想如果您正在使用记录。您可能会在网上找到一个可以用作或用作您自己的起点的类(例如,通过快速搜索从 http://www.naughter.com/serv.html 找到 CEventLogRecord)。
关于c++ - 为什么我的 vector<EVENTLOGRECORD> 莫名其妙地被清除了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4552004/