Binary file handling

I m working on a small library management project (console) which has binary file i/o.

When i save a structure to a file (.bin) and try 2 read it -> it works fine (till the console is closed).

Once the console is re-opened, read is absurd and weird. Pls help to solve this..


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class date {
            public:
                int d,m,y;

                void setDate(int date,int month,int year) {
                    d=date<31?date:01;
                    m=month<12?month:01;
                    y=year>=2012?year:2012;
                }

        };

        struct iBook {
            char title[200],author[200],genre[50];
            date iDate,rDate;
        };

fstream tempStream

tempStream.open(stufile,ios::in|ios::binary);
tempStream.read((char*)tempBook,sizeof(tempBook));
tempStream.close();


P.S. I initialised iBook properly and saved using

f1.write((char*)&b,sizeof(b))

(b is an instance of iBook and f1 is a fstream)

PLS help !!
edit your line 20

add 1 more |

it should be
 
ios::in || ios::binary


this is just smaller mistake.
dere comes only one |, i m sure .. n compiler too generates an error...
It's a bitwise operation, not logical -> therefore one | is correct.

On the topic: what do you mean by absurd and weird? How do you run your code? Which compiler/OS do you use?

This line looks weird:tempStream.read((char*)tempBook,sizeof(tempBook));. If tempBook is a pointer - then the sizeof will return 4 and too few data will be read. If tempBook is an instance - then the conversion to char* should fail .
Ohh!! My bad...

i declared tempBook as pointer...

i m nw using
tempStream.read((char*)&tempBook,sizeof(tempBook));

with tempBook as a normal instance of iBook, it works just perfect...

Thanks a ton...
Topic archived. No new replies allowed.