Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++binaryVC++
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
good
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)
 
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.
  Permalink  
Rate this: bad
good
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. Smile | :)
  Permalink  
Comments
Emilio Garavaglia at 5-Feb-13 2:38am
   
This is C, not C++
Albert Holguin at 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 at 5-Feb-13 2:44am
   
Albert's answer works with both C and C++.
Emilio Garavaglia at 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
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 895
1 OriginalGriff 523
2 thatraja 245
3 Abhinav S 243
4 Emre Ataseven 200
0 Sergey Alexandrovich Kryukov 8,142
1 OriginalGriff 4,665
2 Peter Leow 3,774
3 Maciej Los 3,515
4 Er. Puneet Goel 3,107


Advertise | Privacy | Mobile
Web02 | 2.8.140415.2 | Last Updated 5 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid