Delete a File Using remove() in C
A simple C program that deletes a file using the remove() function from <stdio.h>. It prompts the user for a filename and reports success or failure.
#include <stdio.h>
int main() {
char filename[100];printf("Enter the file name to delete: ");
scanf("%s", filename);if (remove(filename) == 0) {
printf("File %s deleted successfully. ", filename);
} else {
perror("Error deleting file");
}return 0;
}
How It Works?
- #include <stdio.h> — Provides remove() and perror().
- char filename[100]; — Buffer to store the filename entered by the user.
- scanf("%s", filename); — Reads the filename (no spaces).
- remove(filename) — Deletes the file. It returns 0 on success and a non-zero value on failure.
- perror("Error deleting file") — Prints the system error message if deletion fails (e.g., file not found or permission denied).
Example Run:
Enter the file name to delete: test.txt File notest.txt deleted successfully.
Note: The remove() function deletes files but cannot remove non empty directories. To delete directories, use rmdir() (POSIX). Always confirm with the user before deleting files in real programs.