chenluhua1980
9 天以前 517c0e8eba29ff41afbbc0abb0f913914b37e4e1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#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<double, 4>& 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;
}