CStdioFile

来源:互联网 发布:b2c网络建站 编辑:程序博客网 时间:2024/05/29 18:08

CStdioFile是继承于CFile,VS中我们常用Unicode字符集和CString,用CFile操作并不一定方便,尤其是当我们写日志的时候。CStdioFile则专门定义了WriteString函数,非常方便。

//头文件#include <locale>#include <Windows.h>//////////////写日志函数里面//////////////////参数1:CString filename;文件名和路径//参数2:CString sLog;需要写入的日志信息//整理下日志内容,加上时间CTime tm = CTime::GetCurrentTime();CString str;str = tm.Format(L"\n\n%Y\\%m\\%d %H:%M:%S");  str = str + _T(":") + sText;CStdioFile fFileDate;fFileDate.Open(sFileName,CFile::modeNoTruncate | CFile::modeCreate | CFile::modeWrite | CFile::typeText); // 打开文件参数项 /*CFile::modeCreate     --- 如果文件不存在则创建,如果文件存在则打开文件并清空文件内容 CFile::modeCreate | CFile::CFile::modeNoTruncate     --- 如果文件不存在则创建,如果文件存在则打开文件并保留文件内容 CFile::shareDenyNone     --- 允许其它进程对文件读写 CFile::shareDenyRead     --- 不允许其它进程对文件进行读操作CFile::shareDenyWrite     --- 不允许其它进程对文件进行写操作 CFile::shareExclusive     --- 以独占模式打开文件,不允许其它进程对文件进行读写*/setlocale(LC_CTYPE,"chs"); /*Unicode字符下,CStdioFile的Writestring无法写入中文添加#include <locale>头文件char* old_locale = _strdup( setlocale(LC_CTYPE,NULL) );setlocale( LC_CTYPE, "chs" );//设定file.WriteString(_T("abc中文"));//正常写入setlocale( LC_CTYPE, old_locale );free( old_locale );//还原区域设定如果不需要还原设定,直接用setlocale即可*///fFileDate.Seek(0,CFile::end); CFile的写法fFileDate.SeekToEnd(); //移到末尾,下次即变成追加fFileDate.WriteString(str);fFileDate.Close();

读文件也一样很简单:

// 打开文件 CStdioFile file; BOOL ret = file.Open(cstrFileFullPath, CFile::modeRead | CFile::shareDenyNone); if (!ret) {     AfxMessageBox("打开文件失败");     return; } file.SeekToBegin(); // 循环读取文件 CString cstrLine; while (file.ReadString(cstrLine)) {     AfxMessageBox(cstrLine); } // 关闭文件 file.Close();
原创粉丝点击