簡體   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