PDA

View Full Version : c++ problem: overwriting a file


Karim
02-12-2005, 02:03 AM
I'm ouputting the contents of a linked list to a file. It works when there is no existing file. However, when a file already exists with valid content, I can import the data to a linked list, I can modify and display the contents which correctly amends the list but it won't write the modified list to file.


void write_list(ofstream &data, To_Do_Item_Ptr head)
{
To_Do_Item_Ptr temp = head;

while (head != NULL)
{
data << head -> desc << endl;
temp = temp -> next;

if (temp != NULL && (head -> priority > temp -> priority))
{
data << endl;
}
head = head -> next;
}

data.close();
}


Tracing through the while loop, it iterates the correct number of times so it looks like the data is being written to file but no such luck...

Karim
02-12-2005, 02:16 AM
It turns out data was never actually opened unless it didn't exist in the directory... I thought another function had already taken care of it.

Cool...

Karim
02-12-2005, 04:05 AM
Hmm...

adding data.open("filename") enables me to overwrite to an existing file but removes the ability to create a file when none exists...

Karim
02-12-2005, 04:51 AM
quadruple dola.. that's a first...

It turns out if the file existed, the output stream was never opened and vice versa.

I'm not sure how I fixed it but it works now...

For those more skilled than me, isn't it better (safer) to use a fstream when reading/writing to the same file? In this case they were separated because all the reading was done first, stored in a list, and then written to file.

gstelmack
02-12-2005, 03:23 PM
This all depends on how you were opening "data". You can specify modifiers that determine if you overwrite the file, append to the file, etc. Check the working directory as well, maybe you have extra files elsewhere now...