Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to delete a file
In programming, working with files is very important and every programming language has its own set of functions or library that help in manipulation of files. In C Programming Language, the remove() function can be used by the programmer to delete a file.
Syntax
int remove(const char *filename);
Parameters
The function accepts one parameter which is the name of the file that is to be deleted. File name can also be the path to the file but only if the system supports it.
- filename − A string containing the name of the file to be deleted
Return Value
It returns zero if the deletion operation is successfully completed, otherwise a non-zero value on failure.
Example
Note: Create a text file named "testfile.txt" in your current directory before running this program.
#include <stdio.h>
int main() {
int result = remove("testfile.txt");
if (result == 0) {
printf("The file is deleted successfully
");
} else {
printf("Error: Unable to delete the file
");
}
return 0;
}
Output
The file is deleted successfully
Example: Error Handling
Here's an example that demonstrates proper error handling when the file doesn't exist −
#include <stdio.h>
int main() {
const char *filename = "nonexistent.txt";
int result = remove(filename);
if (result == 0) {
printf("File '%s' deleted successfully
", filename);
} else {
printf("Error: Could not delete file '%s'
", filename);
printf("File may not exist or you may not have permission
");
}
return 0;
}
Output
Error: Could not delete file 'nonexistent.txt' File may not exist or you may not have permission
Key Points
- The
remove()function is defined in<stdio.h>header file - Always check the return value to handle errors properly
- The file must exist and you must have proper permissions to delete it
- Once deleted, the file cannot be recovered using this function
Conclusion
The remove() function in C provides a simple way to delete files programmatically. Always implement proper error checking to handle cases where file deletion might fail due to permissions or file not existing.
