如何在c ++中输入/输出二进制文件? [英] how to Input/output binary in c++?

查看:311
本文介绍了如何在c ++中输入/输出二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何输入/输出存储在我硬盘中的二进制文件。

我也想编辑二进制文件。

解决方案

使用C ++标准库,您必须构造(或打开) std :: fstream 给出适当的模式标志( ios_base :: binary



请参阅 http://en.cppreference.com/w/cpp/io/basic_fstream/basic_fstream [ ^ ]



之后,只使用未格式化的i / o方法(如 istream :: read ostream :: write )避免<<和>> oprators(除非你总是需要输出的文本表示,尽管没有行尾翻译。


嗯,你对待二进制文件(差不多)就像你使用任何其他类型的如果您使用 fopen ,只需在模式中添加一点 b 告诉它你是以直接二进制模式工作(请参阅此处 [ ^ ])。



至于处理内部一旦文件打开你的代码,好吧,你必须知道一次要读取多少字节...然后你基本上把这些字节转换成有意义的东西并解释它们。这可以通过几种不同的方式完成。请参阅 fgets 的文档[ ^ ]和 fread [ ^ ]。



用二进制写,它与读取几乎相同,但顺序相反。

获取变量并将它们加载到缓冲区字节 - >以二进制模式打开文件写入 - >写出你的缓冲区数据



希望这至少会把你拉向正确的方向......快乐的编码。 :)

How to input/output binary of files those are stored in my hard disk.
I also want to edit binary.

解决方案

Using the C++ standard library, you have to construct (or open) an std::fstream giving the appropriate mode flags (ios_base::binary)

See http://en.cppreference.com/w/cpp/io/basic_fstream/basic_fstream[^]

After that, use only unformatted i/o methods (like istream::read and ostream::write) avoiding the << and >> oprators (unless you want always a textual representation of the output, although without end-of line translation.


Well, you treat binary files (almost) the same as you would any other type of file. If you use fopen, just add that little "b" in the mode to tell it you''re working in straight binary mode (see here[^]).

As far as handling it within your code once the file is open, well, you have to know how many bytes to read at a time... then you essentially cast those bytes onto something that makes sense and interpret them. This can be done in a few different ways. See documentation for fgets[^] and fread[^].

To write in binary, it''s pretty much the same thing as reading but in reversed order.
Take variables and load them to buffer bytes->Open file in binary mode to write->Write out your buffered data

Hope this at least kicks you in the right direction... happy coding. :)


这篇关于如何在c ++中输入/输出二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆