Group
File Management in C++
Objective
1. Prompt the user to enter the name of the file to be deleted.
2. Use the `remove()` function to attempt to delete the file.
3. Check the return value of `remove()` to determine if the operation succeeded.
4. Display a message indicating whether the file was deleted or if an error occurred.
Create a program that deletes a specific file.
Example C++ Exercise
Show C++ Code
#include <iostream> // For input and output
#include <cstdio> // For using the remove() function
#include <string> // For using the string class
using namespace std;
int main() {
string filename; // Variable to store the name of the file to delete
// Ask the user to enter the filename
cout << "Enter the name of the file to delete: ";
getline(cin, filename); // Read the full filename from user input
// Attempt to delete the file using the remove() function
if (remove(filename.c_str()) == 0) {
// If remove() returns 0, the file was successfully deleted
cout << "File deleted successfully." << endl;
} else {
// If remove() returns a non-zero value, an error occurred
cout << "Error: Unable to delete the file. It may not exist." << endl;
}
return 0; // End of program
}
Output
//Output Example:
Enter the name of the file to delete: example.txt
File deleted successfully.
//Or in case of error:
Enter the name of the file to delete: missing.txt
Error: Unable to delete the file. It may not exist.