繁体   English   中英

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

[英]C++ create a file in Unicode instead of 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,此问题已解决。

当您在文本编辑器中打开File.dat时,如果它不是很明显, File.dat UTF-16LE格式打开,以纯ASCII或UTF-8(甚至使用十六进制编辑器)打开它,您应该会看到字符串。

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

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

当以纯ASCII / UTF-8格式读取时,您猜这是什么?

这是一种不好的处理方式。 它甚至可能是未定义的行为(由于struct成员的填充)。

最好为您的结构编写序列化代码:

#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;
}

现场演示

也:

  • 考虑使用std::string代替char[]strcpy
  • 写原始数据(如编码字符串)时,请考虑使用std::ios::binary

已知的记事本错误 不是你的错。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM