fprintf不打印Unicode字符

时间:2013-05-24 13:28:30

标签: c++ c visual-c++ mfc

今天早上我发现了一个非常奇怪的问题,我找不到解决方案。请使用下面的代码帮助我解决这个问题(使用Visual Studio C ++和MFC):

FILE *fp = NULL;
//fp = fopen(mmFileName , "a");
//Store the module directory path
fopen_s( &fp , "TempWorking.xml" , "wb");
//char* TempChar;
CString strtempff;
strtempff = "\"<article>  <section class="page"><p>Writing for the clown show that is <em>Forbes</em>, Darcy Travlos asks the <a href="http://en.wikipedia.org/wiki/Betteridge%27s_law_of_headlines">Betteridge’s Law</a>-challenging question “Apple And Google: The New ‘Old’ Reality?†(No link but tip o’ the an";
char* TempArray;
TempArray = new char[strtempff.GetLength()];
strcpy(TempArray,strtempff.GetString());
strtempff = "";
strtempff.Empty();
fprintf(fp,(char*)TempArray);

我不知道为什么我的代码没有在fprintf()语句中工作:它给了我一个调试断言。从网上收集strtempff,这只是代码中的一个例子。

2 个答案:

答案 0 :(得分:2)

我相信你的错误是你向fprintf提供了一个不是格式字符串的字符串。你应该这样做:

fprintf(fp,"%s",(char*)TempArray);

要解释一下,字符串中的任何%字符都会混淆它,因为它们是printf系列函数的特殊格式字符。关于缓冲区长度不足的其他评论也是正确的,您也需要解决这个问题。

您可能还想使用fwprintf和宽字符串,因为您正在尝试打印扩展字符集。 http://www.cplusplus.com/reference/cwchar/fwprintf/

答案 1 :(得分:1)

CString::GetLength()函数不包含0终止符,因此您声明的数组太小。

例如,如果CString为“a”,则GetLength()将返回1,您将分配1个字符的TempArray,然后strcpy()将写入2个字符,因为它终止字符串,导致缓冲区溢出和未定义的行为。