zoukankan      html  css  js  c++  java
  • Windows使用UTF16,创建UTF16文件请设置前两个字节为0xfffe,这是UTF16的BOM码

    windows下的Unicode是UTF-16,每个字都用两个字节来表示。编程的时候,通过TEXT宏,以及在项目中定义Unicode, _Unicode变量,就可以保证整个项目都是在Unicode下工作。

    现在在将字符串写入文件的时候,发生了一些问题。写文件用的是WriteFile函数,字符串本身都是UTF-16的,写入文件后发现用vim和记事本打开都无法正确显示。用16进制的方式查看,每个字都是对的,都是2个字节,如果是英文字母,第二个字节就是00。

    google 了一下,发现了答案。要在文件开头写入0xfffe,这是Unicode file的identifier,windows下的记事本和写字板读到这个头之后,就能正确识别这是一个Unicode文件了。所以,在代码中,创建文 本文件的时候,要多写这样一段(用ScheduleDownload的logger.cpp来做个例子):


                        // logfile doesn't exist, create it, that's all
              hFile = CreateFile(log_file_path, GENERIC_WRITE, NULL, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
              
    if (hFile == INVALID_HANDLE_VALUE) {
                 operate_result 
    = FALSE;
              } 
    else {
                 
    // write 0xfffe at the beginning of the file, this makes Notepad reads Unicodes well
                 WORD unicode_identifier = 0xfeff;
                 
    if (WriteFile(hFile, &unicode_identifier, sizeof(WORD), &bytes_written, NULL)) {
                    operate_result 
    = TRUE;
                 } 
    else {
                    operate_result 
    = FALSE;
                 }
              }
              
    goto finished;

        finished:
           
    if (hFile != NULL && hFile != INVALID_HANDLE_VALUE)
              CloseHandle(hFile);
           
    return operate_result;
    这里不要奇怪为什么设置给unicode_identifier变量的值是0xfeff,这是因为x86是little endian,所以代码中的oxfeff存在寄存器中,然后设置到内存的时候,从低地址到高地址就变成了fffe,这样最后将这个WORD写入文件之后就 正好是fffe了。

    最后我自己又测试了一下,写入中文也是没有问题的。使用gvim来打开的话需要设置一下,我在Ubuntu下打开文件是OK的,windows下的gvim的.vimrc设置和Ubuntu一样的话,应该也是没问题的。

  • 相关阅读:
    2013.4.15 Particle Swarm Optimization with Skyline Operator for Fast Cloudbased Web Service Composition
    Adaptive service composition in flexible processes
    2013.4.13 DomainSpecific Service Selection for Composite Services
    2013.4.14 Modeling and Algorithms for QoSAware Service Composition in VirtualizationBased Cloud Computing
    2013.5.29 Towards Networkaware Service Composition in the Cloud
    Efficient algorithms for Web services selection with endtoend QoS constraints
    SQL Server中常用的SQL语句
    接口限流自定义注解
    linux服务器生产环境搭建
    MVEL自定义函数重复掉用报错:duplicate function
  • 原文地址:https://www.cnblogs.com/super119/p/2011406.html
Copyright © 2011-2022 走看看