 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Guest
|
Posted: Sun Nov 05, 2006 8:49 pm Post subject: reading struct from file doesn't work subsequent times - hel |
|
|
This code doesn't work - the first retrieval of t2 returns valid data,
the subsequent do not. Please help!!!
int main(int argc, char* argc){
struct Test{
int i;
int j;
intk;
int l;
}
Test Test1;
Test1.i = 99;
Test1.j = 777;
Test1.k = 12345;
Test1.l = 876;
fstream fout;
fout.open("test.txt", ios::out);
for (int i=0; i<10; i++)
fout.write(reinterpret_cast<char*>(&Test1), sizeof(Test));
fout.close();
fstream fin;
fin.open(test.txt", ios::in);
for(int i=0; i<10; i++){
char c[sizeof(Test)];
fin.get(c, sizeof(Test));
Test t2;
// === THIS COPY OF t2 CONTAINS CORRECT DATA FIRST TIME BUT NOT
SUBSEQUENT
// TIMES!!!!!!!!!
memcpy(&t2, c, sizeof(Test));
}
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ] |
|
| Back to top |
|
 |
Alberto Ganesh Barbati Guest
|
Posted: Mon Nov 06, 2006 3:57 am Post subject: Re: reading struct from file doesn't work subsequent times - |
|
|
paul.anderson (AT) jhuapl (DOT) edu ha scritto:
| Quote: | This code doesn't work - the first retrieval of t2 returns valid data,
the subsequent do not. Please help!!!
int main(int argc, char* argc){
struct Test{
int i;
int j;
intk;
int l;
}
Test Test1;
Test1.i = 99;
Test1.j = 777;
Test1.k = 12345;
Test1.l = 876;
fstream fout;
fout.open("test.txt", ios::out);
|
As you are apparently going to write binary data, you should add the
ios::binary flag. BTW, for output-only streams, it usually better to use
ofstream instead of fstream, the difference being that the former
doesn't derive from basic_istream, so you can't apply input operations
by mistake.
| Quote: |
for (int i=0; i<10; i++)
fout.write(reinterpret_cast<char*>(&Test1), sizeof(Test));
fout.close();
fstream fin;
|
Ditto. You should definitely add ios::binary and you could use ifstream
instead of fstream.
| Quote: | fin.open(test.txt", ios::in);
for(int i=0; i<10; i++){
char c[sizeof(Test)];
fin.get(c, sizeof(Test));
|
You should used read(), not get(), up there. get() is meant for textual
input and will stop after extracting a "\n".
| Quote: | Test t2;
// === THIS COPY OF t2 CONTAINS CORRECT DATA FIRST TIME BUT NOT
SUBSEQUENT
// TIMES!!!!!!!!!
memcpy(&t2, c, sizeof(Test));
}
}
|
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ] |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|