#include "pch.h" #include "ProductResultStorage.h" CProductResultStorage::CProductResultStorage() { TCHAR szPath[MAX_PATH] = { 0 }; GetModuleFileName(NULL, szPath, MAX_PATH); CString strExePath(szPath); int pos = strExePath.ReverseFind(_T('\\')); if (pos != -1) { m_strBaseResultDir = strExePath.Left(pos) + _T("\\Data"); } else { m_strBaseResultDir = _T(".\\Data"); } } void CProductResultStorage::SaveAnalyzeResult(const CString& strProductID, const std::array& result) { CString strFilePath = MakeResultCsvPath(_T("MeasurementResults")); CString strHeader = _T("Timestamp,ProductID,OUT1,OUT2,OUT3,OUT4\r\n"); // 时间戳 CTime now = CTime::GetCurrentTime(); CString strTimestamp; strTimestamp.Format(_T("%02d:%02d:%02d"), now.GetHour(), now.GetMinute(), now.GetSecond()); // 结果行 CString strBody; strBody.Format(_T("%s,%s,%.3f,%.3f,%.3f,%.3f\r\n"), strTimestamp, strProductID, result[0], result[1], result[2], result[3]); AppendCsvWithHeader(strFilePath, strHeader, strBody); } CString CProductResultStorage::MakeResultCsvPath(const CString& strFileName) { SYSTEMTIME st; GetLocalTime(&st); CString strDate; strDate.Format(_T("%04d%02d%02d"), st.wYear, st.wMonth, st.wDay); if (GetFileAttributes(m_strBaseResultDir) == INVALID_FILE_ATTRIBUTES) { CreateDirectory(m_strBaseResultDir, NULL); } CString strFilePath; strFilePath.Format(_T("%s\\%s_%s.csv"), m_strBaseResultDir, strFileName, strDate); return strFilePath; } BOOL CProductResultStorage::AppendCsvWithHeader(const CString& strFilePath, const CString& strHeader, const CString& strBody) { if (strBody.IsEmpty()) { return FALSE; } CFile f; CFileException ex; if (!f.Open(strFilePath, CFile::modeCreate | CFile::modeWrite | CFile::modeNoTruncate | CFile::shareDenyWrite | CFile::shareDenyRead, &ex)) { return FALSE; } if (f.SeekToEnd() == 0L) { f.Write(strHeader, strHeader.GetLength() * sizeof(TCHAR)); } f.Write(strBody, strBody.GetLength() * sizeof(TCHAR)); f.Close(); return TRUE; }