How to Delete a File in C: Simple Guide with Examples
In C, you can delete a file using the
remove() function by passing the file name as a string. It returns 0 on success and a non-zero value if the file cannot be deleted.Syntax
The remove() function deletes a file specified by its name. It is declared in stdio.h. The function returns 0 if the file is deleted successfully, otherwise it returns a non-zero value indicating an error.
filename: The name of the file to delete, as a string.
c
int remove(const char *filename);
Example
This example shows how to delete a file named example.txt. It checks if the deletion was successful and prints a message accordingly.
c
#include <stdio.h> int main() { const char *filename = "example.txt"; int result = remove(filename); if (result == 0) { printf("File '%s' deleted successfully.\n", filename); } else { perror("Error deleting file"); } return 0; }
Output
File 'example.txt' deleted successfully.
Common Pitfalls
Common mistakes when deleting files in C include:
- Trying to delete a file that does not exist, which causes
remove()to fail. - Not checking the return value of
remove(), so errors go unnoticed. - Using incorrect file paths or names, especially on different operating systems.
- Trying to delete a file that is open or locked by another process.
Always check the return value and use perror() to get error details.
c
/* Wrong way: Not checking return value */ remove("nonexistent.txt"); /* Right way: Check return value and handle error */ if (remove("nonexistent.txt") != 0) { perror("Failed to delete file"); }
Quick Reference
| Function | Purpose | Return Value |
|---|---|---|
| remove(const char *filename) | Deletes the specified file | 0 on success, non-zero on failure |
| perror(const char *message) | Prints error message related to last error | None |
Key Takeaways
Use
remove() with the file name to delete a file in C.Always check the return value of
remove() to handle errors.Use
perror() to print detailed error messages when deletion fails.Ensure the file exists and is not open or locked before deleting.
File paths must be correct and consider the operating system's format.