- Let’s start our example by creating a MFC console application.
- Create a function to handle all log file process now.
- Let’s call the AppendLog function now.
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 | void AppendLog(char *pfilename, char *pstr) { CFile file; CFileException ex; /* convert the filename to LPCTSTR */ CString strFilename(pfilename); /* let's open the file now */ if( !file.Open(strFilename, CFile::modeWrite | CFile::modeCreate | CFile:: modeNoTruncate, &ex ) ) return; /* limit the file size to 5k */ const DWORD dwFileSize = 5 * 1024; /* check if the file size is greater * than limit file size that we set */ if (file.GetLength() > dwFileSize) { /* remove all content in the file * by reset it size to zero */ file.SetLength(0); } /* we now go to the end of the file */ file.SeekToEnd(); /* formating the log file data here */ char tem[1024]; CTime time = CTime::GetCurrentTime(); sprintf(tem, "%02d:%02d:%04d %02d:%02d:%02d %s\r\n", time.GetDay(), time.GetMonth(), time.GetYear(), time.GetHour(), time.GetMinute(), time.GetSecond(), pstr); /* write the data to log file */ file.Write(tem, strlen(tem)); /* make sure that we close the file when we finish the writing process */ file.Close(); } |
1 2 3 4 5 6 7 8 9 10 11 | char szInput[100]; cin >> szInput; while(strcmp(szInput, "end") != 0) { AppendLog(1, "d:\\test.log", szInput); memset(szInput, NULL, sizeof(szInput)); cin >> szInput; } |
Writing log file using CFile class