How to convert a UNICODE string to an ANSI C null-terminated string ?

In some cases, you may need to convert a unicode string into an ANSI C null-terminated string. The WideCharToMultiByte function allows you to do this.

In the following example, I have used the ReadDirectoryChangesW function to detect a file modification in a directory. The name of the modified file is stored in UNICODE format. I want to convert it to  a standard C string.

PFILE_NOTIFY_INFORMATION pstFileNotif;

// Initialization of pstFileNotif

char szNotifFilename[ MAX_PATH ] = { 0 };
int iNbChar = WideCharToMultiByte(
CP_OEMCP,
NULL,
pstFileNotif->FileName,
pstFileNotif->FileNameLength / sizeof( WCHAR ),
szNotifFilename,
sizeof( szNotifFilename ) / sizeof( char ),
NULL, NULL ) ;

if ( iNbCar == 0 )
{
// Error
}

Be careful : the size of the 2 strings is not their length in bytes, but their length in characters (a UNICODE character takes 2 bytes)

Leave a Reply

Your email address will not be published. Required fields are marked *