现在的位置: 首页 > 综合 > 正文

写字符串到文本【可设定格式】

2013年10月13日 ⁄ 综合 ⁄ 共 1694字 ⁄ 字号 评论关闭
/*******************************************************************************
函数名称:				WorkClass::WriteString2File	写字符串内容到文件
================================================================================
参数说明:				const CString strText 文件内容
参数说明:				const CString strSavePath 文件路径
参数说明:				BOOL bUtf_8 是否为UTF-8格式
--------------------------------------------------------------------------------
返回值:					BOOL
--------------------------------------------------------------------------------
文件作者:				King.Sollyu					QQ:191067617
*******************************************************************************/BOOL WorkClass::WriteString2File( const CString strText,const CString strSavePath,BOOL bUtf_8 )
{
	CFile fileText; CFileException fileException;
	if (fileText.Open(strSavePath,CFile::modeReadWrite|CFile::modeCreate,&fileException) == FALSE)
	{
		ASSERT (FALSE);
		// 打开文件错误,识别什么错误
		switch (fileException.m_cause)
		{
		case CFileException::fileNotFound:	return SetLastError(ERR_FILENOTFOUND),FALSE;break;
		case CFileException::accessDenied:	return SetLastError(ERR_ACCESSDENIED),FALSE;break;
		case CFileException::sharingViolation: return SetLastError(ERR_SHARINGVIOLATION),FALSE;break;
		default:return SetLastError(ERR_UNKNOW),FALSE;break;
		}
	}

	if (bUtf_8 == TRUE)
	{
		unsigned char data[3] = {0xEF, 0xBB, 0xBF};
		fileText.Write(data,3);
		int nSrcLen = (int)wcslen(strText);
		CStringA utf8String(strText);
		int nBufLen = (nSrcLen+1) * 6;
		LPSTR buffer = utf8String.GetBufferSetLength(nBufLen);
		// 将UNICODE 转换成UTF8
		// 需要函数AtlUnicodeToUTF8 头文件: <atlenc.h>
		int nLen = AtlUnicodeToUTF8(strText, nSrcLen, buffer, nBufLen);   
		buffer[nLen] = 0;
		utf8String.ReleaseBuffer();
		//写文件
		fileText.SeekToEnd();
		fileText.Write((LPCSTR)utf8String, nLen);
	}else
	{
		CStringA strANSI(strText);
		fileText.Write((LPCSTR)strANSI,strANSI.GetLength());
	}

	fileText.Close();
	return TRUE;

}

抱歉!评论已关闭.