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 The filename is the name of the file that you want to delete.
If the remove()
function deletes the file succcessfully, it’ll return zero (0). Or it’ll return -1 on failture.
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:
Code language: C++ (cpp)The file test.txt was deleted.
In case the file test.txt
doesn’t exist or it is locked by another program, you’ll see the following message:
Code language: C++ (cpp)Error deleting the file test.txt.
Summary
- Use the C
remove()
function from the standard library to delete a file.