I have problem with remove() function
First, look at the example and you will see the problem
cout << "Please enter the phone number to remove" << endl << "Phone number: ";
string rphNumber;
cin >> rphNumber;
ifstream ifile("db/" + rphNumber + ".txt");
if(ifile)
remove(("db/" + rphNumber + ".txt").c_str()); // the problem here
else
cout << "failure" << endl;
The problem in this line (the file path), always the function return -1 Although the file exists
remove(("db/" + rphNumber + ".txt").c_str());
Your problem may be that you still have
ifileopen at the point where you try to remove it. Some operating systems don’t let you delete a file that’s open. Another possibility is that the stringrphNumbermight have a newline at the end which you need to strip off before assembling the filename. (I don’t remember ifcindoes that or not.)Your problem definitely is that you are trying to find out if a filesystem operation will work. You can’t do that. In between when you make the test and when you actually try to do the operation, another process may change things so that the operation won’t work, even though your test said it will. Also, being able to open a file is not the same as being able to delete a file; there are probably lots of files on your hard drive that you can open but not delete (such as
/dev/null).You have to just do the filesystem operation. It will tell you if it worked or not, with its return value. Then, when it doesn’t work, you look at
errnoto find out why. The C utility functionstrerror(include<cstring>) will convert anerrnovalue to a human-readable error message.Putting it together, here’s the correct way to write your program:
Incidentally, never use
endl; if'\n'doesn’t work, it means your streambufs are not configured correctly.