Reprint: http://blog.csdn.net/infoworld/article/details/42033097
Scene:
1. A file name is usually required to generate files, which may be generated by user-entered characters, but some characters cannot be used as filenames on windows, and forcing the creation of such files will fail.
2. It is generally possible to replace all illegal characters with regular expressions, where the c++98 template (template) substitution of invalid characters is implemented, std::string,std::wstring. Basically, the windows and strings are inseparable from wstring.
1template<classT>2 voidFilterinvalidfilenamechar (t&str)3 {4 T T;5T.resize (9);6t[0] =0x5C;// \ 7t[1] =0x2F;// /8t[2] =0x3A;// : 9t[3] =0x2A;// * Tent[4] =0x3F;// ? Onet[5] =0x22;// " At[6] =0x3C;//< -t[7] =0x3e;//> -t[8] =0x7C;// | the intLength =str.length (); - for(inti =0; i< length; ++i) - { - if(T.find (str[i])! =T::npos) + { -Str[i] =0x5f; + } A } at }
1InlineChar* Unicode2ansi (Constwchar_t*Unicode)2 { 3 intLen; 4Len = WideCharToMultiByte (CP_ACP,0, Unicode,-1Null0, NULL, NULL); 5 Char*szutf8 = (Char*) malloc (len +1); 6memset (SzUtf8,0, Len +1); 7WideCharToMultiByte (CP_ACP,0, Unicode,-1, SzUtf8, Len, null,null); 8 returnSzUtf8; 9}
Call:
1 std::wstring WSS (L"/asfasdf China 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;
Output:
_ASFASDF China Asdfas_dfa.txt_asfasdf_asdfas_dfa.txt
View Code
Filter illegal characters in the Windows file name