Delete a File in C++
To remove a file in C++, we can use the remove() function defined inside the <stdio.h> header file. The remove() function takes the path of the file as a string argument and deletes the file.
Syntax of remove()
remove(char * path)
where the path is the relative or even absolute path to the file.
If the function returns zero, the file has been successfully deleted. If the function returns a non-zero value, an error occurs.
C++ Program to Remove a File
The below example demonstrates how we can remove a file named “myfile.txt” in C++.
// C++ program to demonstrate how to remove a file
#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 deleted
Time Complexity: O(1), as file removal is a constant time operation.
Auxilliary Space: O(1)
Explanation: The above code attempts to delete the file named “myfile.txt”. If file is removed successfully, it prints “File successfully deleted”. Otherwise, it prints an error message.
Note: The remove() function will not delete a directory. To delete a directory, we need to use the rmdir() function. Also, always ensure that the file is not open in your program or another program before attempting to delete it.
How to Delete a File in C++?
C++ file handling allows us to manipulate external files from our C++ program. We can create, remove, and update files using file handling. In this article, we will learn how to remove a file in C++.
Contact Us