![]() |
VOOZH | about |
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++.
To remove a file in C++, we can use the 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.
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.
The below example demonstrates how we can remove a file named “myfile.txt” in C++.
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.