Keep on going, never give up.

VS字符串类型及转换

看到VS中定义的字符串类型,可以用乱七八糟来形容,其实完全没有必要兼容(或是设计)如此多的字符串类型,该废弃的早该废弃统一,大量的重名定义尽管不会影响项目的设计,但是给研发人员造成极大的困扰,本文就整理一下这些字符串类型。主要来源winnt.h头文件。

一、字符串类型

typedef WCHAR *PWCHAR, *LPWCH, *PWCH;
typedef CONST WCHAR *LPCWCH, *PCWCH;

typedef _Null_terminated_ WCHAR *NWPSTR, *LPWSTR, *PWSTR;
typedef _Null_terminated_ PWSTR *PZPWSTR;
typedef _Null_terminated_ CONST PWSTR *PCZPWSTR;
typedef _Null_terminated_ WCHAR UNALIGNED *LPUWSTR, *PUWSTR;
typedef _Null_terminated_ CONST WCHAR *LPCWSTR, *PCWSTR;
typedef _Null_terminated_ PCWSTR *PZPCWSTR;
typedef _Null_terminated_ CONST PCWSTR *PCZPCWSTR;
typedef _Null_terminated_ CONST WCHAR UNALIGNED *LPCUWSTR, *PCUWSTR;

typedef _NullNull_terminated_ WCHAR *PZZWSTR;
typedef _NullNull_terminated_ CONST WCHAR *PCZZWSTR;
typedef _NullNull_terminated_ WCHAR UNALIGNED *PUZZWSTR;
typedef _NullNull_terminated_ CONST WCHAR UNALIGNED *PCUZZWSTR;

typedef  WCHAR *PNZWCH;
typedef  CONST WCHAR *PCNZWCH;
typedef  WCHAR UNALIGNED *PUNZWCH;
typedef  CONST WCHAR UNALIGNED *PCUNZWCH;

typedef CONST WCHAR *LPCWCHAR, *PCWCHAR;
typedef CONST WCHAR UNALIGNED *LPCUWCHAR, *PCUWCHAR;

//
//  UCS (Universal Character Set) types
//

typedef unsigned long UCSCHAR;

#ifndef _TCHAR_DEFINED
typedef WCHAR TCHAR, *PTCHAR;
typedef WCHAR TBYTE , *PTBYTE ;
#define _TCHAR_DEFINED
#endif /* !_TCHAR_DEFINED */

typedef LPWCH LPTCH, PTCH;
typedef LPCWCH LPCTCH, PCTCH;
typedef LPWSTR PTSTR, LPTSTR;
typedef LPCWSTR PCTSTR, LPCTSTR;
typedef LPUWSTR PUTSTR, LPUTSTR;
typedef LPCUWSTR PCUTSTR, LPCUTSTR;
typedef LPWSTR LP;
typedef PZZWSTR PZZTSTR;
typedef PCZZWSTR PCZZTSTR;
typedef PUZZWSTR PUZZTSTR;
typedef PCUZZWSTR PCUZZTSTR;
typedef PZPWSTR PZPTSTR;
typedef PNZWCH PNZTCH;
typedef PCNZWCH PCNZTCH;
typedef PUNZWCH PUNZTCH;
typedef PCUNZWCH PCUNZTCH;
#define __TEXT(quote) L##quote      // r_winnt

二、字符串转换

1、CString到LPWSTR

CString str;
LPWSTR  lpstr = (LPWSTR)(LPCWSTR)str;

2、CHAR到WCHAR转换

int   ibufLen=512;
WCHAR buf[ibufLen];
UCHAR tmp[256];
//init tmp
//...
size_t num = strlen((const char*)tmp);
MultiByteToWideChar(CP_ACP, 0, (const char *)tmp, (int)num, (LPWSTR)buf, (int)ibufLen);

3、WCHAR到CHAR转换

WCHAR str[512];
int len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
UCHAR *pTmp = new UCHAR[len + 1];
WideCharToMultiByte(CP_ACP, 0, str, -1, pTmp, len, NULL, NULL);
//...
delete pTmp;

4、如何将WCHAR写入文件

如果需要把WCHAR写入文件(默认Unicode方式保存),示例如下:

TCHAR * str=_T("Hello world!");
FILE* fp;
fp= fopen("a.txt", "a");
fwrite(str, sizeof(wchar_t), wcslen(str), fp);//注意第二个参数不是1
fclose(fp);

还有一种方式可先转换为CHAR格式后再保存。

更多类型:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v=vs.85).aspx

这些数据类型范围:

https://msdn.microsoft.com/en-us/library/s3f49ktz.aspx

参考资料:

http://blog.csdn.net/sl159/article/details/6412171

相关评论(0):  

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

订阅博客

最新文章

本站采用创作共用版权协议, 要求署名、非商业用途和保持一致. 转载也必须遵循“署名-非商业用途-保持一致”的创作共用协议. 返回顶部
Copyright@2005-2016 Metsky.com, All rights Reserved.