#C 语言标准库函数 setlocale
/*********************************************
* @brief 获取和设置区域
* @param category 要设置的类别
* @param locale 要设为的区域
* @return 设置后的区域
********************************************/
char* setlocale(int category, const char* locale);
说明
将本地化类别 category
的区域设为 locale
。
参数
category
- 要设置的类别LC_ALL
- 设置全部类别LC_NUMERIC
- 设置数值格式LC_TIME
- 设置时间格式LC_MONETARY
- 设置货币格式LC_CTYPE
- 设置字符分类LC_COLLATE
- 设置排序规则
locale
- 要设为的区域""
- 用户首选的语言环境"C"
- 最小的基本区域设置
返回值
- 成功时返回设置后的区域
- 失败时返回
NULL
#示例
#include <stdio.h>
#include <locale.h>
#include <time.h>
int main(void) {
// 1. 获取当前 locale
char *old_locale = setlocale(LC_ALL, NULL);
printf("当前locale: %s\n", old_locale);
// 2. 设置为 zh_CN.UTF-8
char *new_locale = setlocale(LC_ALL, "zh_CN.UTF-8");
if (new_locale == NULL) {
printf("无法设置locale\n");
return 1;
}
printf("新locale: %s\n", new_locale);
// 3. 演示数字格式
printf("\n数字格式示例:\n");
printf("本地格式: %'d\n", 123456789);
printf("默认格式: %d\n", 123456789);
// 4. 演示货币格式
struct lconv *lc = localeconv();
printf("\n货币格式示例:\n");
printf("本地货币符号: %s\n", lc->currency_symbol);
printf("正数货币格式: %s%.2f\n", lc->currency_symbol, 1234.56);
// 5. 演示时间格式
time_t t = time(NULL);
struct tm *lt = localtime(&t);
char time_str[100];
strftime(time_str, sizeof(time_str), "%c", lt);
printf("\n本地时间格式: %s\n", time_str);
strftime(time_str, sizeof(time_str), "%x", lt);
printf("本地日期格式: %s\n", time_str);
strftime(time_str, sizeof(time_str), "%X", lt);
printf("本地时间格式: %s\n", time_str);
// 6. 恢复原始locale
setlocale(LC_ALL, old_locale);
return 0;
}
运行结果:
当前locale: C 新locale: zh_CN.UTF-8 数字格式示例: 本地格式: 123,456,789 默认格式: 123456789 货币格式示例: 本地货币符号: ¥ 正数货币格式: ¥1234.56 本地时间格式: 2025年07月29日 星期二 19时10分33秒 本地日期格式: 2025年07月29日 本地时间格式: 19时10分33秒
#推荐阅读
#外部参考
#参考标准
- C23 standard (ISO/IEC 9899:2024):
- 7.11.1.1 The setlocale function (p: TBD)
- C17 standard (ISO/IEC 9899:2018):
- 7.11.1.1 The setlocale function (p: 163-164)
- C11 standard (ISO/IEC 9899:2011):
- 7.11.1.1 The setlocale function (p: 224-225)
- C99 standard (ISO/IEC 9899:1999):
- 7.11.1.1 The setlocale function (p: 205-206)
- C89/C90 standard (ISO/IEC 9899:1990):
- 4.4.1.1 The setlocale function