Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf and wprintf in single C code

Tags:

I have a problem when using printf and wprintf functions together in code. If the regular string is printed first, then wprintf 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.

like image 657
Hubert Kario Avatar asked Dec 30 '11 16:12

Hubert Kario


2 Answers

This is to be expected; your code is invoking undefined behavior. Per the C standard, each FILE 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 the fwide function. Calling any function whose orientation conflicts with the orientation of the stream results in undefined behavior.

like image 73
R.. GitHub STOP HELPING ICE Avatar answered Nov 11 '22 12:11

R.. GitHub STOP HELPING ICE


To complement R..'s accepted answer:

While this is very rarely done, checking the return code of printf/wprintf would more clearly indicate that one of them is not working (it should return -1 for the print function which is invalid according to the current orientation of the stream).

Unfortunately, a common pattern for checking errors in standard library functions:

if (wprintf(...) == -1) { perror("wprintf"); ... } 

May not help much here: if the stream is set to output non-wide characters, and you call wprintf, errno may not be set and you'll get wprintf: Success, which does not provide much information.

So indeed this is a somewhat hard to understand issue when you don't know about the character orientation of streams.

like image 41
anol Avatar answered Nov 11 '22 13:11

anol