为什么 WriteFile 不会 运行 不止一次?

Why does WriteFile not run more than once?

这是我的代码,其中我陷入了无限循环(据我所知)

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;

有人知道为什么只写一次吗?我已经等了5分钟多了,看看最后有没有什么效果。

CreateFile 中的标志 CREATE_NEW 阻止了文件更新,因为 CreateFile 失败 ERROR_FILE_EXISTS。请改用 OPEN_ALWAYS。 它也总是会被截断。 如果您想在日志文件末尾添加新行,请将 GENERIC_WRITE 替换为 FILE_APPEND_DATA

整个 CreateFile 行应该是:

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

仔细阅读 CreateFile 文档,这是值得的,因为它在 windows IO 世界中起着核心作用: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx

望补充:

正如 Martin James 在 MSDN 中提到的: CREATE_NEW

Creates a new file, only if it does not already exist.

If the specified file exists, the function fails and the last-error code is set to ERROR_FILE_EXISTS (80).

If the specified file does not exist and is a valid path to a writable location, a new file is created.

因此似乎在第一次调用后句柄无效,因此 WriteFile() 失败。