Deleting Files
Feb 15, 2016 at 9:07am UTC
Hello, forum. I am trying to create save data in a text file for a text-based game I'm making. I already have saving/loading down, but for some reason I can't delete the save file if the user decides to. I'm trying to use
remove(const char *)
, but with no luck. Any quick advice? I'm not the strongest programmer yet, if it hasn't become clear by now..
This is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
void delete_data(){
fstream file_to_del(set_path(), ios::trunc);
const char * filename = set_path().c_str();
string data;
cin.get();
if (file_to_del){
if (remove(filename) == 0){
cout<<"Delete Successful!\n" ;
cin.get();
}
else {
perror("Error deleting file...\n" );
cin.get();
}
}
else {
cout<<"Error deleting file...\n" ;
cin.get();
}
}
the function
set_path()
returns the path name as a string.
Last edited on Feb 15, 2016 at 9:09am UTC
Feb 15, 2016 at 9:24am UTC
You probably should close the file stream before trying to remove the file.
Feb 15, 2016 at 10:01am UTC
Peter, you mean like this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
void delete_data(){
fstream file_to_del(set_path(), ios::trunc);
const char * filename = set_path().c_str();
string data;
cin.get();
if (file_to_del){
file_to_del.close(); //closing stream
if (remove(filename) == 0){
cout<<"Delete Successful!\n" ;
cin.get();
}
else {
perror("Error deleting file...\n" );
cin.get();
}
}
else {
cout<<"Error deleting file...\n" ;
cin.get();
}
}
Because this doesn't change my results
Feb 15, 2016 at 10:49am UTC
Nevermind, I figured it out. ios::trunc was giving me problems, and then You were right to close the stream first, Peter. Thanks for the advice!
Topic archived. No new replies allowed.