CFile读⽂件和写⽂件。追加写⽂件读⽂件到CString
CFile file;
file.Open(_T("F:\\test.json"), CFile::modeRead);
DWORD len = file.GetLength();
char *Buf = new char[len+1];
//memset(Buf,0,len);
Buf[len] = '\0'; //0终⽌字符串,⽤于输出。
file.SeekToBegin();
file.Read(Buf, sizeof(char) * len);
file.Close();
CString strJson(Buf);
SafeDel(Buf);
写⽂件
void CXXXX::WriteFile(CString strContent, CString strFileName, BOOL bBOM /*= FALSE*/)
{
int u8Len = ::WideCharToMultiByte(CP_UTF8, NULL, strContent, (int)wcslen(strContent), NULL, 0, NULL, NULL);
char* szU8 = new char[u8Len + 1];
::WideCharToMultiByte(CP_UTF8, NULL, strContent, (int)wcslen(strContent), szU8, u8Len, NULL, NULL);
szU8[u8Len] = '\0'; //最后加上'\0'
CFile cFile;
cFile.Open(strFileName, CFile::modeWrite | CFile::modeCreate);
cFile.SeekToBegin();
if (bBOM)
{
cFile.Write("\xef\xbb\xbf", 3); //写BOM,同样低位写在前
}
cFile.Write(szU8, u8Len * sizeof(char));
cFile.Flush();
cFile.Close();
delete[] szU8;
szU8 = NULL;
}
追加写⽂件
truncate读void CXXXXX::WriteLogRecord(CString strContent, CString strFileName)
{
COleDateTime curtime = COleDateTime::GetCurrentTime();
CString strTime;
strTime.Format(_T("%d/%d/%d %d:%d:%d---"), curtime.GetYear(), curtime.GetMonth(), curtime.GetDay(),
curtime.GetHour(), curtime.GetMinute(), curtime.GetSecond());
strContent = strTime + strContent + _T("\r\n");
int u8Len = ::WideCharToMultiByte(CP_UTF8, NULL, strContent, (int)wcslen(strContent), NULL, 0, NULL, NULL);
char *szU8 = new char[u8Len + 1];
::WideCharToMultiByte(CP_UTF8, NULL, strContent, (int)wcslen(strContent), szU8, u8Len, NULL, NULL);
szU8[u8Len] = '\0';
CFile cFile;
cFile.Open(strFileName, CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate);
cFile.SeekToEnd();
cFile.Write(szU8, u8Len * sizeof(char));
cFile.Flush();
cFile.Close();
delete[] szU8;
szU8 = NULL;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论