CString”转换为“const char *

在VS中有时候会遇到类似错误:

error C2664: “fopen_s”: 不能将参数 2 从“CString”转换为“const char *”

这是我们可以强制转换CString:

(LPSTR)(LPCTSTR)str

为什么会出现这种错误呢?我们打开菜单中的“项目/项目属性/配置属性/常规“,

可以看到常规中的字符集为”使用Unicode字符集“,原因就在这里。

有两种方法可以解决这个为题,下面举个具体的例子:

例如我想打开文件进行读写操作:

1. 将常规中的字符集设置为”多字节字符集“:

CString filename = _T("..\\data\\colorband\\colorband.txt");		
	FILE *hfile;		
	fopen_s(&hfile, filename,"r+");
2. 将常规中的字符集设置为”使用Unicode字符集“:

char fileName[100];
	strcpy(fileName,"F:/ccm/color_band(unicode)/data/colorband/colorband.txt");		
	FILE *hfile;		
	hfile = fopen(fileName, "r+");

注:Unicode情况下不能使用相对路径,关于Unicode和多字节字符集的区别请参考 http://blog.csdn.net/garfield2005/article/details/7681299

你可能感兴趣的:(C++基础问题,VC++常见错误)