Merge from coreutils.
[gnulib.git] / lib / hard-locale.c
1 /* hard-locale.c -- Determine whether a locale is hard.
2
3    Copyright (C) 1997, 1998, 1999, 2002, 2003, 2004 Free Software
4    Foundation, Inc.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software Foundation,
18    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #include "hard-locale.h"
25
26 #if HAVE_LOCALE_H
27 # include <locale.h>
28 #endif
29
30 #include <stdlib.h>
31 #include <string.h>
32
33 /* Return true if the current CATEGORY locale is hard, i.e. if you
34    can't get away with assuming traditional C or POSIX behavior.  */
35 bool
36 hard_locale (int category)
37 {
38 #if ! HAVE_SETLOCALE
39   return false;
40 #else
41
42   bool hard = true;
43   char const *p = setlocale (category, NULL);
44
45   if (p)
46     {
47 # if defined __GLIBC__ && 2 <= __GLIBC__
48       if (strcmp (p, "C") == 0 || strcmp (p, "POSIX") == 0)
49         hard = false;
50 # else
51       char *locale = malloc (strlen (p) + 1);
52       if (locale)
53         {
54           strcpy (locale, p);
55
56           /* Temporarily set the locale to the "C" and "POSIX" locales
57              to find their names, so that we can determine whether one
58              or the other is the caller's locale.  */
59           if (((p = setlocale (category, "C"))
60                && strcmp (p, locale) == 0)
61               || ((p = setlocale (category, "POSIX"))
62                   && strcmp (p, locale) == 0))
63             hard = false;
64
65           /* Restore the caller's locale.  */
66           setlocale (category, locale);
67           free (locale);
68         }
69 # endif
70     }
71
72   return hard;
73
74 #endif
75 }