#include #include #include #include #include #include #include #include "crashdump.h" long __stdcall DumpCall(EXCEPTION_POINTERS* excp) { // 1. 生成带时间戳的文件名 auto now = std::chrono::system_clock::now(); auto now_time_t = std::chrono::system_clock::to_time_t(now); auto now_ms = std::chrono::duration_cast(now.time_since_epoch()) % 1000; std::ostringstream oss; oss << std::put_time(std::localtime(&now_time_t), "%Y%m%d_%H%M%S") << "_" << std::setfill('0') << std::setw(3) << now_ms.count() << "_crash.log"; std::string filename = oss.str(); // 2. 获取崩溃信息 CrashDump dump(excp); std::string crashInfo = dump.GetExceptionInfo(); // 3. 写入文件 (C++11 风格) try { std::ofstream outfile(filename, std::ios::out | std::ios::trunc); if (outfile) { outfile << "=== Crash Dump ===\n\n"; outfile << "Timestamp: " << std::put_time(std::localtime(&now_time_t), "%Y-%m-%d %H:%M:%S") << "." << std::setfill('0') << std::setw(3) << now_ms.count() << "\n"; outfile << crashInfo; outfile << "\n=== End of Dump ==="; // 确保数据写入磁盘 outfile.flush(); if (outfile.good()) { return EXCEPTION_EXECUTE_HANDLER; } } } catch (...) { // 文件写入失败的备用方案 OutputDebugStringA(("Failed to write crash dump to " + filename).c_str()); } return EXCEPTION_EXECUTE_HANDLER; } void tasks() { int c = 5; while (--c > 0) { std::this_thread::sleep_for(std::chrono::seconds(1)); } int* p = nullptr; *p = 11; std::cout << "over..." << std::endl; } int main() { SetUnhandledExceptionFilter(DumpCall); std::cout << "Hello World!" << std::endl; std::thread thread(tasks); thread.join(); std::cout << "End." << std::endl; return 0; }