Using code page 437 and setlocale at the same time

664 views Asked by At

There's a few special characters from code page 437 that i want to use within a function that prints n-ary trees so i can do something like this:

http://www.randygaul.net/wp-content/uploads/2015/06/Capture1.png (Basically something similar to the tree command in linux)

The problem is, my algorithm is using setlocale(LC_ALL, "Portuguese") which messes up with those special characters. I wanted to know if i can somehow apply C default locale to that function alone.

1

There are 1 answers

5
KamilCuk On BEST ANSWER

Just save the current locale, and then restore:

void func_with_my_own_locale(void) {
   const char * localesave = setlocale(LC_ALL, NULL);
   assert(localesave != NULL); // or some fprintf(stderr, ....);
   if (setlocale(LC_ALL, "CP437" /* or "" */) == NULL) {
       assert(0);
   }
   ...... 
   if (setlocale(LC_ALL, localesave) == NULL) {
       assert(0);
   }
}

Notice, locale is shared between all threads in a process, so you need to pause all other threads (or make sure they don't call any locale dependent functions) while calling such function.

From posix setlocale:

Upon successful completion, setlocale() shall return the string associated with the specified category for the new locale. Otherwise, setlocale() shall return a null pointer and the program's locale is not changed.
A null pointer for locale causes setlocale() to return a pointer to the string associated with the category for the program's current locale.
The string returned by setlocale() is such that a subsequent call with that string and its associated category shall restore that part of the program's locale.