remove file in c++
In C++, you can remove a file using the remove
function from the C Standard Library, which is included in the <cstdio>
header. The remove
function takes a single argument, which is the path to the file you want to delete, and it returns 0
if the file is successfully deleted or a non-zero value if an error occurs.
Here is an example of how to use the remove
function in C++:
#include <cstdio> // For the remove function
#include <iostream> // For std::cout and std::cerr
int main() {
const char* filePath = "path/to/your/file.txt";
if (remove(filePath) == 0) {
std::cout << "File successfully deleted.\n";
} else {
std::cerr << "Error deleting file.\n";
}
return 0;
}
<cstdio>
header is included for the remove
function, and <iostream>
is included for input/output operations.remove
function with the file path as an argument.remove
function. If it returns 0
, the file was successfully deleted. Otherwise, an error occurred.If you need more detailed error handling, you can use the errno
variable and the strerror
function to get a human-readable error message:
#include <cstdio>
#include <iostream>
#include <cerrno> // For errno
#include <cstring> // For strerror
int main() {
const char* filePath = "path/to/your/file.txt";
if (remove(filePath) == 0) {
std::cout << "File successfully deleted.\n";
} else {
std::cerr << "Error deleting file: " << strerror(errno) << '\n';
}
return 0;
}
In this example, if an error occurs, strerror(errno)
will provide a description of the error based on the value of errno
.