Article View: gnu.g++.help
Article #400Read and write binary file
From: Guishen Wang
Date: Wed, 30 Sep 1992 05:33
Date: Wed, 30 Sep 1992 05:33
73 lines
2618 bytes
2618 bytes
I am working on a project with G++. When I try to stream
a object into file, I find some member function of iostrem does
not work correctly.
First I wrote 2 objects into file then read them back.
Everything is wrong. I want know where this bug come from?
from my code ? or from the compiler?
Please send me mail and tell me what is wrong ASAP, because I can
not make any progress on my project before this is done.
I appreciate your time!
the following is the code and output:
#include <std.h>
#include <fstream.h>
#include <iostream.h>
class people{
public:
char name[20];
long ssn;
people(char *n,long num){ memset (name,0,20);strcpy(name,n);}
};
int main()
{ people p0("",0);
people p1("joe",12342);
people p2("jery",345435);
ofstream out("file");
out.write((char *)&p1,sizeof(p1));
out.write((char *)&p2,sizeof(p2));
long pos=out.tellp();
cout<<"position after write 2 people="<< pos<<"\n";
out.close();
ifstream input("file");
input.read((char *)&p0,sizeof(p0));
cout << "This is what is red from the file : "<< p0.name <<" "<<p0.ssn<<"\n";
return 0;
}
mayall% g++ -v cpptest.cc
Reading specs from /local/gnu/lib/gcc/sparc-sun-sunos4.1.1/2.1/specs
gcc version 2.1
/local/gnu/lib/gcc/sparc-sun-sunos4.1.1/2.1/cpp -lang-c++ -v -undef -D__GNUC__=
2 -D__GNUG__=2 -D__cplusplus -Dsparc -Dsun -Dunix -D__sparc__ -D__sun__ -D__unix
__ -D__sparc -D__sun -D__unix cpptest.cc /usr/tmp/cc021848.i
GNU CPP version 2.1 (sparc)
/local/gnu/lib/gcc/sparc-sun-sunos4.1.1/2.1/cc1plus /usr/tmp/cc021848.i -quiet
-dumpbase cpptest.cc -version -o /usr/tmp/cc021848.s
GNU C++ version 2.1 (sparc) compiled by GNU C version 2.1.
as -o cpptest.o /usr/tmp/cc021848.s
/local/gnu/lib/gcc/sparc-sun-sunos4.1.1/2.1/ld -e start -dc -dp /lib/crt0.o -L/
local/gnu/lib/gcc/sparc-sun-sunos4.1.1/2.1/ -L/local/gnu/lib/ cpptest.o -lg++ -l
gcc -lc -lgcc
mayall% a.out
position after write 2 people=0
This is what is red from the file : jjoe 0
(the position should be a number greater than 0)
(the output "jjoe 0 "should be "joe 12342")
Technical Details
Message-ID:
<1992Sep30.053354.22944@unlv.edu>Path:
arc1-ca.pugleaf.net!sparky!uunet!nevada.edu!jimi!lonnie-mack.cs.unlv.edu!gswangShow Full Headers
Complete Article Headers
Newsgroups: gnu.g++.help Path: arc1-ca.pugleaf.net!sparky!uunet!nevada.edu!jimi!lonnie-mack.cs.unlv.edu!gswang From: gswang@lonnie-mack.cs.unlv.edu (Guishen Wang) Subject: Read and write binary file Message-ID: <1992Sep30.053354.22944@unlv.edu> Keywords: iostream Sender: news@unlv.edu (News User) Reply-To: gswang@lonnie-mack.cs.unlv.edu (Guishen Wang) Organization: UNLV Computer Science and Electrical Engineering Date: Wed, 30 Sep 92 05:33:54 GMT Lines: 74