Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to input/output binary of files those are stored in my hard disk.
I also want to edit binary.
Posted

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.
 
Share this answer
 
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. :)
 
Share this answer
 
Comments
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900