过滤Windows文件名中的非法字符

过滤Windows文件名中的非法字符

转载:http://blog.csdn.net/infoworld/article/details/42033097

场景:

1. 通常生成文件时需要一个文件名,而生成文件名的方式可能是通过用户输入的字符,但是有些字符在windows上是不能作为文件名的,强行创建这类文件会失败。

2.一般可以通过正则表达式替换所有的非法字符,这里实现的是C++98 template(模板)方式的替换无效字符,std::string,std::wstring. 基本上windows上和字符串打交道都离不开wstring.

 1 template<class T>
 2 void FilterInvalidFileNameChar(T& str)
 3 {
 4     T t;
 5     t.resize(9);
 6     t[0] = 0x5C; //     
 7     t[1] = 0x2F; //    /
 8     t[2] = 0x3A; //    : 
 9     t[3] = 0x2A; //    * 
10     t[4] = 0x3F; //    ? 
11     t[5] = 0x22; //    " 
12     t[6] = 0x3C; //    < 
13     t[7] = 0x3E; //    > 
14     t[8] = 0x7C; //    |
15     int length = str.length();
16     for(int i = 0; i< length; ++i)
17     {
18         if(t.find(str[i]) != T::npos )
19         {
20             str[i] = 0x5F;
21         }
22     }
23 }

1 inline char* Unicode2Ansi(const wchar_t* unicode)    
2 {    
3     int len;    
4     len = WideCharToMultiByte(CP_ACP, 0, unicode, -1, NULL, 0, NULL, NULL);    
5     char *szUtf8 = (char*)malloc(len + 1);    
6     memset(szUtf8, 0, len + 1);    
7     WideCharToMultiByte(CP_ACP, 0,unicode, -1, szUtf8, len, NULL,NULL);    
8     return szUtf8;    
9 }   

调用:

1 std::wstring wss(L"/asfasdf中国asdfas*dfa.txt");
2 FilterInvalidFileNameChar(wss);
3 cout << Unicode2Ansi(wss.c_str()) << endl;
4 
5 std::string ss("/asfasdf\asdfas*dfa.txt");
6 FilterInvalidFileNameChar(ss);
7 cout << ss.c_str() << endl;

输出:

_asfasdf中国asdfas_dfa.txt
_asfasdf_asdfas_dfa.txt
View Code