1

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.

Real
  • 91
  • 6

1 Answers1

2

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.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • Pardon my ignorance, but what is `assert` in your code – Real May 30 '18 at 11:48
  • A very cheap and simple substitute for error checking, it's a C macro, see [assert](http://en.cppreference.com/w/c/error/assert). `assert checks if its argument [...] compares equal to zero. If it does, assert outputs implementation-specific diagnostic information on the standard error output and calls abort()`. It's good to check every system call return value. – KamilCuk May 30 '18 at 11:53
  • @Real Note that `assert(0)` essentially crashes the program. Any serious program should use more robust error handling. – user694733 May 30 '18 at 11:58
  • It's alright, it's just an assignment for a data structures class in my uni, nothing too serious. Heck, i wasn't even required to print a tree like this, but i'm trying to stand out from others to get better grades obviously – Real May 30 '18 at 12:10
  • 1
    @Real You may also need to check that the output device can handle characters from CP437 and CP1252 (or whatever is used in Portuguese) at the same time. Better to go the Unicode route if the output device can handle it. Or you could use the "poor man's" line-drawing characters `+-|` etc. – Ian Abbott May 30 '18 at 12:17