在 Linux 中存储区域设置名称的缓冲区大小应该是多少?

What should be the size of buffer to store the locale name in Linux?

本文关键字:多少 缓冲区 存储 Linux 区域 设置      更新时间:2023-10-16

我想在Linux上存储setlocale((函数返回的区域设置名称。 与Windows平台一样,最大区域设置大小定义为LOCALE_NAME_MAX_LENGTH,是否有任何类似的宏为Linux定义?另外,我需要在上述两个平台上使用相同的缓冲区。

char buffer[];
buffer = setlocale(LC_ALL, NULL);

您在问题中建议的程序将不起作用。不能将setlocale的返回值(类型char *(分配给本地数组:

error: incompatible types in assignment of ‘char*’ to ‘char [10]’
buffer = setlocale(LC_ALL, NULL);
^

您必须将返回值分配给指针,然后您可以使用strlen检查其实际长度,并使用strcpy将其复制到数组中:

#include <locale.h>  // setlocale
#include <string.h>  // strlen, strcpy
#include <stdio.h>   // printf
int main()
{
char* pLocale;
pLocale = setlocale(LC_ALL, NULL);
char buffer[strlen(pLocale)+1];  // + 1 char for string terminator, see https://stackoverflow.com/a/14905963/711006
strcpy(buffer, pLocale);
printf("%sn", buffer);
return 0;
}

在线查看。

以上实际上是与 C 兼容的代码。如果您使用的是C++,则可以使用setlocale的返回值直接初始化std::string,而无需手动管理char数组:

#include <locale.h>  // setlocale
#include <iostream>
int main()
{
std::string locale = setlocale(LC_ALL, NULL);
std::cout << locale << std::endl;
return 0;
}

在线查看。