CFile类的Open函数有CFile::modeNoTruncate模式,该模式是非截断的意思,再配合CFile::modeCreate,意味着如果文件不存在,则创建,如果文件存在,则不会将文件内容清空。当对文件进行追加写入时,有一个小细节就是打开文件模式中虽然添加了这两种OpenFlag,但是文件指针并未移动到末尾,因此追加出现异常。正确的做法是在打开成功后,将文件指针移动至末尾,如下所示:
CFile file; if (file.Open(_T("d:\\a.txt"), CFile::modeCreate | CFile::modeWrite | CFile::typeBinary | CFile::modeNoTruncate)) { file.SeekToEnd(); } TCHAR* buf = _T("abcd123456\n"); file.Write(buf, _tcslen(buf)*sizeof(TCHAR)); file.Close();
有些时候,文件可能有BOM头,此时就需要特殊处理下,在SeekToEnd后,获取文件指针位置,判断是否是0,是0则写BOM,否则跳过,如下所示:
CFile file; if (file.Open(_T("d:\\a.txt"), CFile::modeCreate | CFile::modeWrite | CFile::typeBinary | CFile::modeNoTruncate)) { file.SeekToEnd(); if (file.GetPosition() == 0) { BYTE bom[] = { 0xFF, 0xFE }; file.Write(bom, _countof(bom)); } } TCHAR* buf = _T("abcd123456\n"); file.Write(buf, _tcslen(buf)*sizeof(TCHAR)); file.Close();
参考MSDN:
-
CFile::modeNoTruncate Combine this value with modeCreate. If the file being created already exists, it is not truncated to 0 length. Furthermore, if the file being created already exists, the underlying file pointer will point to the beginning of the file. This flag guarantees the file to open, either as a newly created file or as an existing file. This might be useful, for example, when opening a settings file that may or may not exist already. This option applies to CStdioFile as well.