How do I remove the difference in locale between gui and commandline interfaces of same program?

让人想犯罪 __ 提交于 2019-12-11 11:19:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!