MFC的CFile类以追加模式写文件
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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现