问题
The program saves a settings file as text which contains floating point numbers of type long double
. The settings file can only be saved via the GUI (GTK2), while files can also be loaded via the command line and without bringing up the GUI.
Unfortunately, a user reports that in the files he has saved, due to his locale setting, the numbers are formatted with commas and the program refuses to load them (emitting error messages) from the command line but seems to load them when the GUI is open.
I have already asked the following question: MPFR, printf, decimal places, locales, file i/o problem which suggested using setlocale(LC_ALL, "C")
which I placed at the beginning of main
. As this did not work, I placed it after calling gtk_init_check
but again, it made no difference. (EDIT It did make a difference after I installed a few locales.)
I want the program to always use the same locale setting (or non-localized locale setting - "C") for these data files it saves, but don't want to mess up the GUI by doing so.
How?
回答1:
do not use locale sensitive functions for save and restore values at all. For example use ieee754.h for save and loading mantissa and exponent.
回答2:
If you can live with only storing these values as double
, I would simply suggest using glib's ASCII-limited string formatting/parsing functions:
To convert a value to string, call g_ascii_dtostr()
. To go the other way, use g_ascii_strtod()
.
I realize this might be bad since you drop precision going from long double
to plain old (g)double
, of course. It doesn't seem glib supports a long double
type, are you sure it really gives you more precision?
回答3:
Store the locale in use at the top of your load/save code:
char* loc = setlocale(LC_NUMERIC, NULL);
Then for every instance where you write numeric values to your file call:
setlocale(LC_NUMERIC, "C");
/* code here for read/write of numeric values:
fprintf(fd, "aspect %0.20lf\n", img->aspect);
*/
setlocale(LC_NUMERIC, loc);
Should do the trick.
来源:https://stackoverflow.com/questions/2171527/how-do-i-remove-the-difference-in-locale-between-gui-and-commandline-interfaces