如何在 c++ 中的循环中执行 fwrite

How to perform fwrite in a loop in c++

本文关键字:循环 执行 fwrite c++      更新时间:2023-10-16

好吧,这是我的代码似乎失败了,甚至没有至少写一次,我看不出到底出了什么问题,谁能指出我正确的方向?

我的目的是在无限循环中每 10 秒执行一次写入

FILE* pFile;
pFile = fopen("Hdd:\LOGFile.txt", "w");
while(true) {
    DWORD TitleID = XamGetCurrentTitleId();
    std::ostringstream titleMessageSS;
    titleMessageSS << "Here's the current title we're on : " << TitleID << "r";
    std::string titleMessage = titleMessageSS.str(); // get the string from the stream
    DWORD dwBytesToWrite = (DWORD)titleMessage.size();
    DWORD dwBytesWritten = 0;
    fwrite(titleMessage.c_str(), 1 , dwBytesToWrite, pFile);
    Sleep(10000);
}
fclose(pFile);
return NULL;

您可能应该在致电Sleep之前致电fflush(pFile);;但是你应该最好使用C++ std::ostream(并使用std::flush操纵器(。

你怎么知道它不写? 文件是否在程序停止。

我怀疑的是您在程序已停止。 流类型(C++ 和 C(通常为缓冲; fwrite将数据复制到本地缓冲区,并且仅传输write当缓冲区为已满,当您显式刷新它时(请参阅fflush (或当文件已满时闭。 例如,这就是为什么我们必须检查输出错误的原因fclose()后.