File handling in C++ allows us to create, read, update, and delete files from a program. To delete an existing file, C++ provides the remove() function, which removes a file from the file system.
- The
remove()function is defined in the<cstdio>header file. - It deletes a file specified by its relative or absolute path.
remove() Function in C++
The remove() function takes the path of the file as an argument and attempts to delete it.
Syntax of remove()
remove(char * path)
Parameters
- path: Relative or absolute path of the file to be deleted.
Return Value
- Returns 0 if the file is deleted successfully.
- Returns a non-zero value if an error occurs.
Program to Delete a File
The following program demonstrates how to delete a file named myfile.txt.
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
// Remove the file named "myfile.txt"
int status = remove("myfile.txt");
// Check if the file has been successfully removed
if (status != 0) {
perror("Error deleting file");
}
else {
cout << "File successfully deleted" << endl;
}
return 0;
}
Output
File successfully deletedExplanation
- The remove() function attempts to delete the file myfile.txt.
- If the operation succeeds, the program prints a success message.
- Otherwise, perror() displays the reason for the failure.
Important Points: While deleting files using remove():
- The file path can be either relative or absolute.
- The file should not be open in the current program or another application.
- The remove() function cannot delete directories.
- To remove a directory, use the rmdir() function.