1. 问题简述
在很多项目中,采用char保存数据,这样在含有unicode的路径(eg:中文路径)情况下,会无法访问。
2. 解决方法——GetShortPathName
WinAPI提供了一种方法——GetShortPathName:对已经存在的文件,会产生一个ID值,表示这个文件。
3. 具体方法
long length = 0;
TCHAR* buffer = NULL;
CString s_path = _T("E:\\影视\\【Mvevo.com分享】周杰伦-魔天伦CF.mp4");
//LPWSTR lpwszFileName = (wchar_t*)s_path.c_str();
// First obtain the size needed by passing NULL and 0.
length = GetShortPathName(s_path, NULL, 0);
if (length == 0)
cout<<"ERROR! GetShortPathName: "<<length<<endl;
buffer = new TCHAR[MAX_PATH];
memset(buffer, 0, MAX_PATH );
length = GetShortPathName(s_path, buffer, MAX_PATH);
if (length == 0)
cout<<"ERROR! GetShortPathName: "<<length<<endl;
_tprintf(TEXT("long name = %s \nshortname = %s \n"), s_path, buffer);
delete [] buffer;
4. 参考
(1)http://msdn.microsoft.com/en-us/library/windows/desktop/aa364989%28v=vs.85%29.aspx
(2)http://blog.sina.com.cn/s/blog_7a1896ee0100pk03.html
本文介绍了一个常见问题的解决方案:当项目使用char类型处理包含Unicode字符(如中文)的路径时,可能导致文件访问失败。通过Windows API提供的GetShortPathName函数,可以为长路径生成一个短路径名,从而解决此问题。

3042

被折叠的 条评论
为什么被折叠?



