Summary: in this tutorial, you will learn how to use the C remove()
function to delete a file from the file system.
Introduction to the C remove() function #
The remove()
function is defined in the stdio.h
standard library. The remove()
function accepts a file name and deletes it from the file system.
Here’s the syntax of the remove()
function:
int remove(const char *filename);
Code language: C++ (cpp)
In this syntax, the filename is the file name you want to delete.
If the remove()
the function deletes the file successfully, returning zero (0). Or it’ll return -1 on failure.
C remove() function example #
The following example uses the remove()
function to remove the test.txt
file in the current working directory:
#include <stdio.h>
int main()
{
char *filename = "test.txt";
if (remove(filename) == 0)
printf("The file %s was deleted.", filename);
else
printf("Error deleting the file %s.", filename);
return 0;
}
Code language: C++ (cpp)
If you run the program and the test.txt
file exists, you’ll see the following message:
The file test.txt was deleted.
Code language: C++ (cpp)
In case the file test.txt
doesn’t exist or it is locked by another program, you’ll see the following message:
Error deleting the file test.txt.
Code language: C++ (cpp)
Summary #
- Use the C
remove()
function from the standard library to delete a file.