How to delete a file in file handling in c++
In c++17
we have the filesystem library, which gives the tools to easily deal with the problem.
Example:
#include <filesystem>
#include <iostream>
#include <string>
int main()
{
std::string searchfilename;
std::cout << "Please enter the filename to be searched\n";
std::cin >> searchfilename;
try {
if (std::filesystem::remove(searchfilename))
std::cout << "file " << searchfilename << " deleted.\n";
else
std::cout << "file " << searchfilename << " not found.\n";
}
catch(const std::filesystem::filesystem_error& err) {
std::cout << "filesystem error: " << err.what() << '\n';
}
}
When you try to delete a file, you should always handle the return value of remove function immediately. For successful result it returns 0
and for failed, it returns non-zero.
const int result = remove( "no-file" );
if( result == 0 ){
printf( "success\n" );
} else {
printf( "%s\n", strerror( errno ) ); // No such file or directory
}
remove
is in the stdio.h
file
and strerror
is in the string.h
So after your remove
function, check to see for what reason it has not been deleted.
The error number is stored in errno
variable and strerror
can map the error number to a string that tells the reason of failure.
Also you can test the error code and a Linux Terminal if you have it using perror
command
> perror 0
OS error code 0: Success
> perror 1
OS error code 1: Operation not permitted
> perror 2
OS error code 2: No such file or directory
> perror 3
OS error code 3: No such process
> perror 4
OS error code 4: Interrupted system call
> perror 5
OS error code 5: Input/output error
You forgot closing the file that you have opened. So, CLOSE the file and it should work.
Note: The solution worked for @AkhileshSharma and included the comment as an answer to close the question as answered.