-
c++ i/o question
experiencing some difficulties implementing the c++ i/o functions from fstream.h.....basically i've struggled to find some good examples of these functions in practical use.
ie what i want to do is check if a file exists....if so, load a struct data type from it...make changes ....then save it back to the file.
if it doesnt exist...i want it created and a struct data type initiliased (to zero) then saved back to the file.
example:
database dbase; //where database is a structure with int members and so on
ifstream FilePresent("testfile.dat");
if (!FilePresent){ ...create file, initiliase struct database to zero and write to file then close}
else if the file exists.....then load data off disk into dbase
ifstream GetFile("testfile.dat");
GetFile.read(&dbase,sizeof(database)); //ie load struct from file into dbase
GetFile.close();
{ ....make changes to working copy of dbase....}
//have finished ...now copy modified struct dbase back to file
ofstream CloseFile("testfile.dat");
CloseFile.write(&dbase,sizeof(database));
CloseFile.close();
the problem im experiencing is that the updated data is not being written to disk...ie everytime i run the program all the data is initialised to zero. so im thinking that the syntax to write a structure to disk ie
CloseFile.write(&dbase,sizeof(database)) ...is incorrect or my logic is flawed.
can someone point out what im doing wrong and is there a simple solution to go about loading data(especially a class or sruct) from a file into a program then back to the file after the completion of the program.
many thanks
-
To write to an already existing file without deleting the already present data you can do 2 things
1) if you use ofsteram() :
create new file
copy present data to new file
write new data to new file
delete old file
2) if you use fstream() :
use ios::app - it will add data to the end of the file without
overwriting.
EG:
Code:
--
--
fstream f1;
f1("testfile.dat",ios::app)
f1<<"THIS IS THE FIRST LINE\n";
f1.close()
--
--
//some other code
--
--
f1("testfile.dat",ios::app)
f1<<"THIS IS THE SECOND LINE\n";
f1.close()
--
--
now when you open the .dat file you'll see both the lines in it.
hope it helps.