Re: writing to a binary file

From: CaptainJ (jeffseacrest_at_spamjam.bresnan.net)
Date: 09/13/04


Date: Sun, 12 Sep 2004 20:25:36 -0600


"Mike Wahler" <mkwahler@mkwahler.net> wrote in message
news:MM21d.1749$_G4.739@newsread3.news.pas.earthlink.net...
>
> "Tony Johansson" <johansson.andersson@telia.com> wrote in message
> news:Ka11d.103192$dP1.369761@newsc.telia.net...
> > Hello!
> >
> > I have this easy program. I write 234 to a binary file.
>
> Below, you write the characters '2', '3', and '4' to a
> file, in that order.
>
> > When I use an editor
> > and look at this file "test.out" I still see 234.
>
> Yes.
>
> >I should see only garbage
> > because I write to a binary file.
>
> But what did you write? :-) See below.
>
> > Can somebody explain to me why I can see
> > 234 when I write to a binary file. The number 234 in binary is
> > 0000000011101010.
>
> The << operators for numeric types are 'formatted output' operators.
> Each takes a binary value and inserts its textual representation
> into the stream.
>
> >
> > #include <iostream>
> > #include <fstream>
> > using namespace std;
> >
> > main()
>
> int main()
>
> > {
> > fstream f("test.out",ios::out|ios::binary);
> >
> > if (!f)
> > cout << "error";
> >
> > f << 234;
> > f.close();
>
> Redundant but innocuous. The stream will be automatically
> closed upon destruction when it goes out of scope.
>
and if you make the correction Mike suggested in the function declaration,
you should return an int:
return 0;

> > }
>
> If you want to write 'raw' binary data to a file,
> use std::ofstream::write().
>
> -Mike
>
CJ



Relevant Pages

  • Re: pipedstreams
    ... time readInt returns values that has never been written to the stream ... to put the wrapped streams into your Comm object. ... catch (IOException e){System.err.println("An error occured ... public synchronized void send(int dest, ...
    (comp.lang.java.programmer)
  • Re: Sending XML data via socket
    ... I looked int a link you have provided. ... // Get a stream object for reading and writing ... Resize the buffer, put in the byte we've just ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: adapting getline
    ... int getline; ... The function reads characters from the input stream stream and stores them ...
    (comp.lang.c)
  • Re: how to remove code duplication
    ... the log directory should containing the same files as the out ... exit(EXIT_FAILURE); ... int main ... void process_log_data(FILE *stream) ...
    (comp.lang.c)
  • Re: Why doesnt std::cin choke on this?
    ... when I was writing a user-driven test program for a data structure I ... You read an int. ... it simpler then checking the stream for it's ... read in a string, this becomes trivial. ...
    (comp.lang.cpp)