| 1088 | } |
| 1089 | |
| 1090 | HandlePtr tempFile(const std::wstring dir) |
| 1091 | { |
| 1092 | // maximum tries of incrementing the counter |
| 1093 | const int MaxTries = 100; |
| 1094 | |
| 1095 | // UTC time and date will be in the filename |
| 1096 | const auto now = std::time(0); |
| 1097 | const auto tm = std::gmtime(&now); |
| 1098 | |
| 1099 | // "ModOrganizer-YYYYMMDDThhmmss.dmp", with a possible "-i" appended, where |
| 1100 | // i can go until MaxTries |
| 1101 | std::wostringstream oss; |
| 1102 | oss << L"ModOrganizer-" << safeVersion() << std::setw(4) << (1900 + tm->tm_year) |
| 1103 | << std::setw(2) << std::setfill(L'0') << (tm->tm_mon + 1) << std::setw(2) |
| 1104 | << std::setfill(L'0') << tm->tm_mday << "T" << std::setw(2) << std::setfill(L'0') |
| 1105 | << tm->tm_hour << std::setw(2) << std::setfill(L'0') << tm->tm_min << std::setw(2) |
| 1106 | << std::setfill(L'0') << tm->tm_sec; |
| 1107 | |
| 1108 | const std::wstring prefix = oss.str(); |
| 1109 | const std::wstring ext = L".dmp"; |
| 1110 | |
| 1111 | // first path to try, without counter in it |
| 1112 | std::wstring path = dir + L"\\" + prefix + ext; |
| 1113 | |
| 1114 | for (int i = 0; i < MaxTries; ++i) { |
| 1115 | std::wclog << L"trying file '" << path << L"'\n"; |
| 1116 | |
| 1117 | HandlePtr h(CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, |
| 1118 | FILE_ATTRIBUTE_NORMAL, nullptr)); |
| 1119 | |
| 1120 | if (h.get() != INVALID_HANDLE_VALUE) { |
| 1121 | // worked |
| 1122 | return h; |
| 1123 | } |
| 1124 | |
| 1125 | const auto e = GetLastError(); |
| 1126 | |
| 1127 | if (e != ERROR_FILE_EXISTS) { |
| 1128 | // probably no write access |
| 1129 | std::wcerr << L"failed to create dump file, " << formatSystemMessage(e) << L"\n"; |
| 1130 | |
| 1131 | return {}; |
| 1132 | } |
| 1133 | |
| 1134 | // try again with "-i" |
| 1135 | path = dir + L"\\" + prefix + L"-" + std::to_wstring(i + 1) + ext; |
| 1136 | } |
| 1137 | |
| 1138 | std::wcerr << L"can't create dump file, ran out of filenames\n"; |
| 1139 | return {}; |
| 1140 | } |
| 1141 | |
| 1142 | HandlePtr dumpFile(const wchar_t* dir) |
| 1143 | { |
no test coverage detected