gnik
asked on
how do you save data it disk?
I have a program which stores its data in a list. How can I go about saving the contents of the list to disk so that thay can be read in at a later date?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Actual code depends on the item in the list you want to serialize to and from the disk. I guess everything is clear. Sa you have a list with 5 items and you wrote functions WriteItem and ReadItem that write and read single item to the disk.
First you open a file. Assume you are programming in windows
FILE* stream;
if( (stream = fopen( "fread.out", "w+" )) != NULL )
{
int item_count = 5;
// write number of item first
fwrite( &item_count , sizeof( item_count ), 1, stream );
//write items themselves
for(int i = 0; i < item_count; i++)
{
WriteItem(i);
}
fclose( stream );
}
To read
FILE* stream;
if( (stream = fopen( "fread.out", "r+" )) != NULL )
{
int item_count;
// read number of item first
fread( &item_count , sizeof( item_count ), 1, stream );
// allocate memory block dinamically according to the number of //items stored in file
Item *pItem = (Item *)malloc(sizeof(Item) * item_count);
//read items themselves
for(int i = 0; i < item_count; i++)
{
// read single item into memory block
ReadItem(i, pItem + i);
}
fclose( stream );
}
First you open a file. Assume you are programming in windows
FILE* stream;
if( (stream = fopen( "fread.out", "w+" )) != NULL )
{
int item_count = 5;
// write number of item first
fwrite( &item_count , sizeof( item_count ), 1, stream );
//write items themselves
for(int i = 0; i < item_count; i++)
{
WriteItem(i);
}
fclose( stream );
}
To read
FILE* stream;
if( (stream = fopen( "fread.out", "r+" )) != NULL )
{
int item_count;
// read number of item first
fread( &item_count , sizeof( item_count ), 1, stream );
// allocate memory block dinamically according to the number of //items stored in file
Item *pItem = (Item *)malloc(sizeof(Item) * item_count);
//read items themselves
for(int i = 0; i < item_count; i++)
{
// read single item into memory block
ReadItem(i, pItem + i);
}
fclose( stream );
}
ASKER
Could you explain to me the actual process for getting the information to the disk.
Thanks.