坑! 有一個大坑,浪費我整整8個小時。最開始的思路是使用 Windows API 來記錄檔,但是發現過程非常繁瑣,而且到最後還有很多資料讀不全,看了一天的 MSDN,最後放棄了。
于是采用另一個思路,20分鐘解決。
使用 C++ 操作指令行,并接收指令行傳回資訊,通過 Dos 指令擷取 Windows 系統日志。
Wevtutil 指令介紹
文檔上介紹的很全,我就不一一列舉了,這裡隻說下我用到的一行指令:
意思就是列印最近三條系統日志
下面是接收指令行傳回資訊的代碼:
// Test_Console.cpp : 定義控制台應用程式的入口點。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int execmd(char* cmd, char* result) {
char buffer[128]; // 緩沖區
FILE* pipe = _popen(cmd, "r"); // 管道
// 管道打開失敗
if (!pipe){return 0;}
// 檢測管道中的結束符,0表示沒有結束
while(!feof(pipe)){
// 從管道中讀取資料
if (fgets(buffer, 128, pipe)) {
// 拼接 char
strcat(result, buffer);
}
}
//關閉管道
_pclose(pipe);
return 1;
}
int main()
{
char result[0x7ffff] = ""; // 存放結果
// 擷取指令行傳回值(保險起見這裡擷取 300 條日志資訊)
if (execmd("wevtutil qe System /c:300 /rd:true /f:text", result) == 1) {
cout << result << endl;
}
// 查找關鍵資料
string s = result;
while ((s.find("igfx")) != -1) {
cout << "找到了 igfx " << endl;
break;
}
system("pause");
return 0;
}
效果圖: