The C library remove(const char *filename) function deletes the given filename so that it is no longer accessible.
SyntaxFollowing is the C library syntax of the remove() function −
remove(const char *filename);Parameters
This function takes only a single parameter −
The function returns 0 if the file is successfully deleted.It returns a non-zero value if an error occurs. In case of an error, errno is set to indicate the specific error code, which can be used to determine the cause of the failure.
Common Error codesThis example creates a file named example1.txt and then successfully deletes it using the remove function.
Below is the illustration of the C library remove() function.
#include <stdio.h> int main() { const char *filename = "example1.txt"; // Create a file to be deleted FILE *file = fopen(filename, "w"); if (file) { fprintf(file, "This is a test file.\n"); fclose(file); } // Attempt to remove the file if (remove(filename) == 0) { printf("File %s successfully deleted.\n", filename); } else { perror("Error deleting file"); } return 0; }Output
The above code produces following result−
File example1.txt successfully deleted.Example 2: Deleting a File Without Permission
This example simulates attempting to delete a file without the necessary permissions, resulting in a permission denied error.
#include <stdio.h> #include <errno.h> int main() { const char *filename = "protectedfile.txt"; // Create a file to be deleted FILE *file = fopen(filename, "w"); if (file) { fprintf(file, "This is a test file with restricted permissions.\n"); fclose(file); } // Simulate restricted permissions (actual permission setting code omitted for simplicity) // Attempt to remove the file if (remove(filename) == 0) { printf("File %s successfully deleted.\n", filename); } else { perror("Error deleting file"); } return 0; }Output
After execution of above code, we get the following result
Error deleting file: Permission denied
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4