Log file can be used to trace your application’s activities effectively. For example, you can create a lo file to trace the active process during the execution of your application, preparing un-installation item list, record inbound data or outbound data, etc. This article will demostrate how to write a log file by using CFile class.
  1. Let’s start our example by creating a MFC console application.
  2. Create a function to handle all log file process now.
  3. 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();
    }
  4. Let’s call the AppendLog function now.
  5. 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;

    }