简体   繁体   English

用C ++和C#写入二进制文件

[英]Writing to binary file in C++ and C#

I have 2 applications. 我有2个应用程序。 One in C++ (windows) open a binary file and only reads from it, i use: 在C ++中(Windows)打开一个二进制文件,仅从其中读取,我使用:

fstream m_fsDataIN.open("C:\TTT", ios::in | ios::binary | ios::app);

and the second application (is in C#) opens the file and writes to it. 第二个应用程序(在C#中)打开文件并写入文件。 I use: 我用:

byte[] b = ... //have a binary data
System.IO.BinaryWriter bw = new System.IO.BinaryWriter(
                        System.IO.File.Open(@"C:\TTT",
                        System.IO.FileMode.Append,
                        System.IO.FileAccess.Write,
                        System.IO.FileShare.ReadWrite));
bw.Write(b);
bw.Flush();
bw.Close();

The problem is that the 8 first bytes are written incorrectly, comparing to what appears in the b array. 问题是,与b数组中出现的内容相比,前8个字节的写入不正确。

When I open the file in the C# application, using System.IO.FileMode.Append it works OK. 当我在C#应用程序中打开文件时,使用System.IO.FileMode.Append可以正常运行。

I checked in the application and it writes wrong 8 bytes. 我检查了应用程序,它写入了错误的8个字节。

I want to add that the first 8 bytes are 2 counters that each was created using IPAddressHostToNetworkAddress . 我想补充一下,前8个字节是2个计数器,每个计数器都是使用IPAddressHostToNetworkAddress创建的。

I think that the problem is in the C++ application, in how I open the file. 我认为问题出在C ++应用程序中,如何打开文件。

Help, Thnaks 帮助,感谢

You've opened it just fine. 您已经打开它就好了。 But how do you read it? 但是你怎么读呢? I think you need to call ntohl on the C++ side. 我认为您需要在C++方面调用ntohl

The problem was in the C++ application. 问题出在C ++应用程序中。 The program contained configuration which produced another file handler. 该程序包含配置,该配置产生了另一个文件处理程序。 Using Process Explorer I found out about it. 使用Process Explorer,我发现了这一点。 Removing the configuration of that extra file handler resolved the problem. 删除该额外文件处理程序的配置可以解决该问题。

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

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