【发布时间】:2009-10-06 13:26:03
【问题描述】:
我已经用 C# 中的 BinaryWriter 将几个整数、char[] 等写入数据文件。使用 BinaryReader(在 C# 中)读回文件,我可以完美地重新创建文件的所有部分。
但是,尝试使用 C++ 重新读取它们会产生一些可怕的结果。我正在使用 fstream 尝试读回数据,但数据未正确读入。在 C++ 中,我使用 ios::in|ios::binary|ios::ate 设置了一个 fstream,并使用 seekg 定位我的位置。然后我读取了接下来的四个字节,它们被写为整数“16”(并正确读取到 C# 中)。这在 C++ 中读取为 1244780 (不是内存地址,我检查了)。为什么会这样? C++ 中是否有与 BinaryReader 等价的东西?我注意到它在 msdn 上提到过,但那是 Visual C++,而智能感知在我看来甚至不像 C++。
编写文件的示例代码(C#):
public static void OpenFile(string filename)
{
fs = new FileStream(filename, FileMode.Create);
w = new BinaryWriter(fs);
}
public static void WriteHeader()
{
w.Write('A');
w.Write('B');
}
public static byte[] RawSerialize(object structure)
{
Int32 size = Marshal.SizeOf(structure);
IntPtr buffer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(structure, buffer, true);
byte[] data = new byte[size];
Marshal.Copy(buffer, data, 0, size);
Marshal.FreeHGlobal(buffer);
return data;
}
public static void WriteToFile(Structures.SomeData data)
{
byte[] buffer = Serializer.RawSerialize(data);
w.Write(buffer);
}
我不确定如何向您展示数据文件。
读回数据示例(C#):
BinaryReader reader = new BinaryReader(new FileStream("C://chris.dat", FileMode.Open));
char[] a = new char[2];
a = reader.ReadChars(2);
Int32 numberoffiles;
numberoffiles = reader.ReadInt32();
Console.Write("Reading: ");
Console.WriteLine(a);
Console.Write("NumberOfFiles: ");
Console.WriteLine(numberoffiles);
这是我想用 C++ 来执行的。初始尝试(在第一个整数处失败):
fstream fin("C://datafile.dat", ios::in|ios::binary|ios::ate);
char *memblock = 0;
int size;
size = 0;
if (fin.is_open())
{
size = static_cast<int>(fin.tellg());
memblock = new char[static_cast<int>(size+1)];
memset(memblock, 0, static_cast<int>(size + 1));
fin.seekg(0, ios::beg);
fin.read(memblock, size);
fin.close();
if(!strncmp("AB", memblock, 2)){
printf("test. This works.");
}
fin.seekg(2); //read the stream starting from after the second byte.
int i;
fin >> i;
编辑:似乎无论我在哪个位置使用“seekg”,我都会收到完全相同的值。
【问题讨论】:
-
你能给我们展示一段代码(或整个代码)和一个二进制文件的例子吗?
-
我已经发布了一些代码。不确定我可以将二进制文件上传到哪里。
-
您在 C# 阅读器中阅读 chris.dat,在 C++ 阅读器中阅读 datafile.dat...
-
@Andy,名称差异只是我来回测试的结果。
-
尝试只写一个 int 以避免担心字符大小。把它写出来,看看你能不能读出来,然后用十六进制编辑器报告文件的样子。
标签: c# c++ file-io binaryfiles binaryreader