Click here to Skip to main content
13,588,681 members
Rate this:
Please Sign up or sign in to vote.
See more:
How to input/output binary of files those are stored in my hard disk.
I also want to edit binary.
Posted 4-Feb-13 19:13pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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


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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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. :)
Emilio Garavaglia 5-Feb-13 2:38am
This is C, not C++
Albert Holguin 5-Feb-13 11:26am
True... but it works... and that was the first thing that came to mind. At least he has options and he can see it's really not that difficult.
H.Brydon 5-Feb-13 2:44am
Albert's answer works with both C and C++.
Emilio Garavaglia 5-Feb-13 7:24am
I've no doubt it works, but that's not C++, since it refers to functions belonging to the C standard library and not to the C++ one. It works because of backward compatibility, but if everything "works with both C and C++" there is no clue to have C++ at all.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web03-2016 | 2.8.180615.1 | Last Updated 5 Feb 2013
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100