printf and wprintf in single C code

来源:互联网 发布:java byte 表示0xff 编辑:程序博客网 时间:2024/05/29 13:45

I have a problem when using printf an wprintf functions together in code. If the regular string is printed first, thenwprintf doesn't work. If I use wprintf first then printf doesn't work.

#include <stdio.h>#include <wchar.h>#include <stdlib.h>#include <locale.h>int main() {    setlocale(LC_ALL,"");    printf("No printing!\n");    wprintf(L"Printing!\n");    wprintf(L"Wide char\n");    printf("ASCII\n");    return 0;}

Outputs:

No printing!ASCII

While

#include <stdio.h>#include <wchar.h>#include <stdlib.h>#include <locale.h>int main() {    setlocale(LC_ALL,"");    wprintf(L"Printing!\n");    printf("No printing!\n");    wprintf(L"Wide char\n");    printf("ASCII\n");    return 0;}

outputs:

Printing!Wide char

I'm using gcc (GCC) 4.6.1 20110819 together with glibc 2.14 on 64bit Linux 3.0.




This is to be expected; your code is invoking undefined behavior. Per the C standard, eachFILE stream has associated with it an "orientation" (either "byte" or "wide) which is set by the first operation performed on it, and which can be inspected with thefwide function. Calling any function whose orientation conflicts with the orientation of the stream results in undefined behavior.

shareimprove this answer
 
 
Is is undefined behavior or simply outputting nothing if the orientation mismatches the data to be written? – alk Dec 30 '11 at 17:25
 
Based on this:gnu.org/savannah-checkouts/gnu/libc/manual/html_node/…, the behavior is undefined. – DRH Dec 30 '11 at 17:42
1 
@alk Undefined behavior means there are no expectations for how it should behave in this circumstance. Therefore, outputting nothing is acceptable, as is silently converting the text to the proper orientation or printing garbage. –  That Chuck Guy Dec 30 '11 at 17:46
1 
OK, so it's a bug in wprintf(3) man page: it doesn't mention this problem... – Hubert Kario Dec 30 '11 at 18:42
1 
@Hubert: it's not a bug in the man page.kernel.org/doc/man-pages/online/pages/man3/wprintf.3.html says: "stdout must not be byte oriented" – Michael Burr Dec 30 '11 at 19:20

0 0