FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


Binary file i/o in c++





shashwatblack
Code:

            //I have a file 'data.dat' with 'max' number of objects of class 'info'
            //I want to remove the 'n'th object element from the file
            fstream file;
            file.open("data.dat", ios::out | ios::in | ios::binary);
            fstream newfile;
            //some code
            newfile.open("newfile.dat", ios::out | ios::in | ios::binary);
            for (int i=0; i<max; i++)
            {
                file.read(reinterpret_cast<char*>(&obj), sizeof(info));
                if (i == n - 1) continue;
                newfile.write(reinterpret_cast<char*>(&obj), sizeof(info));
            }
            file.close();  newfile.close();
            if (remove("data.dat") !=0 ) return 1;
            if (rename("newfile.dat", "data.dat") != 0) return 1;
            file.open("data.dat", ios::out | ios::in | ios::binary);
            //more code


my problem is that this messes up data.dat into garbage.. into numbers like '2001285887'. And all the others are the same value as well.. it's just a repetition of long nummbers.. But this does reduce the number of elements, that is if i had 10 objects previously, after the edit only 9 remain..
so where am i going wrong? please help...

Also, how do you replace an existing file during opening using fstream?
i'm using
Code:
ofstream("newfile.dat").close(); fstream newfile("newfile.dat");

and it works well, but there has to be a better, simpler way..
Peterssidan
I usually don't use fstream so I'm not sure but I think the problem is that when you specify ios::in the file will not be created if it doesn't exist. I prefer using ifstream (to read from file) and ofstream (to write to file) because you don't have to pass so many flags. It is possible to pass the open arguments to the constructor instead and save one line.
Code:
ifstream file("data.dat", ios::binary);
ofstream newfile("newfile.dat", ios::binary);


Quote:
Also, how do you replace an existing file during opening using fstream?

Not sure exactly what you mean. The old file will be replaced automatically when you write to it except if you pass ios::app or ios::ate, or is the default behaviour of fstream different from ofstream? Maybe you need to pass ios::trunc.
Related topics
Reply to topic    Frihost Forum Index -> Scripting -> Others

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.