Click here to Skip to main content
15,890,185 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to save the some error and warning messages into the log file and i want create th log file depends on date if data is same i should not create new file and need to open existing file and save the data.
not able to save the all the data into the file and its saving only first 4 characters.
could you please correct me

What I have tried:

time_t timeVal = 0;

    time(&timeVal);
    char szTimeBuff[128];
    struct tm tmVal;
    localtime_s(&tmVal, &timeVal);
    size_t zCount = strftime(szTimeBuff, _countof(szTimeBuff), "%Y_%m_%d_", &tmVal);
cstring data L"eror data please enter the correct user name and password"
	
    CString FileName = L"log_error_";
    FileName += szTimeBuff;
    FileName += "_Log";
    CFile	myFile;

    if (myFile.Open((FileName ), CFile::modeCreate |
        CFile::modeReadWrite))
    {
        myFile.Write(data, sizeof(data));// its not showing all the data in the file log its showing only first 4 character i.e erro
        myFile.Flush();
        myFile.Seek(0, CFile::begin);
    }
Posted
Updated 15-Jul-18 23:38pm

1 solution

To append data to an existing file and create the file if it does not exists already, use the CFile::modeNoTruncate flag instead of CFile::modeCreate. The latter will only create files if they did not exist and throw an exception otherwise (see the CFile Class[^]).

The sizeof operator - cppreference.com[^] is processed during compilation time to get the size of an object. It will not return the length of dynamic runtime data like strings.

You have to pass the length of the data in bytes when writing:
myFile.Write(data.GetString(), data.GetLength() * sizeof(TCHAR));
GetLength() returns the number of characters in the string. Because the Write() function is byte based, the number of characters has to be multiplied with the number of bytes per character (2 with Unicode applications).

Note also that you are creating a Unicode text file if your application is Unicode (what the L prefix of the string literal assumes).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900