写入文件会产生空文件或根本没有文件
writing to file produces an empty file or no file at all
我的 GUI 在一台机器上运行,如果发生错误,应该按其按钮关闭(而不是通过 windows 屏幕)。
GUI 使用 CStdioFile 对象将错误日志写入文件,然后弹出错误 window 通知用户关闭机器。
似乎在某些情况下,windows 正在删除这个文件,或者文件在那里但它是空的。看起来文件是写入 RAM 而不是硬盘,因为我“粗暴”地关闭了它。
我试图添加:
int 文件长度 = myFile.GetLength();
并查看 fileLength 获得正确的长度,但即使这样文件也被删除/清空。
还尝试添加 myFile.Flush();强制系统将文件写入硬盘。还是不行。
我该怎么做才能解决这个问题?
void WriteToErrorLog(CString str, CString traceID)
{
CFileException fileEx;
CFile fileParam;
CString strFilePath = _T("C:/Errors/errors.log");
CStdioFile myFile;
if (myFile.Open(strFilePath, CFile::modeCreate | CFile::modeNoTruncate | CFile::modeWrite))
{
myFile.SeekToEnd();
myFile.WriteString(str);
myFile.Flush();
myFile.Close();
if (myFile.Open(strFilePath, CFile::modeRead))
{
int fileLength=myFile.GetLength();
myFile.Close();
}
}
来自 CFile
documentation 关于 modeCreate
标志:
Creates a new file if no file exists. If the file already exists, it's overwritten and initially set to zero length.
然后对于 modeNoTruncate
标志:
Creates a new file if no file exists; otherwise, if the file already exists, it's attached to the CFile
object.
简而言之,打开文件时不应使用 modeCreate
标志。
问题不在于 modeCreate。正如我所写,文件 是 正确创建的,但在关闭机器时被删除了。
看来我发现了问题:
后
myFile.Flush();
我加了
FlushFileBuffers(我的文件)
这会导致将所有缓冲数据写入文件。
这迫使 windows 将文件写入磁盘。看来现在可以正常使用了。
我的 GUI 在一台机器上运行,如果发生错误,应该按其按钮关闭(而不是通过 windows 屏幕)。 GUI 使用 CStdioFile 对象将错误日志写入文件,然后弹出错误 window 通知用户关闭机器。 似乎在某些情况下,windows 正在删除这个文件,或者文件在那里但它是空的。看起来文件是写入 RAM 而不是硬盘,因为我“粗暴”地关闭了它。 我试图添加: int 文件长度 = myFile.GetLength(); 并查看 fileLength 获得正确的长度,但即使这样文件也被删除/清空。 还尝试添加 myFile.Flush();强制系统将文件写入硬盘。还是不行。
我该怎么做才能解决这个问题?
void WriteToErrorLog(CString str, CString traceID)
{
CFileException fileEx;
CFile fileParam;
CString strFilePath = _T("C:/Errors/errors.log");
CStdioFile myFile;
if (myFile.Open(strFilePath, CFile::modeCreate | CFile::modeNoTruncate | CFile::modeWrite))
{
myFile.SeekToEnd();
myFile.WriteString(str);
myFile.Flush();
myFile.Close();
if (myFile.Open(strFilePath, CFile::modeRead))
{
int fileLength=myFile.GetLength();
myFile.Close();
}
}
来自 CFile
documentation 关于 modeCreate
标志:
Creates a new file if no file exists. If the file already exists, it's overwritten and initially set to zero length.
然后对于 modeNoTruncate
标志:
Creates a new file if no file exists; otherwise, if the file already exists, it's attached to the
CFile
object.
简而言之,打开文件时不应使用 modeCreate
标志。
问题不在于 modeCreate。正如我所写,文件 是 正确创建的,但在关闭机器时被删除了。 看来我发现了问题: 后 myFile.Flush(); 我加了 FlushFileBuffers(我的文件) 这会导致将所有缓冲数据写入文件。 这迫使 windows 将文件写入磁盘。看来现在可以正常使用了。