在C#中写入二进制文件,然后在C#x2B中读取相同的文件+;
我正在使用BinaryWriter类用C#编写一个二进制文件在C#中写入二进制文件,然后在C#x2B中读取相同的文件+;,c#,c++,binaryfiles,C#,C++,Binaryfiles,我正在使用BinaryWriter类用C#编写一个二进制文件 using (var b = new System.IO.BinaryWriter(System.IO.File.Open("C:\\TextureAtlas0.txa", System.IO.FileMode.Create))) { int count; // Write the number of source rectangle entries count = textureAtlas.Rectan
using (var b = new System.IO.BinaryWriter(System.IO.File.Open("C:\\TextureAtlas0.txa",
System.IO.FileMode.Create)))
{
int count;
// Write the number of source rectangle entries
count = textureAtlas.Rectangles.Count;
b.Write(count);
for (int i = 0; i < count; ++i)
{
b.Write(textureAtlas.SpriteNames[i]);
b.Write(textureAtlas.Rectangles[i].X);
b.Write(textureAtlas.Rectangles[i].Y);
b.Write(textureAtlas.Rectangles[i].Width);
b.Write(textureAtlas.Rectangles[i].Height);
}
}
首先读取计数
int count;
fread(&count, sizeof(int), 1, LoadFile);
然后,我尝试使用计数值来确定保存数据的列表大小。我似乎不能使用数组,因为计数的值会因读取的文件而异
std::list<TextureAtlasEntry> entries;
fread(&entries, sizeof(TextureAtlasEntry), count, LoadFile);
fclose(LoadFile);
现在文件在内存中,如何将char[]数据转换为struct数据?根据,BinaryWriter(字符串)写入
以长度为前缀的字符串表示字符串长度,其前缀为
字符串是包含该字符串长度的单个字节或单词
一串此方法首先将字符串的长度写入UTF-7
编码的无符号整数,然后将那么多字符写入
使用BinaryWriter实例的当前编码进行流
<>在C++代码中,您只是尝试读取结构大小的字节数,这是比BIN使用的不同格式。
你使用C++的C++代码吗?如果是这样,只需使用BinaryReader类来读取文件即可
如果没有,你就得把阅读分成几部分。当您准备读取名称时,首先必须读取一个“UTF-7编码的无符号整数”,然后读取更多字节以获取字符串 编辑 根据下面的评论,看来你不会使用C++ .NET,所以我认为你有两个选择。1)用C语言编写数据,以使C++能够读取C++(使用固定长度字符串)2)找出BIAN编写器(Wrad)()写入数据的方式,以便在C++中正确读取数据。 伪代码——我想是这样的。就像我在下面的评论中所说的,我的C++是生锈的,但是这是基本的算法应该是接近的。read from file int num - number of items
for (i=0;i<num;i++){
read int stringBytes - size of string
read string stringBytes bytes - the name
read int X4
create your struct and add to list/array/dictionary
}
从文件int num读取-项目数
对于(i=0;i而不是在另一个答案中解释的字符串数据类型问题,这里还有一件事。std::list
是一个双链接列表
,它本质上包含额外的指针,因此directfread/memcpy
可能无法提供您在c#snippet中存储的内容。您是否尝试过使用固定大小的缓冲区存储名称,而不是字符串?您的意思是使用textureAtlas.SpriteNames[i].ToCharArray()吗我的C++有点生疏了,但是我的答案是把每个元素分开来创建结构,然后把结构附加到列表中,而不是直接把它们读入列表,这显然是行不通的。@安德鲁。我希望你明白为什么他们不能像你那样工作。思考。单独读取每个元素是有意义的。我应该使用std::vector而不是std::list吗?@user1423893取决于您的目的。理想情况下,我希望最终得到一个std::map of std::string,用于键条目和矩形(x、y、宽度、高度)对于元素,在文档中^符号的含义是什么?例如,代码>文件安全> ^ /代码>二进制写程序使用McScLIB。这将不是当前平台的跨平台。 FielestRAM^ ^ /Cord>是C++特有的语法。我还没有使用C++ .NET,但基本上它是一个“托管”数据类型。
ifstream::pos_type size;
char *memblock;
ifstream file ("TextureAtlas0.txa", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char[size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
printf("File content is in memory");
delete[] memblock;
}
else
{
printf("Unable to open file");
}
read from file int num - number of items
for (i=0;i<num;i++){
read int stringBytes - size of string
read string stringBytes bytes - the name
read int X4
create your struct and add to list/array/dictionary
}