pastebin - collaborative debugging tool
rovema.kpaste.net RSS


thread_locale1.c - Per-thread locale demo
Posted by Anonymous on Tue 31st Jan 2023 09:03
raw | new post
view followups (newest first): thread_locale1.c - Per-thread locale demo by Anonymous
modification of post by Anonymous (view diff)

  1. /*
  2.  * thread_locale1.c - Per-thread locale demo
  3.  *
  4.  * Written by Roland Mainz <roland.mainz@nrubsig.org>
  5.  */
  6.  
  7. #define _XOPEN_SOURCE 700
  8.  
  9. #include <stdlib.h>
  10. #include <stdio.h>
  11. #include <locale.h>
  12.  
  13. #ifdef __GLIBC__
  14. /* { BSD, MacOSX, Illumos, ... } do not need this! */
  15. #define CURSED_GLIBC_DOES_NOT_HAVE_PRINTF_L
  16. #endif
  17.  
  18. #ifdef CURSED_GLIBC_DOES_NOT_HAVE_PRINTF_L
  19. #include <stdarg.h>
  20. #include <errno.h>
  21. #endif /* CURSED_GLIBC_DOES_NOT_HAVE_PRINTF_L */
  22.  
  23. #ifdef CURSED_GLIBC_DOES_NOT_HAVE_PRINTF_L
  24. /* cursed glibc does not provide |printf_l()| */
  25. int vprintf_l(locale_t loc, const char *format, va_list ap)
  26. {
  27.         int ret;
  28.         int saved_errno;
  29.         locale_t prev_loc;
  30.  
  31.         prev_loc = uselocale(loc);
  32.        
  33.         ret = vprintf(format, ap);
  34.         saved_errno = errno;
  35.  
  36.         (void)uselocale(prev_loc);
  37.  
  38.         errno = saved_errno;
  39.         return ret;
  40. }
  41.  
  42. int printf_l(locale_t loc, const char *format, ...)
  43. {
  44.         int res;
  45.  
  46.         va_list args;
  47.         va_start(args, format);
  48.         res = vprintf_l(loc, format, args);
  49.         va_end(args);
  50.  
  51.         return res;
  52. }
  53. #endif /* CURSED_GLIBC_DOES_NOT_HAVE_PRINTF_L */
  54.  
  55.  
  56. int main(int ac, char *av[])
  57. {
  58.         locale_t my_en_l;
  59.         locale_t my_de_l;
  60.         double x;
  61.        
  62.         my_en_l = newlocale(LC_ALL_MASK, "en_US.UTF-8", NULL);
  63.         my_de_l = newlocale(LC_ALL_MASK, "de_DE.UTF-8", NULL);
  64.        
  65.         if ((my_en_l == (locale_t)0) || (my_de_l == (locale_t)0)) {
  66.                 perror("Could not create locale object");
  67.                 return EXIT_FAILURE;
  68.         }
  69.  
  70.         x = 123456.789123456789;
  71.         (void)printf_l(my_en_l, "%8.3f\n", x);
  72.         (void)printf_l(my_de_l, "%8.3f\n", x);
  73.  
  74.         freelocale(my_de_l);
  75.         freelocale(my_en_l);
  76.  
  77.         return EXIT_SUCCESS;
  78. }

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with {%HIGHLIGHT}




All content is user-submitted.
The administrators of this site (kpaste.net) are not responsible for their content.
Abuse reports should be emailed to us at