Search code examples
c++winapiwritefile

Why does WriteFile not run more than once?


Here's my code in which I've got on an infinite loop (to my knowledge)

while(true) {
    DWORD TitleID = XamGetCurrentTitleId();
    std::ostringstream titleMessageSS;
    titleMessageSS << "Here's the current title we're on : " << TitleID << "\n\n";
    std::string titleMessage = titleMessageSS.str(); // get the string from the stream
    DWORD dwBytesToWrite = (DWORD)titleMessage.size();
    DWORD dwBytesWritten = 0;
    BOOL bErrorFlag = FALSE;
    HANDLE logFile = CreateFile( "Hdd:\\LOGFile.txt", GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
    bErrorFlag = WriteFile(logFile, titleMessage.c_str(), dwBytesToWrite, &dwBytesWritten, NULL);
    CloseHandle(logFile);
    Sleep(30000);
}
return NULL;

Does anyone see a reason as to why this only writes just once? I've waited over 5 minutes to see if it does anything in the end to no avail.


Solution

  • The Flag CREATE_NEW in CreateFile prevents the update of the file because CreateFile fail with ERROR_FILE_EXISTS. Use OPEN_ALWAYS instead. Also it will always truncate. Replace GENERIC_WRITE with FILE_APPEND_DATA if you want to add a new line at the end of your logfile.

    The whole CreateFile line should be:

    HANDLE logFile = CreateFile( "Hdd:\\LOGFile.txt", FILE_APPEND_DATA , 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    

    Read CreateFile documentation carefully, it worth it, because it has a central role in the windows IO universe: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx

    look also add: https://stackoverflow.com/a/9891875/1922748