C++文件操作——Unicode下有关字符类型转换(CString,string,char*)

1.CString转string

(1).使用函数T2A,W2A

CString cstrPath = L"D:\\Main\\Log\\Test.Log";
USES_CONVERSION;  
std::string str(W2A(cstrPath)); 

(2).使用WideCharToMultiByte函数

CString cstrPath = L"D:\\Main\\Log\\Test.Log";
int n = cstrPath.GetLength(); //按字符计算,str的长度  
int len = WideCharToMultiByte(CP_ACP,0,cstrPath,n,NULL,0,NULL,NULL);//按Byte计算str长度  
char *pChStr = new char[len+1];//按字节为单位  
WideCharToMultiByte(CP_ACP,0,cstrPath,n,pChStr,len,NULL,NULL);//宽字节转换为多字节编码  
pChStr[len] = '\0';//不要忽略末尾结束标志  
std::string str = pChStr;  
delete []pChStr; 

2.string转CString

CString cstrTemp;  
string str = "D:\\Main\\Log\\Test.Log";  
cstrTemp = const_cast<char*>(str.c_str());  

cstrTemp = str.data();

3.CString转char*

由于CString属于WCHAR类型,即宽字符(16/32位),而char类型一般为8位,所以需要进行转换操作,方法有如下:

(1).利用WideCharToMultiByte函数进行转换

CString cstrPath = L"D:\\Main\\Log\\Test.Log";
int len = WideCharToMultiByte(CP_ACP,0,cstrPath,cstrPath.GetLength(),NULL,0,NULL,NULL);
char * pLogPath = new char[len+1];   //以字节为单位
WideCharToMultiByte(CP_ACP,0,cstrPath,cstrPath.GetLength(),pLogPath,len,NULL,NULL);
pLogPath[len] = '\0';   //多字节字符以'/0'结束
FILE *fp = fopen(pLogPath,"r");

(2).使用函数T2A,W2A,注意有时可能需要添加#include <afxpriv.h>

CString cstrPath = L"D:\\Main\\Log\\Test.Log";
USES_CONVERSION;
//调用函数,T2A和W2A均支持ATL和MFC中的字符转换
char * pLogPath = T2A(cstrPath);
FILE *fp = fopen(pLogPath,"r");

4.char*转CString

(1).利用MultiByteToWideChar函数

char* pLogPath = "D:\\Main\\Log\\Test.Log"; 
//计算char *数组大小,以字节为单位,一个汉字占两个字节
int charLen = strlen(pLogPath);
//计算多字节字符的大小,按字符计算。
int len = MultiByteToWideChar(CP_ACP,0,pLogPath,charLen,NULL,0);
//为宽字节字符数组申请空间,数组大小为按字节计算的多字节字符大小
TCHAR *buf = new TCHAR[len + 1];
//多字节编码转换成宽字节编码
MultiByteToWideChar(CP_ACP,0,pLogPath,charLen,buf,len);
buf[len] = '\0'; //添加字符串结尾,注意不是len+1
//将TCHAR数组转换为CString
CString str;
str.Append(buf);
//删除缓冲区
delete []buf;
MessageBox(str);
(2).使用函数:A2T,A2W

char* pLogPath = "D:\\Main\\Log\\Test.Log"; 
USES_CONVERSION;
CString str = A2T(pLogPath);
MessageBox(str);

5.string转char*

string str = "D:\\Main\\Log\\Test.Log";  
char* pchTmp = (char*)str.data();
char* pchTmp1 = (char*)str.c_str();

6.char*转string,直接转换

char chTemp[MAX_PATH]="D:\\Main\\Log\\Test.Log";
string strTemp = chTemp;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值