场景:
1. 通常生成文件时需要一个文件名,而生成文件名的方式可能是通过用户输入的字符,但是有些字符在windows上是不能作为文件名的,强行创建这类文件会失败。
2.一般可以通过正则表达式替换所有的非法字符,这里实现的是C++98 template(模板)方式的替换无效字符,std::string,std::wstring. 基本上windows上和字符串打交道都离不开wstring.
函数:
template<class T>
void FilterInvalidFileNameChar(T& str)
{
T t;
t.resize(9);
t[0] = 0x5C;
t[1] = 0x2F;
t[2] = 0x3A;
t[3] = 0x2A;
t[4] = 0x3F;
t[5] = 0x22;
t[6] = 0x3C;
t[7] = 0x3E;
t[8] = 0x7C;
int length = str.length();
for(int i = 0; i< length; ++i)
{
if(t.find(str[i]) != T::npos )
{
str[i] = 0x5F;
}
}
}
inline char* Unicode2Ansi(const wchar_t* unicode)
{
int len;
len = WideCharToMultiByte(CP_ACP, 0, unicode, -1, NULL, 0, NULL, NULL);
char *szUtf8 = (char*)malloc(len + 1);
memset(szUtf8, 0, len + 1);
WideCharToMultiByte(CP_ACP, 0,unicode, -1, szUtf8, len, NULL,NULL);
return szUtf8;
}
调用:
std::wstring wss(L"/asfasdf中国asdfas*dfa.txt");
FilterInvalidFileNameChar(wss);
cout << Unicode2Ansi(wss.c_str()) << endl;
std::string ss("/asfasdf\\asdfas*dfa.txt");
FilterInvalidFileNameChar(ss);
cout << ss.c_str() << endl;_asfasdf中国asdfas_dfa.txt _asfasdf_asdfas_dfa.txt
[C/C++标准库]_[初级]_[过滤Windows文件名中的非法字符]
原文:http://blog.csdn.net/infoworld/article/details/42033097