C ++使用Unicode而不是Ansi创建文件

时间:2014-07-02 05:30:19

标签: c++ file-io unicode fstream ansi

为什么要使用C ++,如果你试图在文件中编写这样的结构,创建一个Unicode文件? 部分代码:

struct stEjemplo
{
    char cadena1[9];
    char cadena2[9];
};

写下我在cadena1中写的内容,cadena2在文件中显示了这样的内容:

㈱㐳㘵㠷㠀㘷㐵㈳o

示例:

fstream file("File.dat");
if(!file.is_open())
{
    file.open("File.dat", ios::in | ios::out | ios::trunc);
}
stEjemplo somest = {0};
strcpy(somest.origen, "SomeText");
strcpy(somest.destino, "SomeText");
file.clear();
file.seekg(0,ios::beg); //ios::end if existing information
file.write(reinterpret_cast< char*>(&somest), sizeof(stEjemplo));
file.close();

结果:

潓敭敔瑸匀浯呥硥t

注意最后的“t”(在第二个“SomeText”的最后一个中是“t”)

但如果我的结构是:

struct stEjemplo
{
    int number; //then I assign 1324
    char cadena1[9];
    char cadena2[9];
};

结果:, SomeText SomeText

struct stEjemplo
{
    bool x; //then I assign true o false
    char cadena1[9];
    char cadena2[9];
};

会产生类似:SomeText SomeText

的结果

修改

如果十六进制编辑器中的00(空字符)设置在奇数位置(从0开始,例如:1,3,5,7,9等等)我有问题,但如果设置为00在一对位置并且前面没有另一个00,问题就解决了。

3 个答案:

答案 0 :(得分:3)

你正在文本编辑器中打开File.dat,当它显然不是UTF-16LE时,用纯ASCII或UTF-8打开它(甚至使用十六进制编辑器)你应该看到字符串

潓敭敔瑸匀浯呥corresponds t对应UTF-16LE序列

53 6F 6D 65 54 65 78 74 00 53 6F 6D 65 54 65 78 74 00

猜猜这是什么时候读为普通的ASCII / UTF-8?

答案 1 :(得分:0)

这是一种处理事情的坏方法。它甚至可能是未定义的行为(由于结构成员的填充)。

为结构编写序列化代码会更好:

#include <cstring>
#include <fstream>
#include <iostream>

struct stEjemplo
{
    char cadena1[9];
    char cadena2[9];
};

std::ostream& operator<<(std::ostream& os, const stEjemplo& e)
{
  return os << e.cadena1 << ' ' << e.cadena2;
}

int main()
{
  stEjemplo somest = {};
  std::strcpy(somest.cadena1, "SomeText");
  std::strcpy(somest.cadena2, "SomeText");
  std::ofstream file("File.dat", std::ios::trunc);
  if(!file)
  {
    std::cout << "Failed opening file.\n";
  }
  file << somest;
  file.close();

  // no error checking, assuming all will go well
  std::ifstream test("File.dat");
  std::string contents;
  std::getline(test, contents);
  std::cout << contents;
}

Live demo here

此外:

  • 考虑使用std::string代替char[]strcpy
  • 在编写编码字符串等原始数据时考虑使用std::ios::binary

答案 2 :(得分:0)

Known Notepad bug。不是你的错。