/src/print_env.cpp
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/categories.hpp>
#include <boost/iostreams/code_converter.hpp>
#include <boost/locale.hpp>
#include <string>
#include <stdlib.h>
#include <iostream>
int main()
{
std::string strCodePage = boost::locale::util::get_system_locale();
std::locale loc = boost::locale::generator().generate(strCodePage);
auto encoding = std::use_facet<boost::locale::info>(loc).encoding();
std::cout << " [ Locale ] code page : " << strCodePage << std::endl;
std::cout << " [ Locale ] country : " << std::use_facet<boost::locale::info>(loc).country() << std::endl;
std::cout << " [ Locale ] encoding : " << std::use_facet<boost::locale::info>(loc).encoding() << std::endl;
std::cout << " [ Locale ] language : " << std::use_facet<boost::locale::info>(loc).language() << std::endl;
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
set(PROJECT_NAME print_env)
project(${PROJECT_NAME})
include(CheckIncludeFileCXX)
set(CMAKE_CXX_STANDARD 17)
####################################################################
# boost
####################################################################
if(CMAKE_HOST_SYSTEM_NAME MATCHES "Windows")
set( Boost_ROOT "${LIB_PATH}/boost_1_86_0/stage/lib")
set( BOOST_LIBRARYDIR "${LIB_PATH}/boost_1_86_0/stage/lib")
elseif(CMAKE_HOST_SYSTEM_NAME MATCHES "Linux")
set( Boost_ROOT "${LIB_PATH}/boost_1_86_0/stage/lib")
set( BOOST_LIBRARYDIR "${LIB_PATH}/boost_1_86_0/stage/lib")
set ( Boost_LIBS boost_system
boost_filesystem
boost_locale )
endif()
find_package(Boost 1.62.0 REQUIRED)
include_directories( ${Boost_INCLUDE_DIRS} )
add_executable(print_env ${PROJECT_SOURCE_DIR}/src/print_env.cpp )
# libs
target_link_directories(print_env PRIVATE
${Boost_LIBRARY_DIRS}
)
输出:
这些信息的一个用处是在做 WCHAR -> std::string 转换时对系统编码做自适应。这样可以让代码容易兼容 windows 和 Linux等不同系统
std::string strCodePage = boost::locale::util::get_system_locale();
std::locale loc = boost::locale::generator().generate(strCodePage);
auto encoding = std::use_facet<boost::locale::info>(loc).encoding();
const std::string FPDF_WCHARToString(const FPDF_WCHAR* wideStr, const int len = 0)
{
try {
int wlen = len;
if (0 == wlen)
{
for (; (wlen < 65536) && wideStr[wlen]; wlen++);
}
if (0 == wlen)
{
return std::string();
}
wchar_t* wstr = new wchar_t[wlen];
for (int i=0; i < wlen; i++)
{
wstr[i] = wideStr[i];
}
std::string s = boost::locale::conv::from_utf<wchar_t>( (wchar_t*)wstr, (wchar_t*)wstr+len-1, encoding );
delete[] wstr;
return s;
} catch( boost::locale::conv::conversion_error & e ) {
std::cerr << " Error : " << e.what() << std::endl;
return e.what();
}
}