A solution to the problem of Chinese character file names is to convert cstring to char * in Unicode and use widechartomultibyte for conversion.
There are many articles about the conversion of cstring to char * methods in UNICODE, but most of them are being reproduced from each other. After reading so many materials, the problem of garbled characters is still not solved, later, I found the correct method from a reply to a forum and would like to share it with you.
Summarize the Three conversion methods found on the Internet:
Method 1: Use the setlocale Function
Setlocale (lc_all, "CHS ");
Header file # include <locale. h>
The idea of this method is to configure the localized information. You can set it when you need to input and output Chinese characters. For more information, see setlocale.
Click me
Method 2: Use functions: T2A and w2a
Cstring STR = _ T ("D: // internal project // qq.bmp ");
// Declare the identifier
Uses_conversion;
// Call the function. T2A and w2a both support character conversion in ATL and MFC.
Char * pfilename = T2A (STR );
// Char * pfilename = w2a (STR); // conversion is also possible
Note: Sometimes you may need to add reference # include <afxpriv. h>
When using this method, pay attention to declaring identifiers, T2A, w2a details
Click me
Method 3: Use API: widechartomultibyte for conversion
Cstring STR = _ T ("D: // internal project // qq.bmp ");
// Note: The values of N and Len below are different in size. N is calculated by character, and Len is calculated by byte.
Int n = Str. getlength (); // n = 14, Len = 18
// Obtain the size of a wide byte, measured in bytes.
Int Len = widechartomultibyte (cp_acp, 0, STR, str. getlength (), null, 0, null, null );
// Apply for space for multi-byte character arrays. The array size is the size of the wide byte calculated in bytes.
Char * pfilename = new char [Len + 1]; // in bytes
// Convert the wide-byte encoding to multi-byte encoding
Widechartomultibyte (cp_acp, 0, STR, str. getlength (), pfilename, Len, null, null );
Widechartomultibyte (cp_acp, 0, STR, str. getlength () + 1, pfilename, Len + 1, null, null );
Pfilename [Len + 1] = '/0'; // multi-byte character ends with'/0'
These three methods are quite reliable, and many people have verified that they can be successful. However, when I use them, they are miserable, and none of them work. After careful consideration, the third method should be foolproof and the safest method. After careful searching, it turns out that the parameter is faulty. The yellow color is marked out by a wide range of methods circulating on the Internet, widechartomultibyte (cp_acp, 0, STR, str. getlength () + 1, pfilename, Len + 1, null, null); is the method of my successful verification. As to why, let everyone think about it. Widechartomultibyte